code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import logging import boto3 from botocore.stub import Stubber from django.test import TestCase from django.contrib.auth import get_user_model from django.core.cache import caches from rest_framework.response import Response from rest_framework.test import APIRequestFactory from rest_framework.views import APIView from drftoolbox import views, authentication class KMSSecretAPISignatureAuthentucation(authentication.BaseKMSSecretAPISignatureAuthentication): client = boto3.client('kms', region_name='us-east-1') cache_timeout = 5 def get_aws_kms_arn(self): return 'ARN' def get_user(self, api_key): return get_user_model().objects.get(username=api_key) class UserKMSKeyView(views.BaseUserKMSKeyView): def http_sign_class(self): return KMSSecretAPISignatureAuthentucation class BaseUserKMSKeyView(TestCase): def setUp(self): self.stubber = Stubber(KMSSecretAPISignatureAuthentucation.client) caches['default'].clear() def test_inactive_user_key(self): user = get_user_model().objects.create_user('test', is_active=False) req = APIRequestFactory().get('/user-key/{}'.format(user.pk)) resp = UserKMSKeyView.as_view()(req, pk=user.pk) assert resp.status_code == 404 def test_user_key(self): user = get_user_model().objects.create_user('test') self.stubber.add_response('encrypt', {'CiphertextBlob': b'kms-key'}) self.stubber.activate() req = APIRequestFactory().get('/user-key/{}'.format(user.pk)) resp = UserKMSKeyView.as_view()(req, pk=user.pk) assert resp.status_code == 200 assert resp.data['encrypted_key'] is not None assert resp.data['expiry'] is not None class LoggingView(views.RequestLoggingViewMixin, APIView): def post(self, request): return Response('ok') class TestRequestLoggingViewMixin(): def test_obfuscate(self): mixin = views.RequestLoggingViewMixin val = 'jwt ajwttokenvalue' assert mixin.obfuscate(val) == 'jwt aj...' val = 's=svalueincookie; t=tvalueincookie' assert mixin.obfuscate(val) == 's svalue... t tvalue...' def test_log_simple_request(self, caplog): req = APIRequestFactory().post('/?a=b', data={'x': 'v'}) with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"path": "/"' in msg assert '"query params": { "a": [ "b" ] }' in msg assert '"data": { "x": "v" }' in msg def test_log_authorization(self, caplog): req = APIRequestFactory().post( '/?a=b', data={'x': 'v'}, HTTP_AUTHORIZATION='token abcdef') with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"Authorization": "token ..."' in msg def test_log_jwt_authorization(self, caplog): jwt = '<KEY>' req = APIRequestFactory().post( '/?a=b', data={'x': 'v'}, HTTP_AUTHORIZATION=f'jwt {jwt}') with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"jwt_headers": { "alg": "HS256", "typ": "JWT" }' in msg assert '"jwt_claims": { "sub": "1234567890", "name": "<NAME>", "iat": 1516239022 }' in msg
tests/test_views.py
import logging import boto3 from botocore.stub import Stubber from django.test import TestCase from django.contrib.auth import get_user_model from django.core.cache import caches from rest_framework.response import Response from rest_framework.test import APIRequestFactory from rest_framework.views import APIView from drftoolbox import views, authentication class KMSSecretAPISignatureAuthentucation(authentication.BaseKMSSecretAPISignatureAuthentication): client = boto3.client('kms', region_name='us-east-1') cache_timeout = 5 def get_aws_kms_arn(self): return 'ARN' def get_user(self, api_key): return get_user_model().objects.get(username=api_key) class UserKMSKeyView(views.BaseUserKMSKeyView): def http_sign_class(self): return KMSSecretAPISignatureAuthentucation class BaseUserKMSKeyView(TestCase): def setUp(self): self.stubber = Stubber(KMSSecretAPISignatureAuthentucation.client) caches['default'].clear() def test_inactive_user_key(self): user = get_user_model().objects.create_user('test', is_active=False) req = APIRequestFactory().get('/user-key/{}'.format(user.pk)) resp = UserKMSKeyView.as_view()(req, pk=user.pk) assert resp.status_code == 404 def test_user_key(self): user = get_user_model().objects.create_user('test') self.stubber.add_response('encrypt', {'CiphertextBlob': b'kms-key'}) self.stubber.activate() req = APIRequestFactory().get('/user-key/{}'.format(user.pk)) resp = UserKMSKeyView.as_view()(req, pk=user.pk) assert resp.status_code == 200 assert resp.data['encrypted_key'] is not None assert resp.data['expiry'] is not None class LoggingView(views.RequestLoggingViewMixin, APIView): def post(self, request): return Response('ok') class TestRequestLoggingViewMixin(): def test_obfuscate(self): mixin = views.RequestLoggingViewMixin val = 'jwt ajwttokenvalue' assert mixin.obfuscate(val) == 'jwt aj...' val = 's=svalueincookie; t=tvalueincookie' assert mixin.obfuscate(val) == 's svalue... t tvalue...' def test_log_simple_request(self, caplog): req = APIRequestFactory().post('/?a=b', data={'x': 'v'}) with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"path": "/"' in msg assert '"query params": { "a": [ "b" ] }' in msg assert '"data": { "x": "v" }' in msg def test_log_authorization(self, caplog): req = APIRequestFactory().post( '/?a=b', data={'x': 'v'}, HTTP_AUTHORIZATION='token abcdef') with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"Authorization": "token ..."' in msg def test_log_jwt_authorization(self, caplog): jwt = '<KEY>' req = APIRequestFactory().post( '/?a=b', data={'x': 'v'}, HTTP_AUTHORIZATION=f'jwt {jwt}') with caplog.at_level(logging.INFO, logger='drftoolbox.views'): LoggingView.as_view()(req) assert len(caplog.records) == 1 msg = ' '.join(caplog.text.split()) assert '"jwt_headers": { "alg": "HS256", "typ": "JWT" }' in msg assert '"jwt_claims": { "sub": "1234567890", "name": "<NAME>", "iat": 1516239022 }' in msg
0.437343
0.224029
from pprint import pformat from six import iteritems class V1Volume(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'name': 'str', 'host_path': 'V1HostPathVolumeSource', 'empty_dir': 'V1EmptyDirVolumeSource', 'gce_persistent_disk': 'V1GCEPersistentDiskVolumeSource', 'aws_elastic_block_store': 'V1AWSElasticBlockStoreVolumeSource', 'git_repo': 'V1GitRepoVolumeSource', 'secret': 'V1SecretVolumeSource', 'nfs': 'V1NFSVolumeSource', 'iscsi': 'V1ISCSIVolumeSource', 'glusterfs': 'V1GlusterfsVolumeSource', 'persistent_volume_claim': 'V1PersistentVolumeClaimVolumeSource', 'rbd': 'V1RBDVolumeSource' } self.attribute_map = { 'name': 'name', 'host_path': 'hostPath', 'empty_dir': 'emptyDir', 'gce_persistent_disk': 'gcePersistentDisk', 'aws_elastic_block_store': 'awsElasticBlockStore', 'git_repo': 'gitRepo', 'secret': 'secret', 'nfs': 'nfs', 'iscsi': 'iscsi', 'glusterfs': 'glusterfs', 'persistent_volume_claim': 'persistentVolumeClaim', 'rbd': 'rbd' } self._name = None self._host_path = None self._empty_dir = None self._gce_persistent_disk = None self._aws_elastic_block_store = None self._git_repo = None self._secret = None self._nfs = None self._iscsi = None self._glusterfs = None self._persistent_volume_claim = None self._rbd = None @property def name(self): """ Gets the name of this V1Volume. volume name; must be a DNS_LABEL and unique within the pod; see http://releases.k8s.io/v1.0.4/docs/identifiers.md#names :return: The name of this V1Volume. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this V1Volume. volume name; must be a DNS_LABEL and unique within the pod; see http://releases.k8s.io/v1.0.4/docs/identifiers.md#names :param name: The name of this V1Volume. :type: str """ self._name = name @property def host_path(self): """ Gets the host_path of this V1Volume. pre-existing host file or directory; generally for privileged system daemons or other agents tied to the host; see http://releases.k8s.io/v1.0.4/docs/volumes.md#hostpath :return: The host_path of this V1Volume. :rtype: V1HostPathVolumeSource """ return self._host_path @host_path.setter def host_path(self, host_path): """ Sets the host_path of this V1Volume. pre-existing host file or directory; generally for privileged system daemons or other agents tied to the host; see http://releases.k8s.io/v1.0.4/docs/volumes.md#hostpath :param host_path: The host_path of this V1Volume. :type: V1HostPathVolumeSource """ self._host_path = host_path @property def empty_dir(self): """ Gets the empty_dir of this V1Volume. temporary directory that shares a pod's lifetime; see http://releases.k8s.io/v1.0.4/docs/volumes.md#emptydir :return: The empty_dir of this V1Volume. :rtype: V1EmptyDirVolumeSource """ return self._empty_dir @empty_dir.setter def empty_dir(self, empty_dir): """ Sets the empty_dir of this V1Volume. temporary directory that shares a pod's lifetime; see http://releases.k8s.io/v1.0.4/docs/volumes.md#emptydir :param empty_dir: The empty_dir of this V1Volume. :type: V1EmptyDirVolumeSource """ self._empty_dir = empty_dir @property def gce_persistent_disk(self): """ Gets the gce_persistent_disk of this V1Volume. GCE disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#gcepersistentdisk :return: The gce_persistent_disk of this V1Volume. :rtype: V1GCEPersistentDiskVolumeSource """ return self._gce_persistent_disk @gce_persistent_disk.setter def gce_persistent_disk(self, gce_persistent_disk): """ Sets the gce_persistent_disk of this V1Volume. GCE disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#gcepersistentdisk :param gce_persistent_disk: The gce_persistent_disk of this V1Volume. :type: V1GCEPersistentDiskVolumeSource """ self._gce_persistent_disk = gce_persistent_disk @property def aws_elastic_block_store(self): """ Gets the aws_elastic_block_store of this V1Volume. AWS disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#awselasticblockstore :return: The aws_elastic_block_store of this V1Volume. :rtype: V1AWSElasticBlockStoreVolumeSource """ return self._aws_elastic_block_store @aws_elastic_block_store.setter def aws_elastic_block_store(self, aws_elastic_block_store): """ Sets the aws_elastic_block_store of this V1Volume. AWS disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#awselasticblockstore :param aws_elastic_block_store: The aws_elastic_block_store of this V1Volume. :type: V1AWSElasticBlockStoreVolumeSource """ self._aws_elastic_block_store = aws_elastic_block_store @property def git_repo(self): """ Gets the git_repo of this V1Volume. git repository at a particular revision :return: The git_repo of this V1Volume. :rtype: V1GitRepoVolumeSource """ return self._git_repo @git_repo.setter def git_repo(self, git_repo): """ Sets the git_repo of this V1Volume. git repository at a particular revision :param git_repo: The git_repo of this V1Volume. :type: V1GitRepoVolumeSource """ self._git_repo = git_repo @property def secret(self): """ Gets the secret of this V1Volume. secret to populate volume; see http://releases.k8s.io/v1.0.4/docs/volumes.md#secrets :return: The secret of this V1Volume. :rtype: V1SecretVolumeSource """ return self._secret @secret.setter def secret(self, secret): """ Sets the secret of this V1Volume. secret to populate volume; see http://releases.k8s.io/v1.0.4/docs/volumes.md#secrets :param secret: The secret of this V1Volume. :type: V1SecretVolumeSource """ self._secret = secret @property def nfs(self): """ Gets the nfs of this V1Volume. NFS volume that will be mounted in the host machine; see http://releases.k8s.io/v1.0.4/docs/volumes.md#nfs :return: The nfs of this V1Volume. :rtype: V1NFSVolumeSource """ return self._nfs @nfs.setter def nfs(self, nfs): """ Sets the nfs of this V1Volume. NFS volume that will be mounted in the host machine; see http://releases.k8s.io/v1.0.4/docs/volumes.md#nfs :param nfs: The nfs of this V1Volume. :type: V1NFSVolumeSource """ self._nfs = nfs @property def iscsi(self): """ Gets the iscsi of this V1Volume. iSCSI disk attached to host machine on demand; see http://releases.k8s.io/v1.0.4/examples/iscsi/README.md :return: The iscsi of this V1Volume. :rtype: V1ISCSIVolumeSource """ return self._iscsi @iscsi.setter def iscsi(self, iscsi): """ Sets the iscsi of this V1Volume. iSCSI disk attached to host machine on demand; see http://releases.k8s.io/v1.0.4/examples/iscsi/README.md :param iscsi: The iscsi of this V1Volume. :type: V1ISCSIVolumeSource """ self._iscsi = iscsi @property def glusterfs(self): """ Gets the glusterfs of this V1Volume. Glusterfs volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/glusterfs/README.md :return: The glusterfs of this V1Volume. :rtype: V1GlusterfsVolumeSource """ return self._glusterfs @glusterfs.setter def glusterfs(self, glusterfs): """ Sets the glusterfs of this V1Volume. Glusterfs volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/glusterfs/README.md :param glusterfs: The glusterfs of this V1Volume. :type: V1GlusterfsVolumeSource """ self._glusterfs = glusterfs @property def persistent_volume_claim(self): """ Gets the persistent_volume_claim of this V1Volume. a reference to a PersistentVolumeClaim in the same namespace; see http://releases.k8s.io/v1.0.4/docs/persistent-volumes.md#persistentvolumeclaims :return: The persistent_volume_claim of this V1Volume. :rtype: V1PersistentVolumeClaimVolumeSource """ return self._persistent_volume_claim @persistent_volume_claim.setter def persistent_volume_claim(self, persistent_volume_claim): """ Sets the persistent_volume_claim of this V1Volume. a reference to a PersistentVolumeClaim in the same namespace; see http://releases.k8s.io/v1.0.4/docs/persistent-volumes.md#persistentvolumeclaims :param persistent_volume_claim: The persistent_volume_claim of this V1Volume. :type: V1PersistentVolumeClaimVolumeSource """ self._persistent_volume_claim = persistent_volume_claim @property def rbd(self): """ Gets the rbd of this V1Volume. rados block volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/rbd/README.md :return: The rbd of this V1Volume. :rtype: V1RBDVolumeSource """ return self._rbd @rbd.setter def rbd(self, rbd): """ Sets the rbd of this V1Volume. rados block volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/rbd/README.md :param rbd: The rbd of this V1Volume. :type: V1RBDVolumeSource """ self._rbd = rbd def to_dict(self): """ Return model properties dict """ result = {} for attr, _ in 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() else: result[attr] = value return result def to_str(self): """ Return model properties str """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
magnum/common/pythonk8sclient/swagger_client/models/v1_volume.py
from pprint import pformat from six import iteritems class V1Volume(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'name': 'str', 'host_path': 'V1HostPathVolumeSource', 'empty_dir': 'V1EmptyDirVolumeSource', 'gce_persistent_disk': 'V1GCEPersistentDiskVolumeSource', 'aws_elastic_block_store': 'V1AWSElasticBlockStoreVolumeSource', 'git_repo': 'V1GitRepoVolumeSource', 'secret': 'V1SecretVolumeSource', 'nfs': 'V1NFSVolumeSource', 'iscsi': 'V1ISCSIVolumeSource', 'glusterfs': 'V1GlusterfsVolumeSource', 'persistent_volume_claim': 'V1PersistentVolumeClaimVolumeSource', 'rbd': 'V1RBDVolumeSource' } self.attribute_map = { 'name': 'name', 'host_path': 'hostPath', 'empty_dir': 'emptyDir', 'gce_persistent_disk': 'gcePersistentDisk', 'aws_elastic_block_store': 'awsElasticBlockStore', 'git_repo': 'gitRepo', 'secret': 'secret', 'nfs': 'nfs', 'iscsi': 'iscsi', 'glusterfs': 'glusterfs', 'persistent_volume_claim': 'persistentVolumeClaim', 'rbd': 'rbd' } self._name = None self._host_path = None self._empty_dir = None self._gce_persistent_disk = None self._aws_elastic_block_store = None self._git_repo = None self._secret = None self._nfs = None self._iscsi = None self._glusterfs = None self._persistent_volume_claim = None self._rbd = None @property def name(self): """ Gets the name of this V1Volume. volume name; must be a DNS_LABEL and unique within the pod; see http://releases.k8s.io/v1.0.4/docs/identifiers.md#names :return: The name of this V1Volume. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this V1Volume. volume name; must be a DNS_LABEL and unique within the pod; see http://releases.k8s.io/v1.0.4/docs/identifiers.md#names :param name: The name of this V1Volume. :type: str """ self._name = name @property def host_path(self): """ Gets the host_path of this V1Volume. pre-existing host file or directory; generally for privileged system daemons or other agents tied to the host; see http://releases.k8s.io/v1.0.4/docs/volumes.md#hostpath :return: The host_path of this V1Volume. :rtype: V1HostPathVolumeSource """ return self._host_path @host_path.setter def host_path(self, host_path): """ Sets the host_path of this V1Volume. pre-existing host file or directory; generally for privileged system daemons or other agents tied to the host; see http://releases.k8s.io/v1.0.4/docs/volumes.md#hostpath :param host_path: The host_path of this V1Volume. :type: V1HostPathVolumeSource """ self._host_path = host_path @property def empty_dir(self): """ Gets the empty_dir of this V1Volume. temporary directory that shares a pod's lifetime; see http://releases.k8s.io/v1.0.4/docs/volumes.md#emptydir :return: The empty_dir of this V1Volume. :rtype: V1EmptyDirVolumeSource """ return self._empty_dir @empty_dir.setter def empty_dir(self, empty_dir): """ Sets the empty_dir of this V1Volume. temporary directory that shares a pod's lifetime; see http://releases.k8s.io/v1.0.4/docs/volumes.md#emptydir :param empty_dir: The empty_dir of this V1Volume. :type: V1EmptyDirVolumeSource """ self._empty_dir = empty_dir @property def gce_persistent_disk(self): """ Gets the gce_persistent_disk of this V1Volume. GCE disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#gcepersistentdisk :return: The gce_persistent_disk of this V1Volume. :rtype: V1GCEPersistentDiskVolumeSource """ return self._gce_persistent_disk @gce_persistent_disk.setter def gce_persistent_disk(self, gce_persistent_disk): """ Sets the gce_persistent_disk of this V1Volume. GCE disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#gcepersistentdisk :param gce_persistent_disk: The gce_persistent_disk of this V1Volume. :type: V1GCEPersistentDiskVolumeSource """ self._gce_persistent_disk = gce_persistent_disk @property def aws_elastic_block_store(self): """ Gets the aws_elastic_block_store of this V1Volume. AWS disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#awselasticblockstore :return: The aws_elastic_block_store of this V1Volume. :rtype: V1AWSElasticBlockStoreVolumeSource """ return self._aws_elastic_block_store @aws_elastic_block_store.setter def aws_elastic_block_store(self, aws_elastic_block_store): """ Sets the aws_elastic_block_store of this V1Volume. AWS disk resource attached to the host machine on demand; see http://releases.k8s.io/v1.0.4/docs/volumes.md#awselasticblockstore :param aws_elastic_block_store: The aws_elastic_block_store of this V1Volume. :type: V1AWSElasticBlockStoreVolumeSource """ self._aws_elastic_block_store = aws_elastic_block_store @property def git_repo(self): """ Gets the git_repo of this V1Volume. git repository at a particular revision :return: The git_repo of this V1Volume. :rtype: V1GitRepoVolumeSource """ return self._git_repo @git_repo.setter def git_repo(self, git_repo): """ Sets the git_repo of this V1Volume. git repository at a particular revision :param git_repo: The git_repo of this V1Volume. :type: V1GitRepoVolumeSource """ self._git_repo = git_repo @property def secret(self): """ Gets the secret of this V1Volume. secret to populate volume; see http://releases.k8s.io/v1.0.4/docs/volumes.md#secrets :return: The secret of this V1Volume. :rtype: V1SecretVolumeSource """ return self._secret @secret.setter def secret(self, secret): """ Sets the secret of this V1Volume. secret to populate volume; see http://releases.k8s.io/v1.0.4/docs/volumes.md#secrets :param secret: The secret of this V1Volume. :type: V1SecretVolumeSource """ self._secret = secret @property def nfs(self): """ Gets the nfs of this V1Volume. NFS volume that will be mounted in the host machine; see http://releases.k8s.io/v1.0.4/docs/volumes.md#nfs :return: The nfs of this V1Volume. :rtype: V1NFSVolumeSource """ return self._nfs @nfs.setter def nfs(self, nfs): """ Sets the nfs of this V1Volume. NFS volume that will be mounted in the host machine; see http://releases.k8s.io/v1.0.4/docs/volumes.md#nfs :param nfs: The nfs of this V1Volume. :type: V1NFSVolumeSource """ self._nfs = nfs @property def iscsi(self): """ Gets the iscsi of this V1Volume. iSCSI disk attached to host machine on demand; see http://releases.k8s.io/v1.0.4/examples/iscsi/README.md :return: The iscsi of this V1Volume. :rtype: V1ISCSIVolumeSource """ return self._iscsi @iscsi.setter def iscsi(self, iscsi): """ Sets the iscsi of this V1Volume. iSCSI disk attached to host machine on demand; see http://releases.k8s.io/v1.0.4/examples/iscsi/README.md :param iscsi: The iscsi of this V1Volume. :type: V1ISCSIVolumeSource """ self._iscsi = iscsi @property def glusterfs(self): """ Gets the glusterfs of this V1Volume. Glusterfs volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/glusterfs/README.md :return: The glusterfs of this V1Volume. :rtype: V1GlusterfsVolumeSource """ return self._glusterfs @glusterfs.setter def glusterfs(self, glusterfs): """ Sets the glusterfs of this V1Volume. Glusterfs volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/glusterfs/README.md :param glusterfs: The glusterfs of this V1Volume. :type: V1GlusterfsVolumeSource """ self._glusterfs = glusterfs @property def persistent_volume_claim(self): """ Gets the persistent_volume_claim of this V1Volume. a reference to a PersistentVolumeClaim in the same namespace; see http://releases.k8s.io/v1.0.4/docs/persistent-volumes.md#persistentvolumeclaims :return: The persistent_volume_claim of this V1Volume. :rtype: V1PersistentVolumeClaimVolumeSource """ return self._persistent_volume_claim @persistent_volume_claim.setter def persistent_volume_claim(self, persistent_volume_claim): """ Sets the persistent_volume_claim of this V1Volume. a reference to a PersistentVolumeClaim in the same namespace; see http://releases.k8s.io/v1.0.4/docs/persistent-volumes.md#persistentvolumeclaims :param persistent_volume_claim: The persistent_volume_claim of this V1Volume. :type: V1PersistentVolumeClaimVolumeSource """ self._persistent_volume_claim = persistent_volume_claim @property def rbd(self): """ Gets the rbd of this V1Volume. rados block volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/rbd/README.md :return: The rbd of this V1Volume. :rtype: V1RBDVolumeSource """ return self._rbd @rbd.setter def rbd(self, rbd): """ Sets the rbd of this V1Volume. rados block volume that will be mounted on the host machine; see http://releases.k8s.io/v1.0.4/examples/rbd/README.md :param rbd: The rbd of this V1Volume. :type: V1RBDVolumeSource """ self._rbd = rbd def to_dict(self): """ Return model properties dict """ result = {} for attr, _ in 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() else: result[attr] = value return result def to_str(self): """ Return model properties str """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
0.750827
0.149035
from struct import pack, unpack from time import time from FS.Inode import Inode class Root(object): def __init__(self, superblock, fat, file): self._superblock = superblock self._fat = fat self._file = file self._init_files_list() def add(self, file_name, inode): superblock = self._superblock fat = self._fat file = self._file file_name = bytes(file_name, 'utf-8') clusters = fat.get_clusters_chain(0) empty_space = None for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) if ord(data[1]) == 0: empty_space = file.tell() - 64 break if empty_space: break else: cluster_index = fat.get_free_cluster() fat.set(clusters[-1], cluster_index) fat.set(cluster_index, -1) empty_space = self._cluster_offset(cluster_index) root_inode = Inode.get_inode(superblock.inode_array_offset, file, 0) root_inode.size = (len(clusters) + 1) * superblock.cluster_size Inode.set_inode(superblock.inode_array_offset, file, root_inode) file.seek(empty_space) file.write(pack('59sci', file_name, bytes([len(file_name)]), inode.id)) self._list[file_name.decode()] = inode Inode.set_inode(superblock.inode_array_offset, file, inode) def read(self, file_name): return self._list[file_name] def delete(self, file_name): superblock = self._superblock fat = self._fat file = self._file file_name = bytes(file_name, 'utf-8') clusters = fat.get_clusters_chain(0) found = False for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) length = ord(data[1]) name = data[0][:length] if name == file_name: file.seek(-64, 1) file.write(pack('64s', bytes([0] * 64))) del (self._list[file_name.decode()]) found = True break if found: break def _init_files_list(self): superblock = self._superblock fat = self._fat file = self._file self._list = {} clusters = fat.get_clusters_chain(0) for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) length = ord(data[1]) if length: position = file.tell() self._list[data[0][:length].decode()] = Inode.get_inode( superblock.inode_array_offset, file, data[2]) file.seek(position) def _cluster_offset(self, cluster_index): return ( self._superblock.first_cluster_offset + cluster_index * self._superblock.cluster_size) def update_inode(self, file_name, inode): self._list[file_name] = inode Inode.set_inode(self._superblock.inode_array_offset, self._file, inode) @property def list(self): return self._list.copy() @staticmethod def write(superblock, fat, inode_map, file): now = int(time()) inode = Inode(id=0, size=superblock.cluster_size, ctime=now, mtime=now, first_cluster=0) Inode.set_inode(superblock.inode_array_offset, file, inode) inode_map.set(inode.id, False) fat.set(0, -1)
FS/Root.py
from struct import pack, unpack from time import time from FS.Inode import Inode class Root(object): def __init__(self, superblock, fat, file): self._superblock = superblock self._fat = fat self._file = file self._init_files_list() def add(self, file_name, inode): superblock = self._superblock fat = self._fat file = self._file file_name = bytes(file_name, 'utf-8') clusters = fat.get_clusters_chain(0) empty_space = None for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) if ord(data[1]) == 0: empty_space = file.tell() - 64 break if empty_space: break else: cluster_index = fat.get_free_cluster() fat.set(clusters[-1], cluster_index) fat.set(cluster_index, -1) empty_space = self._cluster_offset(cluster_index) root_inode = Inode.get_inode(superblock.inode_array_offset, file, 0) root_inode.size = (len(clusters) + 1) * superblock.cluster_size Inode.set_inode(superblock.inode_array_offset, file, root_inode) file.seek(empty_space) file.write(pack('59sci', file_name, bytes([len(file_name)]), inode.id)) self._list[file_name.decode()] = inode Inode.set_inode(superblock.inode_array_offset, file, inode) def read(self, file_name): return self._list[file_name] def delete(self, file_name): superblock = self._superblock fat = self._fat file = self._file file_name = bytes(file_name, 'utf-8') clusters = fat.get_clusters_chain(0) found = False for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) length = ord(data[1]) name = data[0][:length] if name == file_name: file.seek(-64, 1) file.write(pack('64s', bytes([0] * 64))) del (self._list[file_name.decode()]) found = True break if found: break def _init_files_list(self): superblock = self._superblock fat = self._fat file = self._file self._list = {} clusters = fat.get_clusters_chain(0) for cluster in clusters: file.seek(self._cluster_offset(cluster)) for _ in range(superblock.cluster_size // 64): data = unpack('59sci', file.read(64)) length = ord(data[1]) if length: position = file.tell() self._list[data[0][:length].decode()] = Inode.get_inode( superblock.inode_array_offset, file, data[2]) file.seek(position) def _cluster_offset(self, cluster_index): return ( self._superblock.first_cluster_offset + cluster_index * self._superblock.cluster_size) def update_inode(self, file_name, inode): self._list[file_name] = inode Inode.set_inode(self._superblock.inode_array_offset, self._file, inode) @property def list(self): return self._list.copy() @staticmethod def write(superblock, fat, inode_map, file): now = int(time()) inode = Inode(id=0, size=superblock.cluster_size, ctime=now, mtime=now, first_cluster=0) Inode.set_inode(superblock.inode_array_offset, file, inode) inode_map.set(inode.id, False) fat.set(0, -1)
0.442877
0.215846
import tornado.gen import tornado.httpserver import tornado.web from wotpy.codecs.enums import MediaTypes from wotpy.protocols.enums import Protocols, InteractionVerbs from wotpy.protocols.http.enums import HTTPSchemes from wotpy.protocols.http.handlers.action import ActionInvokeHandler, PendingInvocationHandler from wotpy.protocols.http.handlers.event import EventObserverHandler from wotpy.protocols.http.handlers.property import PropertyObserverHandler, PropertyReadWriteHandler from wotpy.protocols.server import BaseProtocolServer from wotpy.wot.enums import InteractionTypes from wotpy.wot.form import Form class HTTPServer(BaseProtocolServer): """HTTP binding server implementation.""" DEFAULT_PORT = 80 def __init__(self, port=DEFAULT_PORT, ssl_context=None, action_ttl_secs=300): super(HTTPServer, self).__init__(port=port) self._server = None self._app = self._build_app() self._ssl_context = ssl_context self._action_ttl_secs = action_ttl_secs self._pending_actions = {} self._invocation_check_times = {} @property def protocol(self): """Protocol of this server instance. A member of the Protocols enum.""" return Protocols.HTTP @property def scheme(self): """Returns the URL scheme for this server.""" return HTTPSchemes.HTTPS if self.is_secure else HTTPSchemes.HTTP @property def is_secure(self): """Returns True if this server is configured to use SSL encryption.""" return self._ssl_context is not None @property def app(self): """Tornado application.""" return self._app @property def action_ttl(self): """Returns the Action invocations Time-To-Live (seconds).""" return self._action_ttl_secs @property def pending_actions(self): """Dict of pending action invocations represented as Futures.""" return self._pending_actions @property def invocation_check_times(self): """Dict that contains the timestamp of the last time an invocation was checked by a client..""" return self._invocation_check_times def _build_app(self): """Builds and returns the Tornado application for the WebSockets server.""" return tornado.web.Application([( r"/(?P<thing_name>[^\/]+)/property/(?P<name>[^\/]+)", PropertyReadWriteHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/property/(?P<name>[^\/]+)/subscription", PropertyObserverHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/action/(?P<name>[^\/]+)", ActionInvokeHandler, {"http_server": self} ), ( r"/invocation/(?P<invocation_id>[^\/]+)", PendingInvocationHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/event/(?P<name>[^\/]+)/subscription", EventObserverHandler, {"http_server": self} )]) def _build_forms_property(self, proprty, hostname): """Builds and returns the HTTP Form instances for the given Property interaction.""" href_read_write = "{}://{}:{}/{}/property/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, proprty.thing.url_name, proprty.url_name) form_read = Form( interaction=proprty, protocol=self.protocol, href=href_read_write, content_type=MediaTypes.JSON, op=InteractionVerbs.READ_PROPERTY) form_write = Form( interaction=proprty, protocol=self.protocol, href=href_read_write, content_type=MediaTypes.JSON, op=InteractionVerbs.WRITE_PROPERTY) href_observe = "{}/subscription".format(href_read_write) form_observe = Form( interaction=proprty, protocol=self.protocol, href=href_observe, content_type=MediaTypes.JSON, op=InteractionVerbs.OBSERVE_PROPERTY) return [form_read, form_write, form_observe] def _build_forms_action(self, action, hostname): """Builds and returns the HTTP Form instances for the given Action interaction.""" href_invoke = "{}://{}:{}/{}/action/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, action.thing.url_name, action.url_name) form_invoke = Form( interaction=action, protocol=self.protocol, href=href_invoke, content_type=MediaTypes.JSON, op=InteractionVerbs.INVOKE_ACTION) return [form_invoke] def _build_forms_event(self, event, hostname): """Builds and returns the HTTP Form instances for the given Event interaction.""" href_observe = "{}://{}:{}/{}/event/{}/subscription".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, event.thing.url_name, event.url_name) form_observe = Form( interaction=event, protocol=self.protocol, href=href_observe, content_type=MediaTypes.JSON, op=InteractionVerbs.SUBSCRIBE_EVENT) return [form_observe] def build_forms(self, hostname, interaction): """Builds and returns a list with all Form that are linked to this server for the given Interaction.""" intrct_type_map = { InteractionTypes.PROPERTY: self._build_forms_property, InteractionTypes.ACTION: self._build_forms_action, InteractionTypes.EVENT: self._build_forms_event } if interaction.interaction_type not in intrct_type_map: raise ValueError("Unsupported interaction") return intrct_type_map[interaction.interaction_type](interaction, hostname) def build_base_url(self, hostname, thing): """Returns the base URL for the given Thing in the context of this server.""" if not self.exposed_thing_set.find_by_thing_id(thing.id): raise ValueError("Unknown Thing") return "{}://{}:{}/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, thing.url_name) @tornado.gen.coroutine def start(self): """Starts the HTTP server.""" self._server = tornado.httpserver.HTTPServer(self.app, ssl_options=self._ssl_context) self._server.listen(self.port) @tornado.gen.coroutine def stop(self): """Stops the HTTP server.""" if not self._server: return self._server.stop() self._server = None
wotpy/protocols/http/server.py
import tornado.gen import tornado.httpserver import tornado.web from wotpy.codecs.enums import MediaTypes from wotpy.protocols.enums import Protocols, InteractionVerbs from wotpy.protocols.http.enums import HTTPSchemes from wotpy.protocols.http.handlers.action import ActionInvokeHandler, PendingInvocationHandler from wotpy.protocols.http.handlers.event import EventObserverHandler from wotpy.protocols.http.handlers.property import PropertyObserverHandler, PropertyReadWriteHandler from wotpy.protocols.server import BaseProtocolServer from wotpy.wot.enums import InteractionTypes from wotpy.wot.form import Form class HTTPServer(BaseProtocolServer): """HTTP binding server implementation.""" DEFAULT_PORT = 80 def __init__(self, port=DEFAULT_PORT, ssl_context=None, action_ttl_secs=300): super(HTTPServer, self).__init__(port=port) self._server = None self._app = self._build_app() self._ssl_context = ssl_context self._action_ttl_secs = action_ttl_secs self._pending_actions = {} self._invocation_check_times = {} @property def protocol(self): """Protocol of this server instance. A member of the Protocols enum.""" return Protocols.HTTP @property def scheme(self): """Returns the URL scheme for this server.""" return HTTPSchemes.HTTPS if self.is_secure else HTTPSchemes.HTTP @property def is_secure(self): """Returns True if this server is configured to use SSL encryption.""" return self._ssl_context is not None @property def app(self): """Tornado application.""" return self._app @property def action_ttl(self): """Returns the Action invocations Time-To-Live (seconds).""" return self._action_ttl_secs @property def pending_actions(self): """Dict of pending action invocations represented as Futures.""" return self._pending_actions @property def invocation_check_times(self): """Dict that contains the timestamp of the last time an invocation was checked by a client..""" return self._invocation_check_times def _build_app(self): """Builds and returns the Tornado application for the WebSockets server.""" return tornado.web.Application([( r"/(?P<thing_name>[^\/]+)/property/(?P<name>[^\/]+)", PropertyReadWriteHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/property/(?P<name>[^\/]+)/subscription", PropertyObserverHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/action/(?P<name>[^\/]+)", ActionInvokeHandler, {"http_server": self} ), ( r"/invocation/(?P<invocation_id>[^\/]+)", PendingInvocationHandler, {"http_server": self} ), ( r"/(?P<thing_name>[^\/]+)/event/(?P<name>[^\/]+)/subscription", EventObserverHandler, {"http_server": self} )]) def _build_forms_property(self, proprty, hostname): """Builds and returns the HTTP Form instances for the given Property interaction.""" href_read_write = "{}://{}:{}/{}/property/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, proprty.thing.url_name, proprty.url_name) form_read = Form( interaction=proprty, protocol=self.protocol, href=href_read_write, content_type=MediaTypes.JSON, op=InteractionVerbs.READ_PROPERTY) form_write = Form( interaction=proprty, protocol=self.protocol, href=href_read_write, content_type=MediaTypes.JSON, op=InteractionVerbs.WRITE_PROPERTY) href_observe = "{}/subscription".format(href_read_write) form_observe = Form( interaction=proprty, protocol=self.protocol, href=href_observe, content_type=MediaTypes.JSON, op=InteractionVerbs.OBSERVE_PROPERTY) return [form_read, form_write, form_observe] def _build_forms_action(self, action, hostname): """Builds and returns the HTTP Form instances for the given Action interaction.""" href_invoke = "{}://{}:{}/{}/action/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, action.thing.url_name, action.url_name) form_invoke = Form( interaction=action, protocol=self.protocol, href=href_invoke, content_type=MediaTypes.JSON, op=InteractionVerbs.INVOKE_ACTION) return [form_invoke] def _build_forms_event(self, event, hostname): """Builds and returns the HTTP Form instances for the given Event interaction.""" href_observe = "{}://{}:{}/{}/event/{}/subscription".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, event.thing.url_name, event.url_name) form_observe = Form( interaction=event, protocol=self.protocol, href=href_observe, content_type=MediaTypes.JSON, op=InteractionVerbs.SUBSCRIBE_EVENT) return [form_observe] def build_forms(self, hostname, interaction): """Builds and returns a list with all Form that are linked to this server for the given Interaction.""" intrct_type_map = { InteractionTypes.PROPERTY: self._build_forms_property, InteractionTypes.ACTION: self._build_forms_action, InteractionTypes.EVENT: self._build_forms_event } if interaction.interaction_type not in intrct_type_map: raise ValueError("Unsupported interaction") return intrct_type_map[interaction.interaction_type](interaction, hostname) def build_base_url(self, hostname, thing): """Returns the base URL for the given Thing in the context of this server.""" if not self.exposed_thing_set.find_by_thing_id(thing.id): raise ValueError("Unknown Thing") return "{}://{}:{}/{}".format( self.scheme, hostname.rstrip("/").lstrip("/"), self.port, thing.url_name) @tornado.gen.coroutine def start(self): """Starts the HTTP server.""" self._server = tornado.httpserver.HTTPServer(self.app, ssl_options=self._ssl_context) self._server.listen(self.port) @tornado.gen.coroutine def stop(self): """Stops the HTTP server.""" if not self._server: return self._server.stop() self._server = None
0.790126
0.113211
import numpy as np import matplotlib.pyplot as plt from acconeer_utils.clients import SocketClient, SPIClient, UARTClient from acconeer_utils.clients import configs from acconeer_utils import example_utils def main(): args = example_utils.ExampleArgumentParser(num_sens=1).parse_args() example_utils.config_logging(args) if args.socket_addr: client = SocketClient(args.socket_addr) elif args.spi: client = SPIClient() else: port = args.serial_port or example_utils.autodetect_serial_port() client = UARTClient(port) config = configs.IQServiceConfig() config.sensor = args.sensors config.range_interval = [0.2, 0.6] config.sweep_rate = 10 config.gain = 0.6 info = client.setup_session(config) num_points = info["data_length"] amplitude_y_max = 0.3 fig, (amplitude_ax, phase_ax) = plt.subplots(2) fig.set_size_inches(8, 6) fig.canvas.set_window_title("Acconeer matplotlib example") for ax in [amplitude_ax, phase_ax]: ax.set_xlabel("Depth (m)") ax.set_xlim(config.range_interval) ax.grid(True) amplitude_ax.set_ylabel("Amplitude") amplitude_ax.set_ylim(0, 1.1 * amplitude_y_max) phase_ax.set_ylabel("Phase") example_utils.mpl_setup_yaxis_for_phase(phase_ax) xs = np.linspace(*config.range_interval, num_points) amplitude_line = amplitude_ax.plot(xs, np.zeros_like(xs))[0] phase_line = phase_ax.plot(xs, np.zeros_like(xs))[0] fig.tight_layout() plt.ion() plt.show() interrupt_handler = example_utils.ExampleInterruptHandler() print("Press Ctrl-C to end session") client.start_streaming() while not interrupt_handler.got_signal: info, sweep = client.get_next() amplitude = np.abs(sweep) phase = np.angle(sweep) max_amplitude = np.max(amplitude) if max_amplitude > amplitude_y_max: amplitude_y_max = max_amplitude amplitude_ax.set_ylim(0, 1.1 * max_amplitude) amplitude_line.set_ydata(amplitude) phase_line.set_ydata(phase) if not plt.fignum_exists(1): # Simple way to check if plot is closed break fig.canvas.flush_events() print("Disconnecting...") plt.close() client.disconnect() if __name__ == "__main__": main()
examples/plotting/plot_with_matplotlib.py
import numpy as np import matplotlib.pyplot as plt from acconeer_utils.clients import SocketClient, SPIClient, UARTClient from acconeer_utils.clients import configs from acconeer_utils import example_utils def main(): args = example_utils.ExampleArgumentParser(num_sens=1).parse_args() example_utils.config_logging(args) if args.socket_addr: client = SocketClient(args.socket_addr) elif args.spi: client = SPIClient() else: port = args.serial_port or example_utils.autodetect_serial_port() client = UARTClient(port) config = configs.IQServiceConfig() config.sensor = args.sensors config.range_interval = [0.2, 0.6] config.sweep_rate = 10 config.gain = 0.6 info = client.setup_session(config) num_points = info["data_length"] amplitude_y_max = 0.3 fig, (amplitude_ax, phase_ax) = plt.subplots(2) fig.set_size_inches(8, 6) fig.canvas.set_window_title("Acconeer matplotlib example") for ax in [amplitude_ax, phase_ax]: ax.set_xlabel("Depth (m)") ax.set_xlim(config.range_interval) ax.grid(True) amplitude_ax.set_ylabel("Amplitude") amplitude_ax.set_ylim(0, 1.1 * amplitude_y_max) phase_ax.set_ylabel("Phase") example_utils.mpl_setup_yaxis_for_phase(phase_ax) xs = np.linspace(*config.range_interval, num_points) amplitude_line = amplitude_ax.plot(xs, np.zeros_like(xs))[0] phase_line = phase_ax.plot(xs, np.zeros_like(xs))[0] fig.tight_layout() plt.ion() plt.show() interrupt_handler = example_utils.ExampleInterruptHandler() print("Press Ctrl-C to end session") client.start_streaming() while not interrupt_handler.got_signal: info, sweep = client.get_next() amplitude = np.abs(sweep) phase = np.angle(sweep) max_amplitude = np.max(amplitude) if max_amplitude > amplitude_y_max: amplitude_y_max = max_amplitude amplitude_ax.set_ylim(0, 1.1 * max_amplitude) amplitude_line.set_ydata(amplitude) phase_line.set_ydata(phase) if not plt.fignum_exists(1): # Simple way to check if plot is closed break fig.canvas.flush_events() print("Disconnecting...") plt.close() client.disconnect() if __name__ == "__main__": main()
0.525369
0.341335
import pygame class JCSPyGm_Input: """Input hanlde.""" mouseDownThisFrame = False mouseIsDown = False mouseUpThisFrame = False mousePosition = (0, 0) keysPressedThisFrame = [] keysDown = [] keysReleasedThisFrame = [] @staticmethod def clean_input_buffer(): """Update the key meta table.""" # reset mouse states JCSPyGm_Input.mouseDownThisFrame = False JCSPyGm_Input.mouseUpThisFrame = False # reset key array JCSPyGm_Input.keysPressedThisFrame = [] JCSPyGm_Input.keysReleasedThisFrame = [] @staticmethod def get_key_down(keyCode): """Check whether the given key was pressed this frame.""" # To use static variables, you must reference the class. for key in JCSPyGm_Input.keysPressedThisFrame: # We found the key being requested. if key == keyCode: return True # We did not find the requested key. return False @staticmethod def get_key(keyCode): """Check whether the given key is pressed.""" for key in JCSPyGm_Input.keysDown: if key == keyCode: return True return False @staticmethod def get_key_up(keyCode): """Check whether the given key was released this frame.""" for key in JCSPyGm_Input.keysReleasedThisFrame: if key == keyCode: return True return False @staticmethod def get_mouse_x(): """Get mouse position on x-axis.""" pX, pY = pygame.mouse.get_pos() return pX @staticmethod def get_mouse_y(): """Get mouse position on x-axis.""" pX, pY = pygame.mouse.get_pos() return pY @staticmethod def get_mouse_button(): """Check whether the mouse is held down.""" return JCSPyGm_Input.mouseIsDown @staticmethod def get_mouse_button_down(): """Check whether the mouse was pressed this frame.""" return JCSPyGm_Input.mouseDownThisFrame @staticmethod def get_mouse_button_up(): """Check whether the mouse was released this frame.""" return JCSPyGm_Input.mouseUpThisFrame
jcspygm/util/JCSPyGm_Input.py
import pygame class JCSPyGm_Input: """Input hanlde.""" mouseDownThisFrame = False mouseIsDown = False mouseUpThisFrame = False mousePosition = (0, 0) keysPressedThisFrame = [] keysDown = [] keysReleasedThisFrame = [] @staticmethod def clean_input_buffer(): """Update the key meta table.""" # reset mouse states JCSPyGm_Input.mouseDownThisFrame = False JCSPyGm_Input.mouseUpThisFrame = False # reset key array JCSPyGm_Input.keysPressedThisFrame = [] JCSPyGm_Input.keysReleasedThisFrame = [] @staticmethod def get_key_down(keyCode): """Check whether the given key was pressed this frame.""" # To use static variables, you must reference the class. for key in JCSPyGm_Input.keysPressedThisFrame: # We found the key being requested. if key == keyCode: return True # We did not find the requested key. return False @staticmethod def get_key(keyCode): """Check whether the given key is pressed.""" for key in JCSPyGm_Input.keysDown: if key == keyCode: return True return False @staticmethod def get_key_up(keyCode): """Check whether the given key was released this frame.""" for key in JCSPyGm_Input.keysReleasedThisFrame: if key == keyCode: return True return False @staticmethod def get_mouse_x(): """Get mouse position on x-axis.""" pX, pY = pygame.mouse.get_pos() return pX @staticmethod def get_mouse_y(): """Get mouse position on x-axis.""" pX, pY = pygame.mouse.get_pos() return pY @staticmethod def get_mouse_button(): """Check whether the mouse is held down.""" return JCSPyGm_Input.mouseIsDown @staticmethod def get_mouse_button_down(): """Check whether the mouse was pressed this frame.""" return JCSPyGm_Input.mouseDownThisFrame @staticmethod def get_mouse_button_up(): """Check whether the mouse was released this frame.""" return JCSPyGm_Input.mouseUpThisFrame
0.5144
0.300848
import numpy as np import torch import alf.utils.distributions as ad import alf class DistributionTest(alf.test.TestCase): def _test_its(self, x, its: ad.InverseTransformSampling): x.requires_grad_() y = its.cdf(x) x1 = its.icdf(y) p = its.log_prob(x).exp() step = x[1] - x[0] psum = p.sum() * step self.assertAlmostEqual(psum, 1., delta=0.01) self.assertTensorClose(x1, x, 0.01) grad = torch.autograd.grad(y.sum(), x)[0] self.assertTensorClose(grad.log(), p.log()) def test_normal_its(self): self._test_its(torch.arange(-4., 4., 1 / 128), ad.NormalITS()) def test_cauchy_its(self): self._test_its(torch.arange(-100., 100., 1 / 128), ad.CauchyITS()) def test_t3_its(self): self._test_its(torch.arange(-20., 20., 1 / 128), ad.T2ITS()) def _test_truncated(self, its: ad.InverseTransformSampling): batch_size = 6 dim = 1 lower_bound = -1.5 * torch.ones(dim) upper_bound = 2.5 * torch.ones(dim) loc = torch.ones((batch_size, dim)) loc[0, :] = -2 loc[1, :] = -1 loc[2, :] = 0 loc[3, :] = 1 loc[4, :] = 2 loc[5, :] = 2 scale = torch.ones((6, dim)) scale[2, :] = 0.5 scale[3, :] = 1.5 dist = ad.TruncatedDistribution( loc=loc, scale=scale, lower_bound=lower_bound, upper_bound=upper_bound, its=its) # Test prob sum to 1. step = 1 / 128 x = torch.arange(-1.5, 2.5, step)[:, None, None].expand( -1, batch_size, dim) log_prob = dist.log_prob(x) prob = log_prob.exp() * step self.assertTensorClose( prob.sum(dim=0), torch.ones((batch_size, )), 0.01) # Test samples are within bound samples = dist.rsample((1000, )) self.assertTrue((samples > lower_bound).all()) self.assertTrue((samples < upper_bound).all()) def test_truncated_normal(self): self._test_truncated(ad.NormalITS()) def test_truncated_cauchy(self): self._test_truncated(ad.CauchyITS()) def test_truncated_T2(self): self._test_truncated(ad.T2ITS()) def test_truncated_normal_mode(self): dist = ad.TruncatedNormal( loc=torch.Tensor([[1.5, -3.0, 4.5]]), scale=torch.tensor([[0.8, 1.9, 1.2]]), lower_bound=torch.tensor([1.0, 1.0, 1.0]), upper_bound=torch.tensor([2.0, 2.0, 2.0])) self.assertTrue(torch.all(torch.tensor([1.5, 1.0, 2.0]) == dist.mode)) def test_truncated_normal_kl_divergence(self): def _numerical_kl_divergence(lower_bound, upper_bound, loc_p, scale_p, loc_q, scale_q): p = ad.TruncatedNormal(loc_p, scale_p, lower_bound, upper_bound) q = ad.TruncatedNormal(loc_q, scale_q, lower_bound, upper_bound) delta = 1e-3 accu = torch.as_tensor(0.0) for x in np.arange(lower_bound, upper_bound, delta): log_p_x = p.log_prob(torch.as_tensor(x)) log_q_x = q.log_prob(torch.as_tensor(x)) accu += torch.exp(log_p_x) * (log_p_x - log_q_x) * delta return accu dim = 1 lower_bound = -1.5 * torch.ones(dim) upper_bound = 2.5 * torch.ones(dim) batch_size = 4 loc1 = torch.ones((batch_size, dim)) loc1[0, :] = -2.0 loc1[1, :] = -1.0 loc1[2, :] = 0.0 loc1[3, :] = 1.0 scale1 = torch.ones((batch_size, dim)) scale1[1, :] = 0.5 scale1[2, :] = 1.5 scale1[3, :] = 2.56 dist1 = ad.TruncatedNormal( loc=loc1, scale=scale1, lower_bound=lower_bound, upper_bound=upper_bound) loc2 = torch.ones((batch_size, dim)) loc2[0, :] = -1.0 loc2[1, :] = -2.0 loc2[2, :] = 1.0 loc2[3, :] = 3.0 scale2 = torch.ones((batch_size, dim)) scale2[0, :] = 0.2 scale2[1, :] = 1.5 scale2[2, :] = 0.5 dist2 = ad.TruncatedNormal( loc=loc2, scale=scale2, lower_bound=lower_bound, upper_bound=upper_bound) kl = torch.distributions.kl_divergence(dist1, dist2) for i in range(batch_size): expected = _numerical_kl_divergence(lower_bound[0], upper_bound[0], loc1[i][0], scale1[i][0], loc2[i][0], scale2[i][0]) np.testing.assert_array_almost_equal(kl[i], expected, decimal=3) if __name__ == '__main__': alf.test.main()
alf/utils/distributions_test.py
import numpy as np import torch import alf.utils.distributions as ad import alf class DistributionTest(alf.test.TestCase): def _test_its(self, x, its: ad.InverseTransformSampling): x.requires_grad_() y = its.cdf(x) x1 = its.icdf(y) p = its.log_prob(x).exp() step = x[1] - x[0] psum = p.sum() * step self.assertAlmostEqual(psum, 1., delta=0.01) self.assertTensorClose(x1, x, 0.01) grad = torch.autograd.grad(y.sum(), x)[0] self.assertTensorClose(grad.log(), p.log()) def test_normal_its(self): self._test_its(torch.arange(-4., 4., 1 / 128), ad.NormalITS()) def test_cauchy_its(self): self._test_its(torch.arange(-100., 100., 1 / 128), ad.CauchyITS()) def test_t3_its(self): self._test_its(torch.arange(-20., 20., 1 / 128), ad.T2ITS()) def _test_truncated(self, its: ad.InverseTransformSampling): batch_size = 6 dim = 1 lower_bound = -1.5 * torch.ones(dim) upper_bound = 2.5 * torch.ones(dim) loc = torch.ones((batch_size, dim)) loc[0, :] = -2 loc[1, :] = -1 loc[2, :] = 0 loc[3, :] = 1 loc[4, :] = 2 loc[5, :] = 2 scale = torch.ones((6, dim)) scale[2, :] = 0.5 scale[3, :] = 1.5 dist = ad.TruncatedDistribution( loc=loc, scale=scale, lower_bound=lower_bound, upper_bound=upper_bound, its=its) # Test prob sum to 1. step = 1 / 128 x = torch.arange(-1.5, 2.5, step)[:, None, None].expand( -1, batch_size, dim) log_prob = dist.log_prob(x) prob = log_prob.exp() * step self.assertTensorClose( prob.sum(dim=0), torch.ones((batch_size, )), 0.01) # Test samples are within bound samples = dist.rsample((1000, )) self.assertTrue((samples > lower_bound).all()) self.assertTrue((samples < upper_bound).all()) def test_truncated_normal(self): self._test_truncated(ad.NormalITS()) def test_truncated_cauchy(self): self._test_truncated(ad.CauchyITS()) def test_truncated_T2(self): self._test_truncated(ad.T2ITS()) def test_truncated_normal_mode(self): dist = ad.TruncatedNormal( loc=torch.Tensor([[1.5, -3.0, 4.5]]), scale=torch.tensor([[0.8, 1.9, 1.2]]), lower_bound=torch.tensor([1.0, 1.0, 1.0]), upper_bound=torch.tensor([2.0, 2.0, 2.0])) self.assertTrue(torch.all(torch.tensor([1.5, 1.0, 2.0]) == dist.mode)) def test_truncated_normal_kl_divergence(self): def _numerical_kl_divergence(lower_bound, upper_bound, loc_p, scale_p, loc_q, scale_q): p = ad.TruncatedNormal(loc_p, scale_p, lower_bound, upper_bound) q = ad.TruncatedNormal(loc_q, scale_q, lower_bound, upper_bound) delta = 1e-3 accu = torch.as_tensor(0.0) for x in np.arange(lower_bound, upper_bound, delta): log_p_x = p.log_prob(torch.as_tensor(x)) log_q_x = q.log_prob(torch.as_tensor(x)) accu += torch.exp(log_p_x) * (log_p_x - log_q_x) * delta return accu dim = 1 lower_bound = -1.5 * torch.ones(dim) upper_bound = 2.5 * torch.ones(dim) batch_size = 4 loc1 = torch.ones((batch_size, dim)) loc1[0, :] = -2.0 loc1[1, :] = -1.0 loc1[2, :] = 0.0 loc1[3, :] = 1.0 scale1 = torch.ones((batch_size, dim)) scale1[1, :] = 0.5 scale1[2, :] = 1.5 scale1[3, :] = 2.56 dist1 = ad.TruncatedNormal( loc=loc1, scale=scale1, lower_bound=lower_bound, upper_bound=upper_bound) loc2 = torch.ones((batch_size, dim)) loc2[0, :] = -1.0 loc2[1, :] = -2.0 loc2[2, :] = 1.0 loc2[3, :] = 3.0 scale2 = torch.ones((batch_size, dim)) scale2[0, :] = 0.2 scale2[1, :] = 1.5 scale2[2, :] = 0.5 dist2 = ad.TruncatedNormal( loc=loc2, scale=scale2, lower_bound=lower_bound, upper_bound=upper_bound) kl = torch.distributions.kl_divergence(dist1, dist2) for i in range(batch_size): expected = _numerical_kl_divergence(lower_bound[0], upper_bound[0], loc1[i][0], scale1[i][0], loc2[i][0], scale2[i][0]) np.testing.assert_array_almost_equal(kl[i], expected, decimal=3) if __name__ == '__main__': alf.test.main()
0.722821
0.761671
from .base_random_cell import BaseRandomCellTransform import numpy as np import pandas as pd class ShuffleNoise(BaseRandomCellTransform): """A batch transformation for adding noise to data by randomly shuffling columns. The noise is added by mixing incoming batch with its shuffled version using mask: ```python batch = batch.mask(mask, shuffled_batch) ``` **Parameters** - **n_probs** - a *list*, *tuple* or a *one dimensional numpy array* of probabilities $p_0, p_1, p_2, ... p_n$. $p_0$ is a probability for a row to have 0 augmented elements (no augmentation), $p_1$ - one random cells, $p_2$ - two random cells, etc. A parameter must have at least 2 values, scalars are not accepted - **cols** - a *list*, *tuple* or *one dimensional numpy array* of strings with columns names to be transformed Number of columns must be greater or equal the length of **n_probs** parameter simply because there must be enough columns to choose from to augment n elements in a row - **col_probs** - (optional) a *list*, *tuple* or *one dimensional numpy array* of floats $p_{c_0}, p_{c_1}, ... p_{c_k}$ where k is the number of columns specified in parameter cols. $p_{c_0}$ is the probability of column 0 from parameter *cols* to be selected in when only one column is picked for augmentation. $p_{c_1}$ is the same for column 1, etc. It is important to understand that when two or more columns, are picked for a row, actual frequencies of columns will drift towards equal distribution with every new item added. In a case when number of columns picked for augmentation reaches its max allowed value (number of columns available to choose from parameter **cols**), there will be no choice and the actual counts of columns will be equal. This means the actual distribution will turn into a uniform discrete distribution. **Default: None** """ def _make_augmented_version(self, batch): augmented_batch = batch.apply(lambda x: x.sample(frac=1).values) return augmented_batch
keras_batchflow/base/batch_transformers/shuffle_noise.py
from .base_random_cell import BaseRandomCellTransform import numpy as np import pandas as pd class ShuffleNoise(BaseRandomCellTransform): """A batch transformation for adding noise to data by randomly shuffling columns. The noise is added by mixing incoming batch with its shuffled version using mask: ```python batch = batch.mask(mask, shuffled_batch) ``` **Parameters** - **n_probs** - a *list*, *tuple* or a *one dimensional numpy array* of probabilities $p_0, p_1, p_2, ... p_n$. $p_0$ is a probability for a row to have 0 augmented elements (no augmentation), $p_1$ - one random cells, $p_2$ - two random cells, etc. A parameter must have at least 2 values, scalars are not accepted - **cols** - a *list*, *tuple* or *one dimensional numpy array* of strings with columns names to be transformed Number of columns must be greater or equal the length of **n_probs** parameter simply because there must be enough columns to choose from to augment n elements in a row - **col_probs** - (optional) a *list*, *tuple* or *one dimensional numpy array* of floats $p_{c_0}, p_{c_1}, ... p_{c_k}$ where k is the number of columns specified in parameter cols. $p_{c_0}$ is the probability of column 0 from parameter *cols* to be selected in when only one column is picked for augmentation. $p_{c_1}$ is the same for column 1, etc. It is important to understand that when two or more columns, are picked for a row, actual frequencies of columns will drift towards equal distribution with every new item added. In a case when number of columns picked for augmentation reaches its max allowed value (number of columns available to choose from parameter **cols**), there will be no choice and the actual counts of columns will be equal. This means the actual distribution will turn into a uniform discrete distribution. **Default: None** """ def _make_augmented_version(self, batch): augmented_batch = batch.apply(lambda x: x.sample(frac=1).values) return augmented_batch
0.885792
0.902952
from pathlib import Path from typing import Callable, Iterable, Dict import re from io import BytesIO from collections import defaultdict import nlzss11 from .bzs import ParsedBzs, parseBzs, buildBzs from .msb import ParsedMsb, parseMSB, buildMSB from .u8file import U8File STAGE_REGEX = re.compile('(.+)_stg_l([0-9]+).arc.LZ') EVENT_REGEX = re.compile('([0-9])-[A-Za-z]+.arc') LANGUAGES = {'EU': 'en_GB', 'US': 'en_US'} # no idea for JP EXTRACTS = { ('D003_0', 0): ['GetTriForceSingle'], # Triforce part ('D301', 0): ['GetBowA'], # Bow ('F001r', 3):[ 'GetKobunALetter', # Cawlin's Letter 'GetPouchA' # Adventure Pouch ], ('F002r', 1):[ 'GetPouchB', # Extra Pouch Slot 'GetMedal', # all Medals 'GetNetA' # Bug Net ], ('F004r', 0):[ 'GetPachinkoB', # Scatershot 'GetBowB', # Iron Bow 'GetBowC', # Sacred Bow 'GetBeetleC', # Quick beetle 'GetBeetleD', # Though Beetle 'GetNetB' # Big Bug Net # a bunch more bottles and other stuff is also here ], ('F202', 1): [ 'GetPachinkoA', # slingshot 'GetHookShot', # clawshots 'GetMoleGloveB', # mogma mitts 'GetVacuum', # gust bellows 'GetWhip', # whip 'GetBombBag' # bomb bag ], ('F210', 0):['GetMoleGloveA'], # digging mitts ('S100', 2):['GetSizuku'], # water dragon scale ('S200', 2):['GetEarring'], # fireshield earrings ('D100', 1):['GetBeetleA'], # beetle ('F300', 0):['GetBeetleB'], # hook beetle ('F301_5', 0):['GetMapSea'], # Sand Sea Map ('F402', 2):['GetHarp'], # all Songs & Harp ('F000', 0):[ 'MoldoGut_Baby', # babies rattle 'GetSeedLife' # LTS ], ('F000', 4):[ 'GetShieldWood', # wooden shield 'GetShieldHylia' # hylian shield ], ('F100', 3):[ # stuff for silent realms 'PLHarpPlay', 'SirenEntrance', 'PLSwordStick' ], ('F020', 1):['GetBirdStatue'], # Bird statuette ('F023', 0):['GetTerryCage'], # Beedle's Beetle } class Patcher: def __init__(self, actual_extract_path: Path, modified_extract_path: Path, oarc_cache_path: Path, keep_path: bool=True, copy_unmodified: bool=True): """ Creates a new instance of the Patcher actual_extract_path: a path pointing to the root directory of the extracted game, so that it has the subdirectories DATA and UPDATE modified_extract_path: a path where to write the patched files to, should be a copy of the actual extract if intended to be repacked into an iso keep_path: whether or not to keep the path structure of the original files, set to True if repacking the modified files into an iso and to files if using Riivolution copy_unmodified: If unmodified Stage and Event files should be copied, other files are never copied """ self.actual_extract_path = actual_extract_path self.modified_extract_path = modified_extract_path self.oarc_cache_path = oarc_cache_path self.keep_path = keep_path self.copy_unmodified = copy_unmodified self.stage_oarc_add={} self.stage_patches={} self.room_patches=defaultdict(dict) self.event_patches={} def add_stage_oarc(self, stage: str, layer: int, oarcs: Iterable[str]): self.stage_oarc_add[(stage, layer)] = oarcs def set_stage_patch(self, stage: str, patchfunc: Callable[[ParsedBzs], ParsedBzs]): self.stage_patches[stage] = patchfunc def set_room_patch(self, stage: str, room: int, patchfunc: Callable[[ParsedBzs], ParsedBzs]): self.room_patches[stage][room] = patchfunc def set_event_patch(self, event: str, patchfunc: Callable[[ParsedMsb], ParsedMsb]): self.event_patches[event] = patchfunc def create_oarc_cache(self): self.oarc_cache_path.mkdir(parents=True, exist_ok=True) for (stage, layer), objs in EXTRACTS.items(): data = (self.actual_extract_path/'DATA'/'files'/'Stage'/f'{stage}'/f'{stage}_stg_l{layer}.arc.LZ').read_bytes() data = nlzss11.decompress(data) data = U8File.parse_u8(BytesIO(data)) for objname in objs: outdata=data.get_file_data(f'oarc/{objname}.arc') (self.oarc_cache_path / f'{objname}.arc').write_bytes(outdata) def do_patch(self): self.modified_extract_path.mkdir(parents=True, exist_ok=True) # set for all stage, layer combination that need to be modified stages_layer_to_patch=set() stages_layer_to_patch.update(self.stage_oarc_add.keys()) stages_layer_to_patch.update((stage, 0) for stage in self.stage_patches.keys()) stages_layer_to_patch.update((stage, 0) for stage, room in self.room_patches.items()) # stages for stagepath in (self.actual_extract_path/'DATA'/'files'/'Stage').glob('*/*_stg_l*.arc.LZ'): match = STAGE_REGEX.match(stagepath.parts[-1]) stage = match[1] layer = int(match[2]) if self.keep_path: modified_stagepatch = self.modified_extract_path/'DATA'/'files'/'Stage'/f'{stage}'/f'{stage}_stg_l{layer}.arc.LZ' else: modified_stagepatch = self.modified_extract_path/f'{stage}_stg_l{layer}.arc.LZ' if not (stage, layer) in stages_layer_to_patch: if self.copy_unmodified: modified_stagepatch.write_bytes(stagepath.read_bytes()) print(f'copied {stage} l{layer}') else: stagedata = nlzss11.decompress(stagepath.read_bytes()) stageu8 = U8File.parse_u8(BytesIO(stagedata)) # add additional arcs if needed for arc in self.stage_oarc_add.get((stage, layer), []): oarc_bytes = (self.oarc_cache_path / f'{arc}.arc').read_bytes() stageu8.add_file_data(f'oarc/{arc}.arc', oarc_bytes) # patch stage bzs if needed if stage in self.stage_patches: stagebzs = parseBzs(stageu8.get_file_data('dat/stage.bzs')) stagebzs = self.stage_patches[stage](stagebzs) stageu8.set_file_data('dat/stage.bzs', buildBzs(stagebzs)) # patch all rooms that are needed for roomid, patchfunc in self.room_patches[stage].items(): roomarc = U8File.parse_u8(BytesIO(stageu8.get_file_data(f'rarc/{stage}_r{roomid:02}.arc'))) roombzs = parseBzs(roomarc.get_file_data('dat/room.bzs')) roombzs = patchfunc(roombzs) roomarc.set_file_data('dat/room.bzs', buildBzs(roombzs)) stageu8.set_file_data(f'rarc/{stage}_r{roomid:02}.arc', roomarc.to_buffer()) # repack u8 and compress it stagedata = stageu8.to_buffer() modified_stagepatch.write_bytes(nlzss11.compress(stagedata)) print(f'patched {stage} l{layer}') # events eventrootpath = None modified_eventrootpath = None # check target language for path, lang in LANGUAGES.items(): if (self.actual_extract_path/'DATA'/'files'/path).exists(): eventrootpath = self.actual_extract_path/'DATA'/'files'/path/'Object'/lang if self.keep_path: modified_eventrootpath = self.modified_extract_path/'DATA'/'files'/path/'Object'/lang else: modified_eventrootpath = self.modified_extract_path break if eventrootpath == None: raise Exception('Event files not found') needed_eventfiles = set(x[0] for x in self.event_patches.keys()) # first letter determines which file to use for eventpath in eventrootpath.glob('*.arc'): filename = eventpath.parts[-1] match = EVENT_REGEX.match(filename) eventfilenum = match[1] modified_eventpath = modified_eventrootpath / filename if not eventfilenum in needed_eventfiles: if self.copy_unmodified: modified_eventpath.write_bytes(eventpath.read_bytes()) print(f'copied {filename}') else: eventarc = U8File.parse_u8(BytesIO(eventpath.read_bytes())) for file, patchfunc in self.event_patches.items(): if not str(eventfilenum) == file[0]: # first letter determines which file to use continue parsedMsb = parseMSB(eventarc.get_file_data(f'{filename[:-4]}/{file}')) parsedMsb = patchfunc(parsedMsb) eventarc.set_file_data(f'{filename[:-4]}/{file}', buildMSB(parsedMsb)) modified_eventpath.write_bytes(eventarc.to_buffer()) print(f'patched {filename}')
sslib/patch.py
from pathlib import Path from typing import Callable, Iterable, Dict import re from io import BytesIO from collections import defaultdict import nlzss11 from .bzs import ParsedBzs, parseBzs, buildBzs from .msb import ParsedMsb, parseMSB, buildMSB from .u8file import U8File STAGE_REGEX = re.compile('(.+)_stg_l([0-9]+).arc.LZ') EVENT_REGEX = re.compile('([0-9])-[A-Za-z]+.arc') LANGUAGES = {'EU': 'en_GB', 'US': 'en_US'} # no idea for JP EXTRACTS = { ('D003_0', 0): ['GetTriForceSingle'], # Triforce part ('D301', 0): ['GetBowA'], # Bow ('F001r', 3):[ 'GetKobunALetter', # Cawlin's Letter 'GetPouchA' # Adventure Pouch ], ('F002r', 1):[ 'GetPouchB', # Extra Pouch Slot 'GetMedal', # all Medals 'GetNetA' # Bug Net ], ('F004r', 0):[ 'GetPachinkoB', # Scatershot 'GetBowB', # Iron Bow 'GetBowC', # Sacred Bow 'GetBeetleC', # Quick beetle 'GetBeetleD', # Though Beetle 'GetNetB' # Big Bug Net # a bunch more bottles and other stuff is also here ], ('F202', 1): [ 'GetPachinkoA', # slingshot 'GetHookShot', # clawshots 'GetMoleGloveB', # mogma mitts 'GetVacuum', # gust bellows 'GetWhip', # whip 'GetBombBag' # bomb bag ], ('F210', 0):['GetMoleGloveA'], # digging mitts ('S100', 2):['GetSizuku'], # water dragon scale ('S200', 2):['GetEarring'], # fireshield earrings ('D100', 1):['GetBeetleA'], # beetle ('F300', 0):['GetBeetleB'], # hook beetle ('F301_5', 0):['GetMapSea'], # Sand Sea Map ('F402', 2):['GetHarp'], # all Songs & Harp ('F000', 0):[ 'MoldoGut_Baby', # babies rattle 'GetSeedLife' # LTS ], ('F000', 4):[ 'GetShieldWood', # wooden shield 'GetShieldHylia' # hylian shield ], ('F100', 3):[ # stuff for silent realms 'PLHarpPlay', 'SirenEntrance', 'PLSwordStick' ], ('F020', 1):['GetBirdStatue'], # Bird statuette ('F023', 0):['GetTerryCage'], # Beedle's Beetle } class Patcher: def __init__(self, actual_extract_path: Path, modified_extract_path: Path, oarc_cache_path: Path, keep_path: bool=True, copy_unmodified: bool=True): """ Creates a new instance of the Patcher actual_extract_path: a path pointing to the root directory of the extracted game, so that it has the subdirectories DATA and UPDATE modified_extract_path: a path where to write the patched files to, should be a copy of the actual extract if intended to be repacked into an iso keep_path: whether or not to keep the path structure of the original files, set to True if repacking the modified files into an iso and to files if using Riivolution copy_unmodified: If unmodified Stage and Event files should be copied, other files are never copied """ self.actual_extract_path = actual_extract_path self.modified_extract_path = modified_extract_path self.oarc_cache_path = oarc_cache_path self.keep_path = keep_path self.copy_unmodified = copy_unmodified self.stage_oarc_add={} self.stage_patches={} self.room_patches=defaultdict(dict) self.event_patches={} def add_stage_oarc(self, stage: str, layer: int, oarcs: Iterable[str]): self.stage_oarc_add[(stage, layer)] = oarcs def set_stage_patch(self, stage: str, patchfunc: Callable[[ParsedBzs], ParsedBzs]): self.stage_patches[stage] = patchfunc def set_room_patch(self, stage: str, room: int, patchfunc: Callable[[ParsedBzs], ParsedBzs]): self.room_patches[stage][room] = patchfunc def set_event_patch(self, event: str, patchfunc: Callable[[ParsedMsb], ParsedMsb]): self.event_patches[event] = patchfunc def create_oarc_cache(self): self.oarc_cache_path.mkdir(parents=True, exist_ok=True) for (stage, layer), objs in EXTRACTS.items(): data = (self.actual_extract_path/'DATA'/'files'/'Stage'/f'{stage}'/f'{stage}_stg_l{layer}.arc.LZ').read_bytes() data = nlzss11.decompress(data) data = U8File.parse_u8(BytesIO(data)) for objname in objs: outdata=data.get_file_data(f'oarc/{objname}.arc') (self.oarc_cache_path / f'{objname}.arc').write_bytes(outdata) def do_patch(self): self.modified_extract_path.mkdir(parents=True, exist_ok=True) # set for all stage, layer combination that need to be modified stages_layer_to_patch=set() stages_layer_to_patch.update(self.stage_oarc_add.keys()) stages_layer_to_patch.update((stage, 0) for stage in self.stage_patches.keys()) stages_layer_to_patch.update((stage, 0) for stage, room in self.room_patches.items()) # stages for stagepath in (self.actual_extract_path/'DATA'/'files'/'Stage').glob('*/*_stg_l*.arc.LZ'): match = STAGE_REGEX.match(stagepath.parts[-1]) stage = match[1] layer = int(match[2]) if self.keep_path: modified_stagepatch = self.modified_extract_path/'DATA'/'files'/'Stage'/f'{stage}'/f'{stage}_stg_l{layer}.arc.LZ' else: modified_stagepatch = self.modified_extract_path/f'{stage}_stg_l{layer}.arc.LZ' if not (stage, layer) in stages_layer_to_patch: if self.copy_unmodified: modified_stagepatch.write_bytes(stagepath.read_bytes()) print(f'copied {stage} l{layer}') else: stagedata = nlzss11.decompress(stagepath.read_bytes()) stageu8 = U8File.parse_u8(BytesIO(stagedata)) # add additional arcs if needed for arc in self.stage_oarc_add.get((stage, layer), []): oarc_bytes = (self.oarc_cache_path / f'{arc}.arc').read_bytes() stageu8.add_file_data(f'oarc/{arc}.arc', oarc_bytes) # patch stage bzs if needed if stage in self.stage_patches: stagebzs = parseBzs(stageu8.get_file_data('dat/stage.bzs')) stagebzs = self.stage_patches[stage](stagebzs) stageu8.set_file_data('dat/stage.bzs', buildBzs(stagebzs)) # patch all rooms that are needed for roomid, patchfunc in self.room_patches[stage].items(): roomarc = U8File.parse_u8(BytesIO(stageu8.get_file_data(f'rarc/{stage}_r{roomid:02}.arc'))) roombzs = parseBzs(roomarc.get_file_data('dat/room.bzs')) roombzs = patchfunc(roombzs) roomarc.set_file_data('dat/room.bzs', buildBzs(roombzs)) stageu8.set_file_data(f'rarc/{stage}_r{roomid:02}.arc', roomarc.to_buffer()) # repack u8 and compress it stagedata = stageu8.to_buffer() modified_stagepatch.write_bytes(nlzss11.compress(stagedata)) print(f'patched {stage} l{layer}') # events eventrootpath = None modified_eventrootpath = None # check target language for path, lang in LANGUAGES.items(): if (self.actual_extract_path/'DATA'/'files'/path).exists(): eventrootpath = self.actual_extract_path/'DATA'/'files'/path/'Object'/lang if self.keep_path: modified_eventrootpath = self.modified_extract_path/'DATA'/'files'/path/'Object'/lang else: modified_eventrootpath = self.modified_extract_path break if eventrootpath == None: raise Exception('Event files not found') needed_eventfiles = set(x[0] for x in self.event_patches.keys()) # first letter determines which file to use for eventpath in eventrootpath.glob('*.arc'): filename = eventpath.parts[-1] match = EVENT_REGEX.match(filename) eventfilenum = match[1] modified_eventpath = modified_eventrootpath / filename if not eventfilenum in needed_eventfiles: if self.copy_unmodified: modified_eventpath.write_bytes(eventpath.read_bytes()) print(f'copied {filename}') else: eventarc = U8File.parse_u8(BytesIO(eventpath.read_bytes())) for file, patchfunc in self.event_patches.items(): if not str(eventfilenum) == file[0]: # first letter determines which file to use continue parsedMsb = parseMSB(eventarc.get_file_data(f'{filename[:-4]}/{file}')) parsedMsb = patchfunc(parsedMsb) eventarc.set_file_data(f'{filename[:-4]}/{file}', buildMSB(parsedMsb)) modified_eventpath.write_bytes(eventarc.to_buffer()) print(f'patched {filename}')
0.467575
0.194521
# standard and third party libraries import cv2 import numpy as np import sys import time import copy import multiprocessing import logging import Image # milovision libraries from pipeline_modules import ContourFinder from pipeline_modules import EllipseFitter from pipeline_modules import PoseEstimatorA from simulator import GL_Simulator from output import Pipeline_Output, Printer from camera_values import Camera_Vals from marker import Marker class Pipeline(object): """ The Pipeline class contains the main application loop and instantiates and runs the required image processing modules as well as the optional simulator. """ def __init__(self, options = None): """ sets logger, verbosity, and other execution variables """ self.logger = logging.getLogger('Pipeline') self.options = options self.logger.info('initialised') self.windows = [] self.modules = [] self.loops = 0 self.single_img = False self.fwcam = None self.processes = [] self.outputs = [] self.new_output = False self.start = time.time() self.ellipses = None self.already_shutting_down = False def set_fwcam(self, fwcam): """ sets the pipeline's pydc1394 camera object """ self.fwcam = fwcam def set_image(self, image): """ loads a single image from disk """ self.orig = np.copy(image) self.canvas = np.copy(self.orig) self.single_img = True def stop(self): """ Sets the stop variables that trigger pipeline shutdown. Sends a stop message to the simulator if present, and waits for the simulator process to halt. """ self.end = time.time() self.running = False self.logger.info('stopping pipeline') if self.options.simulate is not None: self.logger.info('waiting for simulator') for process in self.processes: self.q2sim.put('stop') process.join() self.logger.info('simulator complete') def cleanup(self): """ closes any OpenCV windows and/or camera to enable a clean exit """ for window in self.windows: cv2.destroyWindow(window) # opencv bug: only closes windows at exit if hasattr(self, 'fwcam'): if self.fwcam: self.fwcam.stop() self.logger.info('cleanup completed') def shutdown(self): """ main exit routine with logging tasks; runs printer if required """ self.stop() if self.already_shutting_down: self.logger.error('multiple shutdown attempts') sys.exit(0) self.already_shutting_down = True duration = self.end - self.start if self.modules: self.logger.info('processed %d images' % self.loops) self.logger.info('avg rate: %f fps' % (self.loops / duration)) else: self.logger.info('loops: %d' % self.loops) self.logger.info('avg rate: %f loops /sec' % (self.loops / duration)) avcts = 0.0 avels = 0.0 avmels = 0.0 if self.modules: if (len(self.modules) > 0) and self.loops > 0: avcts = self.modules[0].nr_conts / self.loops self.modules[0].logger.info('avg contours /img: %f' % avcts) if (len(self.modules) > 1) and self.loops > 0: avels = self.modules[1].nr_ellipses / (self.loops * 1.0) avmels = self.modules[1].nr_candidates / (self.loops * 1.0) self.modules[1].logger.info('pre-filter ellipses /img: %f' % avels) self.modules[1].logger.info('post-filter ellipses /img: %f' % avmels) if len(self.modules) > 2: msg = 'used lopt1 %d times' % self.modules[2].nrlopt1 self.modules[2].logger.info(msg) msg = 'used lopt2 %d times' % self.modules[2].nrlopt2 self.modules[2].logger.info(msg) msg = 'used lopt3 %d times' % self.modules[2].nrlopt3 self.modules[2].logger.info(msg) self.cleanup() printer = Printer(pipe = self) printer.final(outputs = self.outputs) self.logger.info('shutdown completed') sys.exit(0) def run(self): """ Main application function. Starts image stream from real or simulated camera (or loads a single image); initialises any pipeline modules; and then enters the main pipeline processing loop. Once in the loop the pipeline runs until a shutdown flag is set. The message queue from the simulator, if there is one, is checked on each loop iteration for image data and synchronisation messages (such as a shutdown message). """ self.running = True if self.fwcam and not self.single_img: self.fwcam.start(interactive = True) time.sleep(1) self.orig = np.copy(np.asarray(self.fwcam.current_image)) self.canv = np.copy(self.orig) self.init_output = Pipeline_Output(sim=False) self.init_output.cam = Camera_Vals(camera_id = 'chameleon1') self.init_output.markers.append(Marker(cam=self.init_output.cam)) elif self.options.simulate is not None: self.q2sim = multiprocessing.Queue() self.q2pipe = multiprocessing.Queue() queues = self.q2sim, self.q2pipe args = queues, self.options process = multiprocessing.Process(name='child', target=GL_Simulator, args=args) self.processes.append(process) process.start() self.init_output = Pipeline_Output(sim = True) self.q2sim.put(copy.deepcopy(self.init_output)) incoming = self.q2pipe.get() if 'stop' in incoming: self.shutdown() elif 'simulglob' in incoming: _, self.orig, output = incoming self.outputs.append(copy.deepcopy(output)) self.init_output.cam = self.outputs[0].cam m = [] if self.options.nr_modules == 0: self.logger.info('running an empty pipeline') else: if self.options.nr_modules >=1: self.modules.append(ContourFinder(pipeline = self)) if self.options.nr_modules >=2: self.modules.append(EllipseFitter(pipeline = self)) if self.options.nr_modules >=3: self.modules.append(PoseEstimatorA(pipeline = self)) self.logger.info('running with %d modules' % self.options.nr_modules) if self.options.windows: for module in self.modules: if not (module.__class__.__name__ == 'PoseEstimatorA'): self.windows.append(module.__class__.__name__) if self.single_img: for module in self.modules: module.run() if self.options.windows: cv2.imshow(module.__class__.__name__, self.canv) cv2.waitKey(2) time.sleep(5) self.shutdown() while self.running: if self.fwcam: self.orig = np.copy(np.asarray(self.fwcam.current_image)) if self.options.windows: cv2.imshow("original", self.orig) elif (self.options.simulate is not None) and self.outputs[-1].end_time: incoming = self.q2pipe.get() if 'stop' in incoming: self.running = False continue elif 'simulglob' in incoming: _, self.orig, output = incoming self.outputs.append(copy.deepcopy(output)) self.new_output = True else: self.logger.error('unknown in queue: \'%s\''% incoming) self.shutdown() self.canv = np.copy(self.orig) for module in self.modules: module.run() classname = module.__class__.__name__ if not (self.options.windows and classname == 'PoseEstimatorA'): cv2.imshow(module.__class__.__name__, self.canv) self.loops += 1 self.outputs[-1].complete() if self.ellipses: self.ellipses = None if self.options.windows: cv2.waitKey(2) if time.time() - self.start >= self.options.simtime: self.running = False self.shutdown()
pipeline.py
# standard and third party libraries import cv2 import numpy as np import sys import time import copy import multiprocessing import logging import Image # milovision libraries from pipeline_modules import ContourFinder from pipeline_modules import EllipseFitter from pipeline_modules import PoseEstimatorA from simulator import GL_Simulator from output import Pipeline_Output, Printer from camera_values import Camera_Vals from marker import Marker class Pipeline(object): """ The Pipeline class contains the main application loop and instantiates and runs the required image processing modules as well as the optional simulator. """ def __init__(self, options = None): """ sets logger, verbosity, and other execution variables """ self.logger = logging.getLogger('Pipeline') self.options = options self.logger.info('initialised') self.windows = [] self.modules = [] self.loops = 0 self.single_img = False self.fwcam = None self.processes = [] self.outputs = [] self.new_output = False self.start = time.time() self.ellipses = None self.already_shutting_down = False def set_fwcam(self, fwcam): """ sets the pipeline's pydc1394 camera object """ self.fwcam = fwcam def set_image(self, image): """ loads a single image from disk """ self.orig = np.copy(image) self.canvas = np.copy(self.orig) self.single_img = True def stop(self): """ Sets the stop variables that trigger pipeline shutdown. Sends a stop message to the simulator if present, and waits for the simulator process to halt. """ self.end = time.time() self.running = False self.logger.info('stopping pipeline') if self.options.simulate is not None: self.logger.info('waiting for simulator') for process in self.processes: self.q2sim.put('stop') process.join() self.logger.info('simulator complete') def cleanup(self): """ closes any OpenCV windows and/or camera to enable a clean exit """ for window in self.windows: cv2.destroyWindow(window) # opencv bug: only closes windows at exit if hasattr(self, 'fwcam'): if self.fwcam: self.fwcam.stop() self.logger.info('cleanup completed') def shutdown(self): """ main exit routine with logging tasks; runs printer if required """ self.stop() if self.already_shutting_down: self.logger.error('multiple shutdown attempts') sys.exit(0) self.already_shutting_down = True duration = self.end - self.start if self.modules: self.logger.info('processed %d images' % self.loops) self.logger.info('avg rate: %f fps' % (self.loops / duration)) else: self.logger.info('loops: %d' % self.loops) self.logger.info('avg rate: %f loops /sec' % (self.loops / duration)) avcts = 0.0 avels = 0.0 avmels = 0.0 if self.modules: if (len(self.modules) > 0) and self.loops > 0: avcts = self.modules[0].nr_conts / self.loops self.modules[0].logger.info('avg contours /img: %f' % avcts) if (len(self.modules) > 1) and self.loops > 0: avels = self.modules[1].nr_ellipses / (self.loops * 1.0) avmels = self.modules[1].nr_candidates / (self.loops * 1.0) self.modules[1].logger.info('pre-filter ellipses /img: %f' % avels) self.modules[1].logger.info('post-filter ellipses /img: %f' % avmels) if len(self.modules) > 2: msg = 'used lopt1 %d times' % self.modules[2].nrlopt1 self.modules[2].logger.info(msg) msg = 'used lopt2 %d times' % self.modules[2].nrlopt2 self.modules[2].logger.info(msg) msg = 'used lopt3 %d times' % self.modules[2].nrlopt3 self.modules[2].logger.info(msg) self.cleanup() printer = Printer(pipe = self) printer.final(outputs = self.outputs) self.logger.info('shutdown completed') sys.exit(0) def run(self): """ Main application function. Starts image stream from real or simulated camera (or loads a single image); initialises any pipeline modules; and then enters the main pipeline processing loop. Once in the loop the pipeline runs until a shutdown flag is set. The message queue from the simulator, if there is one, is checked on each loop iteration for image data and synchronisation messages (such as a shutdown message). """ self.running = True if self.fwcam and not self.single_img: self.fwcam.start(interactive = True) time.sleep(1) self.orig = np.copy(np.asarray(self.fwcam.current_image)) self.canv = np.copy(self.orig) self.init_output = Pipeline_Output(sim=False) self.init_output.cam = Camera_Vals(camera_id = 'chameleon1') self.init_output.markers.append(Marker(cam=self.init_output.cam)) elif self.options.simulate is not None: self.q2sim = multiprocessing.Queue() self.q2pipe = multiprocessing.Queue() queues = self.q2sim, self.q2pipe args = queues, self.options process = multiprocessing.Process(name='child', target=GL_Simulator, args=args) self.processes.append(process) process.start() self.init_output = Pipeline_Output(sim = True) self.q2sim.put(copy.deepcopy(self.init_output)) incoming = self.q2pipe.get() if 'stop' in incoming: self.shutdown() elif 'simulglob' in incoming: _, self.orig, output = incoming self.outputs.append(copy.deepcopy(output)) self.init_output.cam = self.outputs[0].cam m = [] if self.options.nr_modules == 0: self.logger.info('running an empty pipeline') else: if self.options.nr_modules >=1: self.modules.append(ContourFinder(pipeline = self)) if self.options.nr_modules >=2: self.modules.append(EllipseFitter(pipeline = self)) if self.options.nr_modules >=3: self.modules.append(PoseEstimatorA(pipeline = self)) self.logger.info('running with %d modules' % self.options.nr_modules) if self.options.windows: for module in self.modules: if not (module.__class__.__name__ == 'PoseEstimatorA'): self.windows.append(module.__class__.__name__) if self.single_img: for module in self.modules: module.run() if self.options.windows: cv2.imshow(module.__class__.__name__, self.canv) cv2.waitKey(2) time.sleep(5) self.shutdown() while self.running: if self.fwcam: self.orig = np.copy(np.asarray(self.fwcam.current_image)) if self.options.windows: cv2.imshow("original", self.orig) elif (self.options.simulate is not None) and self.outputs[-1].end_time: incoming = self.q2pipe.get() if 'stop' in incoming: self.running = False continue elif 'simulglob' in incoming: _, self.orig, output = incoming self.outputs.append(copy.deepcopy(output)) self.new_output = True else: self.logger.error('unknown in queue: \'%s\''% incoming) self.shutdown() self.canv = np.copy(self.orig) for module in self.modules: module.run() classname = module.__class__.__name__ if not (self.options.windows and classname == 'PoseEstimatorA'): cv2.imshow(module.__class__.__name__, self.canv) self.loops += 1 self.outputs[-1].complete() if self.ellipses: self.ellipses = None if self.options.windows: cv2.waitKey(2) if time.time() - self.start >= self.options.simtime: self.running = False self.shutdown()
0.275812
0.160957
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation class LDA: """ Parameters ---------- n_topics : int Number of topics n_iter : int, default 2000 Number of sampling iterations alpha : float, default 0.1 Dirichlet parameter for distribution over topics eta : float, default 0.01 Dirichlet parameter for distribution over words random_state : int or RandomState, optional The generator used for the initial topics. Feature-related parameters: max_df: float, default 0.95, min_df=2, max_features """ def __init__(self, n_topics=10, n_iter=2000, alpha=0.1, eta=0.01, max_df=0.95, min_df=2, max_features=None): self.n_topics = n_topics self.n_iter = n_iter self.alpha = alpha self.eta = eta self.max_df = max_df self.min_df = min_df self.max_features = max_features def fit_model_TFIDF(self, data_samples): """ trains LDA model on the data_samples returns: the trained LDA_model, the vectorizer (configuration) and features (tfidf) """ tfidf_vectorizer = TfidfVectorizer(max_df=self.max_df, min_df=self.min_df, max_features=self.max_features, stop_words='english') tfidf = tfidf_vectorizer.fit_transform(data_samples) lda_model = LatentDirichletAllocation(n_components=self.n_topics, max_iter=self.n_iter, learning_method='online', learning_offset=10., random_state=0) lda_model.fit(tfidf) return lda_model, tfidf_vectorizer, tfidf def print_top_words(self, lda_model, feature_names, n_top_words): '''Prints the n top words from the model. :param model: The model :param feature_names: The feature names :param n_top_words: Number of top words ''' store_topics = [] for topic_idx, topic in enumerate(lda_model.components_): print("Topic #%d:" % topic_idx) topic_keywords = " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(topic_keywords) # store_topics.append(topic_keywords) print() # Utils.write_list_to_file("topic_keywords.txt", store_topics)
src/models/LDA.py
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation class LDA: """ Parameters ---------- n_topics : int Number of topics n_iter : int, default 2000 Number of sampling iterations alpha : float, default 0.1 Dirichlet parameter for distribution over topics eta : float, default 0.01 Dirichlet parameter for distribution over words random_state : int or RandomState, optional The generator used for the initial topics. Feature-related parameters: max_df: float, default 0.95, min_df=2, max_features """ def __init__(self, n_topics=10, n_iter=2000, alpha=0.1, eta=0.01, max_df=0.95, min_df=2, max_features=None): self.n_topics = n_topics self.n_iter = n_iter self.alpha = alpha self.eta = eta self.max_df = max_df self.min_df = min_df self.max_features = max_features def fit_model_TFIDF(self, data_samples): """ trains LDA model on the data_samples returns: the trained LDA_model, the vectorizer (configuration) and features (tfidf) """ tfidf_vectorizer = TfidfVectorizer(max_df=self.max_df, min_df=self.min_df, max_features=self.max_features, stop_words='english') tfidf = tfidf_vectorizer.fit_transform(data_samples) lda_model = LatentDirichletAllocation(n_components=self.n_topics, max_iter=self.n_iter, learning_method='online', learning_offset=10., random_state=0) lda_model.fit(tfidf) return lda_model, tfidf_vectorizer, tfidf def print_top_words(self, lda_model, feature_names, n_top_words): '''Prints the n top words from the model. :param model: The model :param feature_names: The feature names :param n_top_words: Number of top words ''' store_topics = [] for topic_idx, topic in enumerate(lda_model.components_): print("Topic #%d:" % topic_idx) topic_keywords = " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(topic_keywords) # store_topics.append(topic_keywords) print() # Utils.write_list_to_file("topic_keywords.txt", store_topics)
0.853073
0.402921
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class AccessLevel(pulumi.CustomResource): basic: pulumi.Output[dict] description: pulumi.Output[str] name: pulumi.Output[str] parent: pulumi.Output[str] title: pulumi.Output[str] def __init__(__self__, resource_name, opts=None, basic=None, description=None, name=None, parent=None, title=None, __name__=None, __opts__=None): """ An AccessLevel is a label that can be applied to requests to GCP services, along with a list of requirements necessary for the label to be applied. > **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. See [Provider Versions](https://terraform.io/docs/providers/google/provider_versions.html) for more details on beta resources. To get more information about AccessLevel, see: * [API documentation](https://cloud.google.com/access-context-manager/docs/reference/rest/v1beta/accessPolicies.accessLevels) * How-to Guides * [Access Policy Quickstart](https://cloud.google.com/access-context-manager/docs/quickstart) :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if not resource_name: raise TypeError('Missing resource name argument (for URN creation)') if not isinstance(resource_name, str): raise TypeError('Expected resource name to be a string') if opts and not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') __props__ = dict() __props__['basic'] = basic __props__['description'] = description __props__['name'] = name if parent is None: raise TypeError('Missing required property parent') __props__['parent'] = parent if title is None: raise TypeError('Missing required property title') __props__['title'] = title super(AccessLevel, __self__).__init__( 'gcp:accesscontextmanager/accessLevel:AccessLevel', resource_name, __props__, opts) def translate_output_property(self, prop): return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
sdk/python/pulumi_gcp/accesscontextmanager/access_level.py
import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class AccessLevel(pulumi.CustomResource): basic: pulumi.Output[dict] description: pulumi.Output[str] name: pulumi.Output[str] parent: pulumi.Output[str] title: pulumi.Output[str] def __init__(__self__, resource_name, opts=None, basic=None, description=None, name=None, parent=None, title=None, __name__=None, __opts__=None): """ An AccessLevel is a label that can be applied to requests to GCP services, along with a list of requirements necessary for the label to be applied. > **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. See [Provider Versions](https://terraform.io/docs/providers/google/provider_versions.html) for more details on beta resources. To get more information about AccessLevel, see: * [API documentation](https://cloud.google.com/access-context-manager/docs/reference/rest/v1beta/accessPolicies.accessLevels) * How-to Guides * [Access Policy Quickstart](https://cloud.google.com/access-context-manager/docs/quickstart) :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if not resource_name: raise TypeError('Missing resource name argument (for URN creation)') if not isinstance(resource_name, str): raise TypeError('Expected resource name to be a string') if opts and not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') __props__ = dict() __props__['basic'] = basic __props__['description'] = description __props__['name'] = name if parent is None: raise TypeError('Missing required property parent') __props__['parent'] = parent if title is None: raise TypeError('Missing required property title') __props__['title'] = title super(AccessLevel, __self__).__init__( 'gcp:accesscontextmanager/accessLevel:AccessLevel', resource_name, __props__, opts) def translate_output_property(self, prop): return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
0.505371
0.080177
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import models import util if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') def squared_l2_norm(x): flattened = x.view(x.unsqueeze(0).shape[0], -1) return (flattened ** 2).sum(1) def l2_norm(x): return squared_l2_norm(x).sqrt() class TradesLoss(nn.Module): def __init__(self, step_size=0.007, epsilon=0.031, perturb_steps=10, beta=6.0, distance='l_inf', ce=False, cutmix=False, adjust_freeze=True): super(TradesLoss, self).__init__() self.step_size = step_size self.epsilon = epsilon self.perturb_steps = perturb_steps self.beta = beta self.distance = distance self.ce = ce self.criterion_kl = nn.KLDivLoss(reduction='sum') self.cross_entropy = models.CutMixCrossEntropyLoss() if cutmix else torch.nn.CrossEntropyLoss() self.adjust_freeze = adjust_freeze def forward(self, model, x_natural, y, optimizer): # define KL-loss criterion_kl = self.criterion_kl model.eval() if self.adjust_freeze: for param in model.parameters(): param.requires_grad = False # generate adversarial example batch_size = len(x_natural) logits = model(x_natural) x_adv = x_natural.detach() + 0.001 * torch.randn(x_natural.shape).to(device).detach() if self.distance == 'l_inf': for _ in range(self.perturb_steps): x_adv.requires_grad_() if self.ce: loss_kl = self.cross_entropy(model(x_adv), y) else: loss_kl = criterion_kl(F.log_softmax(model(x_adv), dim=1), F.softmax(logits, dim=1)) grad = torch.autograd.grad(loss_kl, [x_adv])[0] x_adv = x_adv.detach() + self.step_size * torch.sign(grad.detach()) x_adv = torch.min(torch.max(x_adv, x_natural - self.epsilon), x_natural + self.epsilon) x_adv = torch.clamp(x_adv, 0.0, 1.0) elif self.distance == 'l_2': delta = 0.001 * torch.randn(x_natural.shape).cuda().detach() delta = Variable(delta.data, requires_grad=True) # Setup optimizers optimizer_delta = optim.SGD([delta], lr=self.epsilon / self.perturb_steps * 2) for _ in range(self.perturb_steps): adv = x_natural + delta # optimize optimizer_delta.zero_grad() loss = (-1) * criterion_kl(F.log_softmax(model(adv), dim=1), F.softmax(logits, dim=1)) loss.backward() # renorming gradient grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1) delta.grad.div_(grad_norms.view(-1, 1, 1, 1)) # avoid nan or inf if gradient is 0 if (grad_norms == 0).any(): delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0]) optimizer_delta.step() # projection delta.data.add_(x_natural) delta.data.clamp_(0, 1).sub_(x_natural) delta.data.renorm_(p=2, dim=0, maxnorm=self.epsilon) x_adv = Variable(x_natural + delta, requires_grad=False) else: x_adv = torch.clamp(x_adv, 0.0, 1.0) if self.adjust_freeze: for param in model.parameters(): param.requires_grad = True model.train() x_adv = Variable(torch.clamp(x_adv, 0.0, 1.0), requires_grad=False) # zero gradient optimizer.zero_grad() # calculate robust loss logits = model(x_natural) loss_natural = self.cross_entropy(logits, y) adv_logits = model(x_adv) loss_robust = (1.0 / batch_size) * criterion_kl(F.log_softmax(adv_logits, dim=1), F.softmax(logits, dim=1)) loss = loss_natural + self.beta * loss_robust return adv_logits, loss
trades.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import models import util if torch.cuda.is_available(): device = torch.device('cuda') else: device = torch.device('cpu') def squared_l2_norm(x): flattened = x.view(x.unsqueeze(0).shape[0], -1) return (flattened ** 2).sum(1) def l2_norm(x): return squared_l2_norm(x).sqrt() class TradesLoss(nn.Module): def __init__(self, step_size=0.007, epsilon=0.031, perturb_steps=10, beta=6.0, distance='l_inf', ce=False, cutmix=False, adjust_freeze=True): super(TradesLoss, self).__init__() self.step_size = step_size self.epsilon = epsilon self.perturb_steps = perturb_steps self.beta = beta self.distance = distance self.ce = ce self.criterion_kl = nn.KLDivLoss(reduction='sum') self.cross_entropy = models.CutMixCrossEntropyLoss() if cutmix else torch.nn.CrossEntropyLoss() self.adjust_freeze = adjust_freeze def forward(self, model, x_natural, y, optimizer): # define KL-loss criterion_kl = self.criterion_kl model.eval() if self.adjust_freeze: for param in model.parameters(): param.requires_grad = False # generate adversarial example batch_size = len(x_natural) logits = model(x_natural) x_adv = x_natural.detach() + 0.001 * torch.randn(x_natural.shape).to(device).detach() if self.distance == 'l_inf': for _ in range(self.perturb_steps): x_adv.requires_grad_() if self.ce: loss_kl = self.cross_entropy(model(x_adv), y) else: loss_kl = criterion_kl(F.log_softmax(model(x_adv), dim=1), F.softmax(logits, dim=1)) grad = torch.autograd.grad(loss_kl, [x_adv])[0] x_adv = x_adv.detach() + self.step_size * torch.sign(grad.detach()) x_adv = torch.min(torch.max(x_adv, x_natural - self.epsilon), x_natural + self.epsilon) x_adv = torch.clamp(x_adv, 0.0, 1.0) elif self.distance == 'l_2': delta = 0.001 * torch.randn(x_natural.shape).cuda().detach() delta = Variable(delta.data, requires_grad=True) # Setup optimizers optimizer_delta = optim.SGD([delta], lr=self.epsilon / self.perturb_steps * 2) for _ in range(self.perturb_steps): adv = x_natural + delta # optimize optimizer_delta.zero_grad() loss = (-1) * criterion_kl(F.log_softmax(model(adv), dim=1), F.softmax(logits, dim=1)) loss.backward() # renorming gradient grad_norms = delta.grad.view(batch_size, -1).norm(p=2, dim=1) delta.grad.div_(grad_norms.view(-1, 1, 1, 1)) # avoid nan or inf if gradient is 0 if (grad_norms == 0).any(): delta.grad[grad_norms == 0] = torch.randn_like(delta.grad[grad_norms == 0]) optimizer_delta.step() # projection delta.data.add_(x_natural) delta.data.clamp_(0, 1).sub_(x_natural) delta.data.renorm_(p=2, dim=0, maxnorm=self.epsilon) x_adv = Variable(x_natural + delta, requires_grad=False) else: x_adv = torch.clamp(x_adv, 0.0, 1.0) if self.adjust_freeze: for param in model.parameters(): param.requires_grad = True model.train() x_adv = Variable(torch.clamp(x_adv, 0.0, 1.0), requires_grad=False) # zero gradient optimizer.zero_grad() # calculate robust loss logits = model(x_natural) loss_natural = self.cross_entropy(logits, y) adv_logits = model(x_adv) loss_robust = (1.0 / batch_size) * criterion_kl(F.log_softmax(adv_logits, dim=1), F.softmax(logits, dim=1)) loss = loss_natural + self.beta * loss_robust return adv_logits, loss
0.927629
0.515864
import os from abc import abstractmethod from collections import OrderedDict import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from hydra import compose, initialize from ishtos_datasets import get_dataset from ishtos_models import get_model from ishtos_transforms import get_transforms from pytorch_grad_cam import GradCAMPlusPlus from pytorch_grad_cam.utils.image import show_cam_on_image from torch.utils.data import DataLoader from tqdm import tqdm class Runner: def __init__(self, config_name="config.yaml", ckpt="loss", batch_size=32): self.config = None self.df = None self.init(config_name, ckpt, batch_size) def init(self, config_name, ckpt, batch_size): self.load_config(config_name, batch_size) self.load_df() self.load_models(ckpt) def load_config(self, config_name, batch_size): with initialize(config_path="configs", job_name="config"): config = compose(config_name=config_name) config.dataset.loader.batch_size = batch_size config.dataset.store_valid = False self.config = config @abstractmethod def load_df(self): pass def load_model(self, fold, ckpt): model = get_model(self.config.model) state_dict = OrderedDict() ckpt_path = os.path.join( self.config.general.exp_dir, "checkpoints", ckpt, f"fold-{fold}.ckpt" ) for k, v in torch.load(ckpt_path)["state_dict"].items(): name = k.replace("model.", "", 1) state_dict[name] = v model.load_state_dict(state_dict) model.to("cuda") model.eval() return model def load_models(self, ckpt): self.ckpt = ckpt models = [] for fold in range(self.config.preprocess.fold.n_splits): model = self.load_model(fold, ckpt) models.append(model) self.models = models def load_dataloader(self, df, phase, apply_transforms=True): dataset = get_dataset(self.config, df, phase, apply_transforms) dataloader = DataLoader( dataset, batch_size=self.config.dataset.loader.batch_size, num_workers=self.config.dataset.loader.num_workers, shuffle=False, drop_last=False, pin_memory=False, ) return dataloader def oof(self, model, dataloader): oofs = [] with torch.inference_mode(): for images, _ in tqdm(dataloader): logits = model(images.to("cuda")).squeeze(1) preds = logits.softmax(dim=1).cpu().numpy() oofs.append(preds) return np.concatenate(oofs) def inference(self, model, dataloader): inferences = [] with torch.inference_mode(): for images in tqdm(dataloader): logits = model(images.to("cuda")).squeeze(1) preds = logits.softmax(dim=1).cpu().numpy() inferences.append(preds) return np.concatenate(inferences) class Validator(Runner): def load_df(self): df = pd.read_csv(self.config.dataset.train_csv) self.df = df def run_oof(self): oofs = np.zeros((len(self.df), self.config.model.params.num_classes)) for fold in range(self.config.preprocess.fold.n_splits): valid_df = self.df[self.df["fold"] == fold].reset_index(drop=True) model = self.models[fold] dataloader = self.load_dataloader(valid_df, "valid") oofs[valid_df.index] = self.oof(model, dataloader) self.oofs = oofs self.save_oof() def save_oof(self): df = self.df.copy() for i in range(self.config.model.params.num_classes): df[f"oof_{i}"] = self.oofs[:, i] df.to_csv( os.path.join(self.config.general.exp_dir, f"oof_{self.ckpt}.csv"), index=False, ) def load_cam(self, model, target_layers, reshape_transform=None): cam = GradCAMPlusPlus( model=model, target_layers=target_layers, use_cuda=True, reshape_transform=reshape_transform, ) return cam def get_target_layers(self, model_name, model): if model_name == "convnext": return [model.model.layers[-1].blocks[-1].norm1] elif model_name == "efficientnet": return [model.model.blocks[-1][-1].bn1] elif model_name == "resnet": return [model.model.layer4[-1]] elif model_name == "swin": return [model.model.layers[-1].blocks[-1].norm1] else: raise ValueError(f"Not supported model: {model_name}.") def get_reshape_transform(self, model_name): if model_name == "convnext": return reshape_transform elif model_name == "efficientnet": return None elif model_name == "resnet": return None elif model_name == "swin": return reshape_transform else: raise ValueError(f"Not supported model: {model_name}.") def run_cam(self): self.config.dataset.gradcam = True for fold in range(self.config.preprocess.fold.n_splits): valid_df = self.df[self.df["fold"] == fold].reset_index(drop=True) model = self.models[fold] dataloader = self.load_dataloader(valid_df, "valid", False) cam = self.load_cam( model, target_layers=self.get_target_layers(self.config.model.name, model), reshape_transform=self.get_reshape_transform(self.config.model.name), ) transforms = get_transforms(self.config, "valid") original_images, grayscale_cams, preds, labels = self.inference_cam( model, dataloader, transforms, cam ) self.save_cam(original_images, grayscale_cams, preds, labels, fold) def inference_cam(self, model, dataloader, transforms, cam): original_images, targets = iter(dataloader).next() images = torch.stack( [transforms(image=image.numpy())["image"] for image in original_images] ) logits = model(images.to("cuda")).squeeze(1) preds = torch.argmax(logits, dim=1).detach().cpu().numpy() labels = targets.detach().cpu().numpy() grayscale_cams = cam(input_tensor=images, targets=None, eigen_smooth=True) original_images = original_images.detach().cpu().numpy() / 255.0 return original_images, grayscale_cams, preds, labels def save_cam(self, original_images, grayscale_cams, preds, labels, fold): batch_size = self.config.dataset.loader.batch_size fig, axes = plt.subplots( batch_size // 4, 4, figsize=(32, 32), sharex=True, sharey=True ) for i, (image, grayscale_cam, pred, label) in enumerate( zip(original_images, grayscale_cams, preds, labels) ): visualization = show_cam_on_image(image, grayscale_cam) ax = axes[i // 4, i % 4] ax.set_title(f"pred: {pred:.1f}, label: {label}") ax.imshow(visualization) fig.savefig( os.path.join(self.config.general.exp_dir, f"cam_{self.ckpt}_{fold}.png") ) def reshape_transform(tensor, height=12, width=12): result = tensor.reshape(tensor.size(0), height, width, tensor.size(2)) result = result.permute(0, 3, 1, 2) return result class Tester(Runner): def load_df(self): df = pd.read_csv(self.config.dataset.test_csv) self.df = df def run_inference(self): inferences = np.zeros((len(self.df), self.config.model.params.num_classes)) for fold in range(self.config.preprocess.fold.n_splits): model = self.models[fold] dataloader = self.load_dataloader(self.df, "test") inferences += self.inference(model, dataloader) inferences = inferences / self.config.preprocess.fold.n_splits self.inferences = inferences self.save_inference() def save_inference(self): df = self.df.copy() df.loc[:, self.config.dataset.target] = self.inferences df.to_csv( os.path.join(self.config.general.exp_dir, f"inferences_{self.ckpt}.csv"), index=False, )
{{cookiecutter.package_name}}/src/exp_000/ishtos_runner.py
import os from abc import abstractmethod from collections import OrderedDict import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from hydra import compose, initialize from ishtos_datasets import get_dataset from ishtos_models import get_model from ishtos_transforms import get_transforms from pytorch_grad_cam import GradCAMPlusPlus from pytorch_grad_cam.utils.image import show_cam_on_image from torch.utils.data import DataLoader from tqdm import tqdm class Runner: def __init__(self, config_name="config.yaml", ckpt="loss", batch_size=32): self.config = None self.df = None self.init(config_name, ckpt, batch_size) def init(self, config_name, ckpt, batch_size): self.load_config(config_name, batch_size) self.load_df() self.load_models(ckpt) def load_config(self, config_name, batch_size): with initialize(config_path="configs", job_name="config"): config = compose(config_name=config_name) config.dataset.loader.batch_size = batch_size config.dataset.store_valid = False self.config = config @abstractmethod def load_df(self): pass def load_model(self, fold, ckpt): model = get_model(self.config.model) state_dict = OrderedDict() ckpt_path = os.path.join( self.config.general.exp_dir, "checkpoints", ckpt, f"fold-{fold}.ckpt" ) for k, v in torch.load(ckpt_path)["state_dict"].items(): name = k.replace("model.", "", 1) state_dict[name] = v model.load_state_dict(state_dict) model.to("cuda") model.eval() return model def load_models(self, ckpt): self.ckpt = ckpt models = [] for fold in range(self.config.preprocess.fold.n_splits): model = self.load_model(fold, ckpt) models.append(model) self.models = models def load_dataloader(self, df, phase, apply_transforms=True): dataset = get_dataset(self.config, df, phase, apply_transforms) dataloader = DataLoader( dataset, batch_size=self.config.dataset.loader.batch_size, num_workers=self.config.dataset.loader.num_workers, shuffle=False, drop_last=False, pin_memory=False, ) return dataloader def oof(self, model, dataloader): oofs = [] with torch.inference_mode(): for images, _ in tqdm(dataloader): logits = model(images.to("cuda")).squeeze(1) preds = logits.softmax(dim=1).cpu().numpy() oofs.append(preds) return np.concatenate(oofs) def inference(self, model, dataloader): inferences = [] with torch.inference_mode(): for images in tqdm(dataloader): logits = model(images.to("cuda")).squeeze(1) preds = logits.softmax(dim=1).cpu().numpy() inferences.append(preds) return np.concatenate(inferences) class Validator(Runner): def load_df(self): df = pd.read_csv(self.config.dataset.train_csv) self.df = df def run_oof(self): oofs = np.zeros((len(self.df), self.config.model.params.num_classes)) for fold in range(self.config.preprocess.fold.n_splits): valid_df = self.df[self.df["fold"] == fold].reset_index(drop=True) model = self.models[fold] dataloader = self.load_dataloader(valid_df, "valid") oofs[valid_df.index] = self.oof(model, dataloader) self.oofs = oofs self.save_oof() def save_oof(self): df = self.df.copy() for i in range(self.config.model.params.num_classes): df[f"oof_{i}"] = self.oofs[:, i] df.to_csv( os.path.join(self.config.general.exp_dir, f"oof_{self.ckpt}.csv"), index=False, ) def load_cam(self, model, target_layers, reshape_transform=None): cam = GradCAMPlusPlus( model=model, target_layers=target_layers, use_cuda=True, reshape_transform=reshape_transform, ) return cam def get_target_layers(self, model_name, model): if model_name == "convnext": return [model.model.layers[-1].blocks[-1].norm1] elif model_name == "efficientnet": return [model.model.blocks[-1][-1].bn1] elif model_name == "resnet": return [model.model.layer4[-1]] elif model_name == "swin": return [model.model.layers[-1].blocks[-1].norm1] else: raise ValueError(f"Not supported model: {model_name}.") def get_reshape_transform(self, model_name): if model_name == "convnext": return reshape_transform elif model_name == "efficientnet": return None elif model_name == "resnet": return None elif model_name == "swin": return reshape_transform else: raise ValueError(f"Not supported model: {model_name}.") def run_cam(self): self.config.dataset.gradcam = True for fold in range(self.config.preprocess.fold.n_splits): valid_df = self.df[self.df["fold"] == fold].reset_index(drop=True) model = self.models[fold] dataloader = self.load_dataloader(valid_df, "valid", False) cam = self.load_cam( model, target_layers=self.get_target_layers(self.config.model.name, model), reshape_transform=self.get_reshape_transform(self.config.model.name), ) transforms = get_transforms(self.config, "valid") original_images, grayscale_cams, preds, labels = self.inference_cam( model, dataloader, transforms, cam ) self.save_cam(original_images, grayscale_cams, preds, labels, fold) def inference_cam(self, model, dataloader, transforms, cam): original_images, targets = iter(dataloader).next() images = torch.stack( [transforms(image=image.numpy())["image"] for image in original_images] ) logits = model(images.to("cuda")).squeeze(1) preds = torch.argmax(logits, dim=1).detach().cpu().numpy() labels = targets.detach().cpu().numpy() grayscale_cams = cam(input_tensor=images, targets=None, eigen_smooth=True) original_images = original_images.detach().cpu().numpy() / 255.0 return original_images, grayscale_cams, preds, labels def save_cam(self, original_images, grayscale_cams, preds, labels, fold): batch_size = self.config.dataset.loader.batch_size fig, axes = plt.subplots( batch_size // 4, 4, figsize=(32, 32), sharex=True, sharey=True ) for i, (image, grayscale_cam, pred, label) in enumerate( zip(original_images, grayscale_cams, preds, labels) ): visualization = show_cam_on_image(image, grayscale_cam) ax = axes[i // 4, i % 4] ax.set_title(f"pred: {pred:.1f}, label: {label}") ax.imshow(visualization) fig.savefig( os.path.join(self.config.general.exp_dir, f"cam_{self.ckpt}_{fold}.png") ) def reshape_transform(tensor, height=12, width=12): result = tensor.reshape(tensor.size(0), height, width, tensor.size(2)) result = result.permute(0, 3, 1, 2) return result class Tester(Runner): def load_df(self): df = pd.read_csv(self.config.dataset.test_csv) self.df = df def run_inference(self): inferences = np.zeros((len(self.df), self.config.model.params.num_classes)) for fold in range(self.config.preprocess.fold.n_splits): model = self.models[fold] dataloader = self.load_dataloader(self.df, "test") inferences += self.inference(model, dataloader) inferences = inferences / self.config.preprocess.fold.n_splits self.inferences = inferences self.save_inference() def save_inference(self): df = self.df.copy() df.loc[:, self.config.dataset.target] = self.inferences df.to_csv( os.path.join(self.config.general.exp_dir, f"inferences_{self.ckpt}.csv"), index=False, )
0.706596
0.214691
""" TUPLAS """ # Una tupla es una colección de variables de cualquier tipo tupla = (1, "dos", True) #%% # Aunque lo normal es que todos los objetos dentro de la colección sean del # mismo tipo, como en este caso, que son variables de tipo texto tupla = ('uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez') #%% # Puedes acceder los elementos de la tupla por su índice # EL primer elemento de la tupla está en el índice 0 print(tupla[0]) #%% # Contando desde cero, accedemos a cualquier elemento print(tupla[3]) #%% # Podemos acceder a un rango de elementos print(tupla[0:3]) print(tupla[2:4]) print(tupla[3:]) #%% # SI no ponemos nada, cuenta como el elemento 0 print(tupla[:3]) #%% # Si es en el segudo índice, es el final print(tupla[6:]) #%% # Hay algún truquillo para llegar al final de la tupla print(tupla[-1]) #%% # Podemos saber cuanto mide esta tupla len(tupla) #%% # Y también podemos preguntar si hay o no un elemento dentro: print("diez" in tupla) print("once" in tupla) #%% """ LISTAS """ #%% # Las tuplas están bien, pero no permiten añadir ni borrar elementos. # ¡Se usan a veces! pero con mucha más frecuencia, usarás una lista. # Se distingue por que en vez de paréntesis, se usa un corchete cuadraro lista = ['uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez'] #%% Y funciona exactamente igual print(lista[0]) print(lista[3]) print(lista[0:3]) print(lista[2:4]) print(lista[3:]) print(lista[:3]) print(lista[6:]) print(lista[-1]) len(lista) print("diez" in lista) print("once" in lista) #%% con la diferencia de que puedes añadir elementos print(lista) lista.append("once") print(lista) #%% y eliminarlo! lista.remove("once") print("once" in lista) #%% Si tratas de eliminar un elemento que no existe, python lanzará un error lista.remove("once") #%% Puedes eliminar elementos por su índice: lista.pop(0) print("uno" in lista) #%% # Puedo obtener una lista de una variable de tipo texto palabras = "tenedor cuchillo cuchara peine" print(palabras) print(palabras.split()) #%% # Podemos encadenar métodos de string para hacer cosas # Como eliminar los espacios del principio y del final palabras = " tenedor cuchillo cuchara peine " print(palabras.split(" ")) print(palabras.strip().split(" ")) #%% # Podeis hacer split por casi cualquier caracter palabras_con_comas = "hola,tengo,varias,palabras" print(palabras_con_comas.split(",")) #%% # Incluso por salto de linea, con el método splitlines # lo que nos resultará muy util para leer algunos ficheros cadena = """Hola tengo varias lineas""" print(cadena.splitlines()) #%% Strip también funcionará con saltos de línea cadena = """ Hola tengo varias lineas """ print(cadena.splitlines()) #%% print(cadena.strip().splitlines()) #%% # Las propias cadenas de texto funcionan como si fueran listas: # por ejemplo, puedo acceder a sus índices cadena = "Hola mundo!" print(cadena[0]) print(cadena[-1]) print(cadena[2:6]) #%% # Podemos ordenar las listas: lista = ["z","g","a","d"] lista.sort() print(lista) #%% # También numéricamente lista = [9,4,1,0,100,23] lista.sort() print(lista) #%% #Y darle la vuelta lista.reverse() print(lista) #%% """ DICCIONARIOS """ #%% # Los diccionarios asocian una palabra a un valor: diccionario = { "uno": 1, "dos": 2, "tres": 3 } print(diccionario) #%% # En vez de acceder por el índice, accedemos por la palabra print(diccionario["uno"]) #%% # Si queremos saber las claves que contiene, debemos usar la palabra keys() print(diccionario.keys()) #%% Podemos convertir esto en una lista, para acceder a ellos como si fuerann # los elementos de una lista claves = list(diccionario.keys()) print(claves[0]) #%% # La palabra reservada "in" aquí funciona de manera algo distinta: # Responde a la pregunta ¿está la palabra en el diccionario? print("uno" in diccionario) print(1 in diccionario) #%% Si queremos saber si un valor está dentro del diccionario, al igual # que tenemos keys, tenemos values print(diccionario.values()) #%% # Igualmente puedes convertirlo en una lista valores = list(diccionario.values()) print(valores[0]) #%% # Y así es como puede comprobarse si un valor está dentro de un diccionario print(1 in diccionario.values()) #%% """ ANIDACIÓN DE ESTRUCTURAS """ #%% Algo que no solo es común, si no que vosotras mismas querréis hacer # es anidar estructuras de datos. # Por ejemplo: personas = [ {"nombre": "Juan", "apellido": "Espadas"}, {"nombre": "Fernando", "apellido": "Jimenez"} ] print(personas) #%% Para estos casos el comando print nos puede mostrar cosas muy confusas # Es mucho mejor pprint, que nos coloca saltos de línea from pprint import pprint pprint(personas) #%% # COmo veis, hemos creado una lista, y cada elemento de la lista es a su vez un # diccionario. ¿Como accedo a cada elemento? Pues como si pelase una cebolla # desde las capas superiores a las inferiores. Empiezo por la lista. # personas[0]`deberia darme el primer elemento print(personas[0]) #%% # Dentro de ese primer elemento, puedo acceder al diccionario print(personas[0]["nombre"]) #%% Podríamos querer acceder al segundo elemento: print(personas[1]["nombre"]) #%% # Tenemos total libertad de anidación de estos objetos. Por ejemplo, podríamos # completar nuestro ejemplo: personas = [{ "nombre":"Juan", "apellidos":"Espadas", "direccion":{ "fiscal": { "calle":"Calle del álamo 12", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28005" }, "postal" : { "calle":"Calle del cerezo 15", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28008" } }, "telefonos":[ "212 555-1234", "646 555-4567" ] }, { "nombre":"Fernando", "apellidos":"Jimenez", "direccion":{ "fiscal": { "calle":"Calle del cierzo 110", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28012" }, "postal" : { "calle":"Plaza del céfiro 1", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28001" } }, "telefonos":[ "567 555-8765", "666 555-5432" ] }] #%% # Fijaos en la diferencia entre pprint y print print(personas) #%% pprint(personas) #%% #Solo tenemos que ser conscientes de que cuanto más liemos las cosas, # más dificil seránn de leer, y que debemos de buscar estructuras lo más # intuitivas posibles: # Aqui está la dirección de la primera persona print(personas[0]["direccion"]["postal"]["calle"])
03_estructuras_de_datos.py
""" TUPLAS """ # Una tupla es una colección de variables de cualquier tipo tupla = (1, "dos", True) #%% # Aunque lo normal es que todos los objetos dentro de la colección sean del # mismo tipo, como en este caso, que son variables de tipo texto tupla = ('uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez') #%% # Puedes acceder los elementos de la tupla por su índice # EL primer elemento de la tupla está en el índice 0 print(tupla[0]) #%% # Contando desde cero, accedemos a cualquier elemento print(tupla[3]) #%% # Podemos acceder a un rango de elementos print(tupla[0:3]) print(tupla[2:4]) print(tupla[3:]) #%% # SI no ponemos nada, cuenta como el elemento 0 print(tupla[:3]) #%% # Si es en el segudo índice, es el final print(tupla[6:]) #%% # Hay algún truquillo para llegar al final de la tupla print(tupla[-1]) #%% # Podemos saber cuanto mide esta tupla len(tupla) #%% # Y también podemos preguntar si hay o no un elemento dentro: print("diez" in tupla) print("once" in tupla) #%% """ LISTAS """ #%% # Las tuplas están bien, pero no permiten añadir ni borrar elementos. # ¡Se usan a veces! pero con mucha más frecuencia, usarás una lista. # Se distingue por que en vez de paréntesis, se usa un corchete cuadraro lista = ['uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez'] #%% Y funciona exactamente igual print(lista[0]) print(lista[3]) print(lista[0:3]) print(lista[2:4]) print(lista[3:]) print(lista[:3]) print(lista[6:]) print(lista[-1]) len(lista) print("diez" in lista) print("once" in lista) #%% con la diferencia de que puedes añadir elementos print(lista) lista.append("once") print(lista) #%% y eliminarlo! lista.remove("once") print("once" in lista) #%% Si tratas de eliminar un elemento que no existe, python lanzará un error lista.remove("once") #%% Puedes eliminar elementos por su índice: lista.pop(0) print("uno" in lista) #%% # Puedo obtener una lista de una variable de tipo texto palabras = "tenedor cuchillo cuchara peine" print(palabras) print(palabras.split()) #%% # Podemos encadenar métodos de string para hacer cosas # Como eliminar los espacios del principio y del final palabras = " tenedor cuchillo cuchara peine " print(palabras.split(" ")) print(palabras.strip().split(" ")) #%% # Podeis hacer split por casi cualquier caracter palabras_con_comas = "hola,tengo,varias,palabras" print(palabras_con_comas.split(",")) #%% # Incluso por salto de linea, con el método splitlines # lo que nos resultará muy util para leer algunos ficheros cadena = """Hola tengo varias lineas""" print(cadena.splitlines()) #%% Strip también funcionará con saltos de línea cadena = """ Hola tengo varias lineas """ print(cadena.splitlines()) #%% print(cadena.strip().splitlines()) #%% # Las propias cadenas de texto funcionan como si fueran listas: # por ejemplo, puedo acceder a sus índices cadena = "Hola mundo!" print(cadena[0]) print(cadena[-1]) print(cadena[2:6]) #%% # Podemos ordenar las listas: lista = ["z","g","a","d"] lista.sort() print(lista) #%% # También numéricamente lista = [9,4,1,0,100,23] lista.sort() print(lista) #%% #Y darle la vuelta lista.reverse() print(lista) #%% """ DICCIONARIOS """ #%% # Los diccionarios asocian una palabra a un valor: diccionario = { "uno": 1, "dos": 2, "tres": 3 } print(diccionario) #%% # En vez de acceder por el índice, accedemos por la palabra print(diccionario["uno"]) #%% # Si queremos saber las claves que contiene, debemos usar la palabra keys() print(diccionario.keys()) #%% Podemos convertir esto en una lista, para acceder a ellos como si fuerann # los elementos de una lista claves = list(diccionario.keys()) print(claves[0]) #%% # La palabra reservada "in" aquí funciona de manera algo distinta: # Responde a la pregunta ¿está la palabra en el diccionario? print("uno" in diccionario) print(1 in diccionario) #%% Si queremos saber si un valor está dentro del diccionario, al igual # que tenemos keys, tenemos values print(diccionario.values()) #%% # Igualmente puedes convertirlo en una lista valores = list(diccionario.values()) print(valores[0]) #%% # Y así es como puede comprobarse si un valor está dentro de un diccionario print(1 in diccionario.values()) #%% """ ANIDACIÓN DE ESTRUCTURAS """ #%% Algo que no solo es común, si no que vosotras mismas querréis hacer # es anidar estructuras de datos. # Por ejemplo: personas = [ {"nombre": "Juan", "apellido": "Espadas"}, {"nombre": "Fernando", "apellido": "Jimenez"} ] print(personas) #%% Para estos casos el comando print nos puede mostrar cosas muy confusas # Es mucho mejor pprint, que nos coloca saltos de línea from pprint import pprint pprint(personas) #%% # COmo veis, hemos creado una lista, y cada elemento de la lista es a su vez un # diccionario. ¿Como accedo a cada elemento? Pues como si pelase una cebolla # desde las capas superiores a las inferiores. Empiezo por la lista. # personas[0]`deberia darme el primer elemento print(personas[0]) #%% # Dentro de ese primer elemento, puedo acceder al diccionario print(personas[0]["nombre"]) #%% Podríamos querer acceder al segundo elemento: print(personas[1]["nombre"]) #%% # Tenemos total libertad de anidación de estos objetos. Por ejemplo, podríamos # completar nuestro ejemplo: personas = [{ "nombre":"Juan", "apellidos":"Espadas", "direccion":{ "fiscal": { "calle":"Calle del álamo 12", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28005" }, "postal" : { "calle":"Calle del cerezo 15", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28008" } }, "telefonos":[ "212 555-1234", "646 555-4567" ] }, { "nombre":"Fernando", "apellidos":"Jimenez", "direccion":{ "fiscal": { "calle":"Calle del cierzo 110", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28012" }, "postal" : { "calle":"Plaza del céfiro 1", "localidad":"Madrid", "provincina":"Madrid", "codigoPostal":"28001" } }, "telefonos":[ "567 555-8765", "666 555-5432" ] }] #%% # Fijaos en la diferencia entre pprint y print print(personas) #%% pprint(personas) #%% #Solo tenemos que ser conscientes de que cuanto más liemos las cosas, # más dificil seránn de leer, y que debemos de buscar estructuras lo más # intuitivas posibles: # Aqui está la dirección de la primera persona print(personas[0]["direccion"]["postal"]["calle"])
0.196094
0.356587
from getratings.models.ratings import Ratings class NA_Ziggs_Jng_Aatrox(Ratings): pass class NA_Ziggs_Jng_Ahri(Ratings): pass class NA_Ziggs_Jng_Akali(Ratings): pass class NA_Ziggs_Jng_Alistar(Ratings): pass class NA_Ziggs_Jng_Amumu(Ratings): pass class NA_Ziggs_Jng_Anivia(Ratings): pass class NA_Ziggs_Jng_Annie(Ratings): pass class NA_Ziggs_Jng_Ashe(Ratings): pass class NA_Ziggs_Jng_AurelionSol(Ratings): pass class NA_Ziggs_Jng_Azir(Ratings): pass class NA_Ziggs_Jng_Bard(Ratings): pass class NA_Ziggs_Jng_Blitzcrank(Ratings): pass class NA_Ziggs_Jng_Brand(Ratings): pass class NA_Ziggs_Jng_Braum(Ratings): pass class NA_Ziggs_Jng_Caitlyn(Ratings): pass class NA_Ziggs_Jng_Camille(Ratings): pass class NA_Ziggs_Jng_Cassiopeia(Ratings): pass class NA_Ziggs_Jng_Chogath(Ratings): pass class NA_Ziggs_Jng_Corki(Ratings): pass class NA_Ziggs_Jng_Darius(Ratings): pass class NA_Ziggs_Jng_Diana(Ratings): pass class NA_Ziggs_Jng_Draven(Ratings): pass class NA_Ziggs_Jng_DrMundo(Ratings): pass class NA_Ziggs_Jng_Ekko(Ratings): pass class NA_Ziggs_Jng_Elise(Ratings): pass class NA_Ziggs_Jng_Evelynn(Ratings): pass class NA_Ziggs_Jng_Ezreal(Ratings): pass class NA_Ziggs_Jng_Fiddlesticks(Ratings): pass class NA_Ziggs_Jng_Fiora(Ratings): pass class NA_Ziggs_Jng_Fizz(Ratings): pass class NA_Ziggs_Jng_Galio(Ratings): pass class NA_Ziggs_Jng_Gangplank(Ratings): pass class NA_Ziggs_Jng_Garen(Ratings): pass class NA_Ziggs_Jng_Gnar(Ratings): pass class NA_Ziggs_Jng_Gragas(Ratings): pass class NA_Ziggs_Jng_Graves(Ratings): pass class NA_Ziggs_Jng_Hecarim(Ratings): pass class NA_Ziggs_Jng_Heimerdinger(Ratings): pass class NA_Ziggs_Jng_Illaoi(Ratings): pass class NA_Ziggs_Jng_Irelia(Ratings): pass class NA_Ziggs_Jng_Ivern(Ratings): pass class NA_Ziggs_Jng_Janna(Ratings): pass class NA_Ziggs_Jng_JarvanIV(Ratings): pass class NA_Ziggs_Jng_Jax(Ratings): pass class NA_Ziggs_Jng_Jayce(Ratings): pass class NA_Ziggs_Jng_Jhin(Ratings): pass class NA_Ziggs_Jng_Jinx(Ratings): pass class NA_Ziggs_Jng_Kalista(Ratings): pass class NA_Ziggs_Jng_Karma(Ratings): pass class NA_Ziggs_Jng_Karthus(Ratings): pass class NA_Ziggs_Jng_Kassadin(Ratings): pass class NA_Ziggs_Jng_Katarina(Ratings): pass class NA_Ziggs_Jng_Kayle(Ratings): pass class NA_Ziggs_Jng_Kayn(Ratings): pass class NA_Ziggs_Jng_Kennen(Ratings): pass class NA_Ziggs_Jng_Khazix(Ratings): pass class NA_Ziggs_Jng_Kindred(Ratings): pass class NA_Ziggs_Jng_Kled(Ratings): pass class NA_Ziggs_Jng_KogMaw(Ratings): pass class NA_Ziggs_Jng_Leblanc(Ratings): pass class NA_Ziggs_Jng_LeeSin(Ratings): pass class NA_Ziggs_Jng_Leona(Ratings): pass class NA_Ziggs_Jng_Lissandra(Ratings): pass class NA_Ziggs_Jng_Lucian(Ratings): pass class NA_Ziggs_Jng_Lulu(Ratings): pass class NA_Ziggs_Jng_Lux(Ratings): pass class NA_Ziggs_Jng_Malphite(Ratings): pass class NA_Ziggs_Jng_Malzahar(Ratings): pass class NA_Ziggs_Jng_Maokai(Ratings): pass class NA_Ziggs_Jng_MasterYi(Ratings): pass class NA_Ziggs_Jng_MissFortune(Ratings): pass class NA_Ziggs_Jng_MonkeyKing(Ratings): pass class NA_Ziggs_Jng_Mordekaiser(Ratings): pass class NA_Ziggs_Jng_Morgana(Ratings): pass class NA_Ziggs_Jng_Nami(Ratings): pass class NA_Ziggs_Jng_Nasus(Ratings): pass class NA_Ziggs_Jng_Nautilus(Ratings): pass class NA_Ziggs_Jng_Nidalee(Ratings): pass class NA_Ziggs_Jng_Nocturne(Ratings): pass class NA_Ziggs_Jng_Nunu(Ratings): pass class NA_Ziggs_Jng_Olaf(Ratings): pass class NA_Ziggs_Jng_Orianna(Ratings): pass class NA_Ziggs_Jng_Ornn(Ratings): pass class NA_Ziggs_Jng_Pantheon(Ratings): pass class NA_Ziggs_Jng_Poppy(Ratings): pass class NA_Ziggs_Jng_Quinn(Ratings): pass class NA_Ziggs_Jng_Rakan(Ratings): pass class NA_Ziggs_Jng_Rammus(Ratings): pass class NA_Ziggs_Jng_RekSai(Ratings): pass class NA_Ziggs_Jng_Renekton(Ratings): pass class NA_Ziggs_Jng_Rengar(Ratings): pass class NA_Ziggs_Jng_Riven(Ratings): pass class NA_Ziggs_Jng_Rumble(Ratings): pass class NA_Ziggs_Jng_Ryze(Ratings): pass class NA_Ziggs_Jng_Sejuani(Ratings): pass class NA_Ziggs_Jng_Shaco(Ratings): pass class NA_Ziggs_Jng_Shen(Ratings): pass class NA_Ziggs_Jng_Shyvana(Ratings): pass class NA_Ziggs_Jng_Singed(Ratings): pass class NA_Ziggs_Jng_Sion(Ratings): pass class NA_Ziggs_Jng_Sivir(Ratings): pass class NA_Ziggs_Jng_Skarner(Ratings): pass class NA_Ziggs_Jng_Sona(Ratings): pass class NA_Ziggs_Jng_Soraka(Ratings): pass class NA_Ziggs_Jng_Swain(Ratings): pass class NA_Ziggs_Jng_Syndra(Ratings): pass class NA_Ziggs_Jng_TahmKench(Ratings): pass class NA_Ziggs_Jng_Taliyah(Ratings): pass class NA_Ziggs_Jng_Talon(Ratings): pass class NA_Ziggs_Jng_Taric(Ratings): pass class NA_Ziggs_Jng_Teemo(Ratings): pass class NA_Ziggs_Jng_Thresh(Ratings): pass class NA_Ziggs_Jng_Tristana(Ratings): pass class NA_Ziggs_Jng_Trundle(Ratings): pass class NA_Ziggs_Jng_Tryndamere(Ratings): pass class NA_Ziggs_Jng_TwistedFate(Ratings): pass class NA_Ziggs_Jng_Twitch(Ratings): pass class NA_Ziggs_Jng_Udyr(Ratings): pass class NA_Ziggs_Jng_Urgot(Ratings): pass class NA_Ziggs_Jng_Varus(Ratings): pass class NA_Ziggs_Jng_Vayne(Ratings): pass class NA_Ziggs_Jng_Veigar(Ratings): pass class NA_Ziggs_Jng_Velkoz(Ratings): pass class NA_Ziggs_Jng_Vi(Ratings): pass class NA_Ziggs_Jng_Viktor(Ratings): pass class NA_Ziggs_Jng_Vladimir(Ratings): pass class NA_Ziggs_Jng_Volibear(Ratings): pass class NA_Ziggs_Jng_Warwick(Ratings): pass class NA_Ziggs_Jng_Xayah(Ratings): pass class NA_Ziggs_Jng_Xerath(Ratings): pass class NA_Ziggs_Jng_XinZhao(Ratings): pass class NA_Ziggs_Jng_Yasuo(Ratings): pass class NA_Ziggs_Jng_Yorick(Ratings): pass class NA_Ziggs_Jng_Zac(Ratings): pass class NA_Ziggs_Jng_Zed(Ratings): pass class NA_Ziggs_Jng_Ziggs(Ratings): pass class NA_Ziggs_Jng_Zilean(Ratings): pass class NA_Ziggs_Jng_Zyra(Ratings): pass
loldib/getratings/models/NA/na_ziggs/na_ziggs_jng.py
from getratings.models.ratings import Ratings class NA_Ziggs_Jng_Aatrox(Ratings): pass class NA_Ziggs_Jng_Ahri(Ratings): pass class NA_Ziggs_Jng_Akali(Ratings): pass class NA_Ziggs_Jng_Alistar(Ratings): pass class NA_Ziggs_Jng_Amumu(Ratings): pass class NA_Ziggs_Jng_Anivia(Ratings): pass class NA_Ziggs_Jng_Annie(Ratings): pass class NA_Ziggs_Jng_Ashe(Ratings): pass class NA_Ziggs_Jng_AurelionSol(Ratings): pass class NA_Ziggs_Jng_Azir(Ratings): pass class NA_Ziggs_Jng_Bard(Ratings): pass class NA_Ziggs_Jng_Blitzcrank(Ratings): pass class NA_Ziggs_Jng_Brand(Ratings): pass class NA_Ziggs_Jng_Braum(Ratings): pass class NA_Ziggs_Jng_Caitlyn(Ratings): pass class NA_Ziggs_Jng_Camille(Ratings): pass class NA_Ziggs_Jng_Cassiopeia(Ratings): pass class NA_Ziggs_Jng_Chogath(Ratings): pass class NA_Ziggs_Jng_Corki(Ratings): pass class NA_Ziggs_Jng_Darius(Ratings): pass class NA_Ziggs_Jng_Diana(Ratings): pass class NA_Ziggs_Jng_Draven(Ratings): pass class NA_Ziggs_Jng_DrMundo(Ratings): pass class NA_Ziggs_Jng_Ekko(Ratings): pass class NA_Ziggs_Jng_Elise(Ratings): pass class NA_Ziggs_Jng_Evelynn(Ratings): pass class NA_Ziggs_Jng_Ezreal(Ratings): pass class NA_Ziggs_Jng_Fiddlesticks(Ratings): pass class NA_Ziggs_Jng_Fiora(Ratings): pass class NA_Ziggs_Jng_Fizz(Ratings): pass class NA_Ziggs_Jng_Galio(Ratings): pass class NA_Ziggs_Jng_Gangplank(Ratings): pass class NA_Ziggs_Jng_Garen(Ratings): pass class NA_Ziggs_Jng_Gnar(Ratings): pass class NA_Ziggs_Jng_Gragas(Ratings): pass class NA_Ziggs_Jng_Graves(Ratings): pass class NA_Ziggs_Jng_Hecarim(Ratings): pass class NA_Ziggs_Jng_Heimerdinger(Ratings): pass class NA_Ziggs_Jng_Illaoi(Ratings): pass class NA_Ziggs_Jng_Irelia(Ratings): pass class NA_Ziggs_Jng_Ivern(Ratings): pass class NA_Ziggs_Jng_Janna(Ratings): pass class NA_Ziggs_Jng_JarvanIV(Ratings): pass class NA_Ziggs_Jng_Jax(Ratings): pass class NA_Ziggs_Jng_Jayce(Ratings): pass class NA_Ziggs_Jng_Jhin(Ratings): pass class NA_Ziggs_Jng_Jinx(Ratings): pass class NA_Ziggs_Jng_Kalista(Ratings): pass class NA_Ziggs_Jng_Karma(Ratings): pass class NA_Ziggs_Jng_Karthus(Ratings): pass class NA_Ziggs_Jng_Kassadin(Ratings): pass class NA_Ziggs_Jng_Katarina(Ratings): pass class NA_Ziggs_Jng_Kayle(Ratings): pass class NA_Ziggs_Jng_Kayn(Ratings): pass class NA_Ziggs_Jng_Kennen(Ratings): pass class NA_Ziggs_Jng_Khazix(Ratings): pass class NA_Ziggs_Jng_Kindred(Ratings): pass class NA_Ziggs_Jng_Kled(Ratings): pass class NA_Ziggs_Jng_KogMaw(Ratings): pass class NA_Ziggs_Jng_Leblanc(Ratings): pass class NA_Ziggs_Jng_LeeSin(Ratings): pass class NA_Ziggs_Jng_Leona(Ratings): pass class NA_Ziggs_Jng_Lissandra(Ratings): pass class NA_Ziggs_Jng_Lucian(Ratings): pass class NA_Ziggs_Jng_Lulu(Ratings): pass class NA_Ziggs_Jng_Lux(Ratings): pass class NA_Ziggs_Jng_Malphite(Ratings): pass class NA_Ziggs_Jng_Malzahar(Ratings): pass class NA_Ziggs_Jng_Maokai(Ratings): pass class NA_Ziggs_Jng_MasterYi(Ratings): pass class NA_Ziggs_Jng_MissFortune(Ratings): pass class NA_Ziggs_Jng_MonkeyKing(Ratings): pass class NA_Ziggs_Jng_Mordekaiser(Ratings): pass class NA_Ziggs_Jng_Morgana(Ratings): pass class NA_Ziggs_Jng_Nami(Ratings): pass class NA_Ziggs_Jng_Nasus(Ratings): pass class NA_Ziggs_Jng_Nautilus(Ratings): pass class NA_Ziggs_Jng_Nidalee(Ratings): pass class NA_Ziggs_Jng_Nocturne(Ratings): pass class NA_Ziggs_Jng_Nunu(Ratings): pass class NA_Ziggs_Jng_Olaf(Ratings): pass class NA_Ziggs_Jng_Orianna(Ratings): pass class NA_Ziggs_Jng_Ornn(Ratings): pass class NA_Ziggs_Jng_Pantheon(Ratings): pass class NA_Ziggs_Jng_Poppy(Ratings): pass class NA_Ziggs_Jng_Quinn(Ratings): pass class NA_Ziggs_Jng_Rakan(Ratings): pass class NA_Ziggs_Jng_Rammus(Ratings): pass class NA_Ziggs_Jng_RekSai(Ratings): pass class NA_Ziggs_Jng_Renekton(Ratings): pass class NA_Ziggs_Jng_Rengar(Ratings): pass class NA_Ziggs_Jng_Riven(Ratings): pass class NA_Ziggs_Jng_Rumble(Ratings): pass class NA_Ziggs_Jng_Ryze(Ratings): pass class NA_Ziggs_Jng_Sejuani(Ratings): pass class NA_Ziggs_Jng_Shaco(Ratings): pass class NA_Ziggs_Jng_Shen(Ratings): pass class NA_Ziggs_Jng_Shyvana(Ratings): pass class NA_Ziggs_Jng_Singed(Ratings): pass class NA_Ziggs_Jng_Sion(Ratings): pass class NA_Ziggs_Jng_Sivir(Ratings): pass class NA_Ziggs_Jng_Skarner(Ratings): pass class NA_Ziggs_Jng_Sona(Ratings): pass class NA_Ziggs_Jng_Soraka(Ratings): pass class NA_Ziggs_Jng_Swain(Ratings): pass class NA_Ziggs_Jng_Syndra(Ratings): pass class NA_Ziggs_Jng_TahmKench(Ratings): pass class NA_Ziggs_Jng_Taliyah(Ratings): pass class NA_Ziggs_Jng_Talon(Ratings): pass class NA_Ziggs_Jng_Taric(Ratings): pass class NA_Ziggs_Jng_Teemo(Ratings): pass class NA_Ziggs_Jng_Thresh(Ratings): pass class NA_Ziggs_Jng_Tristana(Ratings): pass class NA_Ziggs_Jng_Trundle(Ratings): pass class NA_Ziggs_Jng_Tryndamere(Ratings): pass class NA_Ziggs_Jng_TwistedFate(Ratings): pass class NA_Ziggs_Jng_Twitch(Ratings): pass class NA_Ziggs_Jng_Udyr(Ratings): pass class NA_Ziggs_Jng_Urgot(Ratings): pass class NA_Ziggs_Jng_Varus(Ratings): pass class NA_Ziggs_Jng_Vayne(Ratings): pass class NA_Ziggs_Jng_Veigar(Ratings): pass class NA_Ziggs_Jng_Velkoz(Ratings): pass class NA_Ziggs_Jng_Vi(Ratings): pass class NA_Ziggs_Jng_Viktor(Ratings): pass class NA_Ziggs_Jng_Vladimir(Ratings): pass class NA_Ziggs_Jng_Volibear(Ratings): pass class NA_Ziggs_Jng_Warwick(Ratings): pass class NA_Ziggs_Jng_Xayah(Ratings): pass class NA_Ziggs_Jng_Xerath(Ratings): pass class NA_Ziggs_Jng_XinZhao(Ratings): pass class NA_Ziggs_Jng_Yasuo(Ratings): pass class NA_Ziggs_Jng_Yorick(Ratings): pass class NA_Ziggs_Jng_Zac(Ratings): pass class NA_Ziggs_Jng_Zed(Ratings): pass class NA_Ziggs_Jng_Ziggs(Ratings): pass class NA_Ziggs_Jng_Zilean(Ratings): pass class NA_Ziggs_Jng_Zyra(Ratings): pass
0.204938
0.097907
from torch.utils.data import Subset from PIL import Image from torchvision.datasets import CIFAR100 from base.torchvision_dataset import TorchvisionDataset import numpy as np import torch import torchvision.transforms as transforms import random class CIFAR100_Dataset(TorchvisionDataset): def __init__(self, root: str, normal_class: int = 0, data_augmentation: bool = False, normalize: bool = False, outlier_exposure: bool = False, oe_n_classes: int = 100, seed: int = 0): super().__init__(root) self.image_size = (3, 32, 32) self.n_classes = 2 # 0: normal, 1: outlier self.shuffle = True random.seed(seed) # set seed if outlier_exposure: self.normal_classes = None self.outlier_classes = list(range(0, 100)) self.known_outlier_classes = tuple(random.sample(self.outlier_classes, oe_n_classes)) else: # Define normal and outlier classes self.normal_classes = tuple([normal_class]) self.outlier_classes = list(range(0, 100)) self.outlier_classes.remove(normal_class) self.outlier_classes = tuple(self.outlier_classes) # CIFAR-100 preprocessing: feature scaling to [0, 1], data normalization, and data augmentation train_transform = [] test_transform = [] if data_augmentation: # only augment training data train_transform += [transforms.ColorJitter(brightness=0.01, contrast=0.01, saturation=0.01, hue=0.01), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomCrop(32, padding=4)] train_transform += [transforms.ToTensor()] test_transform += [transforms.ToTensor()] if data_augmentation: train_transform += [transforms.Lambda(lambda x: x + 0.001 * torch.randn_like(x))] if normalize: train_transform += [transforms.Normalize((0.491373, 0.482353, 0.446667), (0.247059, 0.243529, 0.261569))] test_transform += [transforms.Normalize((0.491373, 0.482353, 0.446667), (0.247059, 0.243529, 0.261569))] train_transform = transforms.Compose(train_transform) test_transform = transforms.Compose(test_transform) target_transform = transforms.Lambda(lambda x: int(x in self.outlier_classes)) # Get train set train_set = MyCIFAR100(root=self.root, train=True, transform=train_transform, target_transform=target_transform, download=True) if outlier_exposure: idx = np.argwhere(np.isin(np.array(train_set.targets), self.known_outlier_classes)) idx = idx.flatten().tolist() train_set.semi_targets[idx] = -1 * torch.ones(len(idx)).long() # set outlier exposure labels # Subset train_set to selected classes self.train_set = Subset(train_set, idx) self.train_set.shuffle_idxs = False self.test_set = None else: # Subset train_set to normal_classes idx = np.argwhere(np.isin(np.array(train_set.targets), self.normal_classes)) idx = idx.flatten().tolist() train_set.semi_targets[idx] = torch.zeros(len(idx)).long() self.train_set = Subset(train_set, idx) # Get test set self.test_set = MyCIFAR100(root=self.root, train=False, transform=test_transform, target_transform=target_transform, download=True) class MyCIFAR100(CIFAR100): """ Torchvision CIFAR100 class with additional targets for the outlier exposure setting and patch of __getitem__ method to also return the outlier exposure target as well as the index of a data sample. """ def __init__(self, *args, **kwargs): super(MyCIFAR100, self).__init__(*args, **kwargs) self.semi_targets = torch.zeros(len(self.targets), dtype=torch.int64) self.shuffle_idxs = False def __getitem__(self, index): """Override the original method of the CIFAR100 class. Args: index (int): Index Returns: tuple: (image, target, semi_target, index) """ img, target, semi_target = self.data[index], self.targets[index], int(self.semi_targets[index]) # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, semi_target, index
src/datasets/cifar100.py
from torch.utils.data import Subset from PIL import Image from torchvision.datasets import CIFAR100 from base.torchvision_dataset import TorchvisionDataset import numpy as np import torch import torchvision.transforms as transforms import random class CIFAR100_Dataset(TorchvisionDataset): def __init__(self, root: str, normal_class: int = 0, data_augmentation: bool = False, normalize: bool = False, outlier_exposure: bool = False, oe_n_classes: int = 100, seed: int = 0): super().__init__(root) self.image_size = (3, 32, 32) self.n_classes = 2 # 0: normal, 1: outlier self.shuffle = True random.seed(seed) # set seed if outlier_exposure: self.normal_classes = None self.outlier_classes = list(range(0, 100)) self.known_outlier_classes = tuple(random.sample(self.outlier_classes, oe_n_classes)) else: # Define normal and outlier classes self.normal_classes = tuple([normal_class]) self.outlier_classes = list(range(0, 100)) self.outlier_classes.remove(normal_class) self.outlier_classes = tuple(self.outlier_classes) # CIFAR-100 preprocessing: feature scaling to [0, 1], data normalization, and data augmentation train_transform = [] test_transform = [] if data_augmentation: # only augment training data train_transform += [transforms.ColorJitter(brightness=0.01, contrast=0.01, saturation=0.01, hue=0.01), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomCrop(32, padding=4)] train_transform += [transforms.ToTensor()] test_transform += [transforms.ToTensor()] if data_augmentation: train_transform += [transforms.Lambda(lambda x: x + 0.001 * torch.randn_like(x))] if normalize: train_transform += [transforms.Normalize((0.491373, 0.482353, 0.446667), (0.247059, 0.243529, 0.261569))] test_transform += [transforms.Normalize((0.491373, 0.482353, 0.446667), (0.247059, 0.243529, 0.261569))] train_transform = transforms.Compose(train_transform) test_transform = transforms.Compose(test_transform) target_transform = transforms.Lambda(lambda x: int(x in self.outlier_classes)) # Get train set train_set = MyCIFAR100(root=self.root, train=True, transform=train_transform, target_transform=target_transform, download=True) if outlier_exposure: idx = np.argwhere(np.isin(np.array(train_set.targets), self.known_outlier_classes)) idx = idx.flatten().tolist() train_set.semi_targets[idx] = -1 * torch.ones(len(idx)).long() # set outlier exposure labels # Subset train_set to selected classes self.train_set = Subset(train_set, idx) self.train_set.shuffle_idxs = False self.test_set = None else: # Subset train_set to normal_classes idx = np.argwhere(np.isin(np.array(train_set.targets), self.normal_classes)) idx = idx.flatten().tolist() train_set.semi_targets[idx] = torch.zeros(len(idx)).long() self.train_set = Subset(train_set, idx) # Get test set self.test_set = MyCIFAR100(root=self.root, train=False, transform=test_transform, target_transform=target_transform, download=True) class MyCIFAR100(CIFAR100): """ Torchvision CIFAR100 class with additional targets for the outlier exposure setting and patch of __getitem__ method to also return the outlier exposure target as well as the index of a data sample. """ def __init__(self, *args, **kwargs): super(MyCIFAR100, self).__init__(*args, **kwargs) self.semi_targets = torch.zeros(len(self.targets), dtype=torch.int64) self.shuffle_idxs = False def __getitem__(self, index): """Override the original method of the CIFAR100 class. Args: index (int): Index Returns: tuple: (image, target, semi_target, index) """ img, target, semi_target = self.data[index], self.targets[index], int(self.semi_targets[index]) # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target, semi_target, index
0.90692
0.594434
"""Server-side sessions.""" from datetime import datetime, timedelta from flask import request from flask.sessions import SessionInterface, SessionMixin from .model import get_session_data, store_session_data, delete_session from .util import random_string class RedisSession(dict, SessionMixin): """The session object.""" def __init__(self, initial=None, sid=None, new=None): if initial is None: initial = {} dict.__init__(self, initial) self.sid = sid self.old_sid = None self.new = new self.modified_keys = set() def init_data(self): """Create a random session key and CSRF token.""" self.sid = random_string(64) self['csrf'] = random_string(64) def rotate(self): """Reset the session key and CSRF token.""" if not self.new: self.old_sid = self.sid self.init_data() def __setitem__(self, key, value): """Change the value, and record the change.""" self.modified = True self.modified_keys.add(key) return super(RedisSession, self).__setitem__(key, value) @property def authed(self): """Return whether the user is authenticated.""" return 'user' in self @property def permanent(self): """Return whether the session should be stored long-term.""" return self.authed class RedisSessionInterface(SessionInterface): session_class = RedisSession def open_session(self, app, request): """Attempt to load the session from a cookie, or create one.""" sid = request.cookies.get(app.session_cookie_name) if sid: try: data = get_session_data(sid) return self.session_class(initial=data, sid=sid) except LookupError: pass session = self.session_class(new=True) session.init_data() return session def get_session_lifetime(self, app, session): if session.permanent: return app.permanent_session_lifetime return timedelta(days=1) def get_expiration_time(self, app, session): return datetime.utcnow() + self.get_session_lifetime(app, session) def save_session(self, app, session, response): """Write the session to redis, and set the cookie.""" domain = self.get_cookie_domain(app) if not session: delete_session(session.sid) if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain) return redis_exp = self.get_session_lifetime(app, session) cookie_exp = self.get_expiration_time(app, session) changed_data = dict((k, session.get(k)) for k in session.modified_keys) store_session_data(session.sid, changed_data, redis_exp, session.old_sid) response.set_cookie(app.session_cookie_name, session.sid, expires=cookie_exp, httponly=True, domain=domain, secure=(request.scheme == 'https'))
frost/session.py
"""Server-side sessions.""" from datetime import datetime, timedelta from flask import request from flask.sessions import SessionInterface, SessionMixin from .model import get_session_data, store_session_data, delete_session from .util import random_string class RedisSession(dict, SessionMixin): """The session object.""" def __init__(self, initial=None, sid=None, new=None): if initial is None: initial = {} dict.__init__(self, initial) self.sid = sid self.old_sid = None self.new = new self.modified_keys = set() def init_data(self): """Create a random session key and CSRF token.""" self.sid = random_string(64) self['csrf'] = random_string(64) def rotate(self): """Reset the session key and CSRF token.""" if not self.new: self.old_sid = self.sid self.init_data() def __setitem__(self, key, value): """Change the value, and record the change.""" self.modified = True self.modified_keys.add(key) return super(RedisSession, self).__setitem__(key, value) @property def authed(self): """Return whether the user is authenticated.""" return 'user' in self @property def permanent(self): """Return whether the session should be stored long-term.""" return self.authed class RedisSessionInterface(SessionInterface): session_class = RedisSession def open_session(self, app, request): """Attempt to load the session from a cookie, or create one.""" sid = request.cookies.get(app.session_cookie_name) if sid: try: data = get_session_data(sid) return self.session_class(initial=data, sid=sid) except LookupError: pass session = self.session_class(new=True) session.init_data() return session def get_session_lifetime(self, app, session): if session.permanent: return app.permanent_session_lifetime return timedelta(days=1) def get_expiration_time(self, app, session): return datetime.utcnow() + self.get_session_lifetime(app, session) def save_session(self, app, session, response): """Write the session to redis, and set the cookie.""" domain = self.get_cookie_domain(app) if not session: delete_session(session.sid) if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain) return redis_exp = self.get_session_lifetime(app, session) cookie_exp = self.get_expiration_time(app, session) changed_data = dict((k, session.get(k)) for k in session.modified_keys) store_session_data(session.sid, changed_data, redis_exp, session.old_sid) response.set_cookie(app.session_cookie_name, session.sid, expires=cookie_exp, httponly=True, domain=domain, secure=(request.scheme == 'https'))
0.839142
0.168754
import os from unittest import mock from unittest.mock import MagicMock import pytest from pytorch_lightning import Trainer from pytorch_lightning.loggers import _MLFLOW_AVAILABLE, MLFlowLogger from tests.helpers import BoringModel def mock_mlflow_run_creation(logger, experiment_name=None, experiment_id=None, run_id=None): """ Helper function to simulate mlflow client creating a new (or existing) experiment. """ run = MagicMock() run.info.run_id = run_id logger._mlflow_client.get_experiment_by_name = MagicMock(return_value=experiment_name) logger._mlflow_client.create_experiment = MagicMock(return_value=experiment_id) logger._mlflow_client.create_run = MagicMock(return_value=run) return logger @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_logger_exists(client, mlflow, tmpdir): """ Test launching three independent loggers with either same or different experiment name. """ run1 = MagicMock() run1.info.run_id = "run-id-1" run2 = MagicMock() run2.info.run_id = "run-id-2" run3 = MagicMock() run3.info.run_id = "run-id-3" # simulate non-existing experiment creation client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id-1") # experiment_id client.return_value.create_run = MagicMock(return_value=run1) logger = MLFlowLogger('test', save_dir=tmpdir) assert logger._experiment_id is None assert logger._run_id is None _ = logger.experiment assert logger.experiment_id == "exp-id-1" assert logger.run_id == "run-id-1" assert logger.experiment.create_experiment.asset_called_once() client.reset_mock(return_value=True) # simulate existing experiment returns experiment id exp1 = MagicMock() exp1.experiment_id = "exp-id-1" client.return_value.get_experiment_by_name = MagicMock(return_value=exp1) client.return_value.create_run = MagicMock(return_value=run2) # same name leads to same experiment id, but different runs get recorded logger2 = MLFlowLogger('test', save_dir=tmpdir) assert logger2.experiment_id == logger.experiment_id assert logger2.run_id == "run-id-2" assert logger2.experiment.create_experiment.call_count == 0 assert logger2.experiment.create_run.asset_called_once() client.reset_mock(return_value=True) # simulate a 3rd experiment with new name client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id-3") client.return_value.create_run = MagicMock(return_value=run3) # logger with new experiment name causes new experiment id and new run id to be created logger3 = MLFlowLogger('new', save_dir=tmpdir) assert logger3.experiment_id == "exp-id-3" != logger.experiment_id assert logger3.run_id == "run-id-3" @mock.patch("pytorch_lightning.loggers.mlflow.mlflow") @mock.patch("pytorch_lightning.loggers.mlflow.MlflowClient") def test_mlflow_log_dir(client, mlflow, tmpdir): """ Test that the trainer saves checkpoints in the logger's save dir. """ # simulate experiment creation with mlflow client mock run = MagicMock() run.info.run_id = "run-id" client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id") client.return_value.create_run = MagicMock(return_value=run) # test construction of default log dir path logger = MLFlowLogger("test", save_dir=tmpdir) assert logger.save_dir == tmpdir assert logger.version == "run-id" assert logger.name == "exp-id" model = BoringModel() trainer = Trainer( default_root_dir=tmpdir, logger=logger, max_epochs=1, limit_train_batches=1, limit_val_batches=3, ) assert trainer.log_dir == logger.save_dir trainer.fit(model) assert trainer.checkpoint_callback.dirpath == (tmpdir / "exp-id" / "run-id" / 'checkpoints') assert set(os.listdir(trainer.checkpoint_callback.dirpath)) == {'epoch=0-step=0.ckpt'} assert trainer.log_dir == logger.save_dir def test_mlflow_logger_dirs_creation(tmpdir): """ Test that the logger creates the folders and files in the right place. """ if not _MLFLOW_AVAILABLE: pytest.xfail("test for explicit file creation requires mlflow dependency to be installed.") assert not os.listdir(tmpdir) logger = MLFlowLogger('test', save_dir=tmpdir) assert logger.save_dir == tmpdir assert set(os.listdir(tmpdir)) == {'.trash'} run_id = logger.run_id exp_id = logger.experiment_id # multiple experiment calls should not lead to new experiment folders for i in range(2): _ = logger.experiment assert set(os.listdir(tmpdir)) == {'.trash', exp_id} assert set(os.listdir(tmpdir / exp_id)) == {run_id, 'meta.yaml'} class CustomModel(BoringModel): def training_epoch_end(self, *args, **kwargs): super().training_epoch_end(*args, **kwargs) self.log('epoch', self.current_epoch) model = CustomModel() limit_batches = 5 trainer = Trainer( default_root_dir=tmpdir, logger=logger, max_epochs=1, limit_train_batches=limit_batches, limit_val_batches=limit_batches, log_gpu_memory=True, ) trainer.fit(model) assert set(os.listdir(tmpdir / exp_id)) == {run_id, 'meta.yaml'} assert 'epoch' in os.listdir(tmpdir / exp_id / run_id / 'metrics') assert set(os.listdir(tmpdir / exp_id / run_id / 'params')) == model.hparams.keys() assert trainer.checkpoint_callback.dirpath == (tmpdir / exp_id / run_id / 'checkpoints') assert os.listdir(trainer.checkpoint_callback.dirpath) == [f'epoch=0-step={limit_batches - 1}.ckpt'] @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_experiment_id_retrieved_once(client, mlflow, tmpdir): """ Test that the logger experiment_id retrieved only once. """ logger = MLFlowLogger('test', save_dir=tmpdir) _ = logger.experiment _ = logger.experiment _ = logger.experiment assert logger.experiment.get_experiment_by_name.call_count == 1 @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_logger_with_unexpected_characters(client, mlflow, tmpdir): """ Test that the logger raises warning with special characters not accepted by MLFlow. """ logger = MLFlowLogger('test', save_dir=tmpdir) metrics = {'[some_metric]': 10} with pytest.warns(RuntimeWarning, match='special characters in metric name'): logger.log_metrics(metrics)
tests/loggers/test_mlflow.py
import os from unittest import mock from unittest.mock import MagicMock import pytest from pytorch_lightning import Trainer from pytorch_lightning.loggers import _MLFLOW_AVAILABLE, MLFlowLogger from tests.helpers import BoringModel def mock_mlflow_run_creation(logger, experiment_name=None, experiment_id=None, run_id=None): """ Helper function to simulate mlflow client creating a new (or existing) experiment. """ run = MagicMock() run.info.run_id = run_id logger._mlflow_client.get_experiment_by_name = MagicMock(return_value=experiment_name) logger._mlflow_client.create_experiment = MagicMock(return_value=experiment_id) logger._mlflow_client.create_run = MagicMock(return_value=run) return logger @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_logger_exists(client, mlflow, tmpdir): """ Test launching three independent loggers with either same or different experiment name. """ run1 = MagicMock() run1.info.run_id = "run-id-1" run2 = MagicMock() run2.info.run_id = "run-id-2" run3 = MagicMock() run3.info.run_id = "run-id-3" # simulate non-existing experiment creation client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id-1") # experiment_id client.return_value.create_run = MagicMock(return_value=run1) logger = MLFlowLogger('test', save_dir=tmpdir) assert logger._experiment_id is None assert logger._run_id is None _ = logger.experiment assert logger.experiment_id == "exp-id-1" assert logger.run_id == "run-id-1" assert logger.experiment.create_experiment.asset_called_once() client.reset_mock(return_value=True) # simulate existing experiment returns experiment id exp1 = MagicMock() exp1.experiment_id = "exp-id-1" client.return_value.get_experiment_by_name = MagicMock(return_value=exp1) client.return_value.create_run = MagicMock(return_value=run2) # same name leads to same experiment id, but different runs get recorded logger2 = MLFlowLogger('test', save_dir=tmpdir) assert logger2.experiment_id == logger.experiment_id assert logger2.run_id == "run-id-2" assert logger2.experiment.create_experiment.call_count == 0 assert logger2.experiment.create_run.asset_called_once() client.reset_mock(return_value=True) # simulate a 3rd experiment with new name client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id-3") client.return_value.create_run = MagicMock(return_value=run3) # logger with new experiment name causes new experiment id and new run id to be created logger3 = MLFlowLogger('new', save_dir=tmpdir) assert logger3.experiment_id == "exp-id-3" != logger.experiment_id assert logger3.run_id == "run-id-3" @mock.patch("pytorch_lightning.loggers.mlflow.mlflow") @mock.patch("pytorch_lightning.loggers.mlflow.MlflowClient") def test_mlflow_log_dir(client, mlflow, tmpdir): """ Test that the trainer saves checkpoints in the logger's save dir. """ # simulate experiment creation with mlflow client mock run = MagicMock() run.info.run_id = "run-id" client.return_value.get_experiment_by_name = MagicMock(return_value=None) client.return_value.create_experiment = MagicMock(return_value="exp-id") client.return_value.create_run = MagicMock(return_value=run) # test construction of default log dir path logger = MLFlowLogger("test", save_dir=tmpdir) assert logger.save_dir == tmpdir assert logger.version == "run-id" assert logger.name == "exp-id" model = BoringModel() trainer = Trainer( default_root_dir=tmpdir, logger=logger, max_epochs=1, limit_train_batches=1, limit_val_batches=3, ) assert trainer.log_dir == logger.save_dir trainer.fit(model) assert trainer.checkpoint_callback.dirpath == (tmpdir / "exp-id" / "run-id" / 'checkpoints') assert set(os.listdir(trainer.checkpoint_callback.dirpath)) == {'epoch=0-step=0.ckpt'} assert trainer.log_dir == logger.save_dir def test_mlflow_logger_dirs_creation(tmpdir): """ Test that the logger creates the folders and files in the right place. """ if not _MLFLOW_AVAILABLE: pytest.xfail("test for explicit file creation requires mlflow dependency to be installed.") assert not os.listdir(tmpdir) logger = MLFlowLogger('test', save_dir=tmpdir) assert logger.save_dir == tmpdir assert set(os.listdir(tmpdir)) == {'.trash'} run_id = logger.run_id exp_id = logger.experiment_id # multiple experiment calls should not lead to new experiment folders for i in range(2): _ = logger.experiment assert set(os.listdir(tmpdir)) == {'.trash', exp_id} assert set(os.listdir(tmpdir / exp_id)) == {run_id, 'meta.yaml'} class CustomModel(BoringModel): def training_epoch_end(self, *args, **kwargs): super().training_epoch_end(*args, **kwargs) self.log('epoch', self.current_epoch) model = CustomModel() limit_batches = 5 trainer = Trainer( default_root_dir=tmpdir, logger=logger, max_epochs=1, limit_train_batches=limit_batches, limit_val_batches=limit_batches, log_gpu_memory=True, ) trainer.fit(model) assert set(os.listdir(tmpdir / exp_id)) == {run_id, 'meta.yaml'} assert 'epoch' in os.listdir(tmpdir / exp_id / run_id / 'metrics') assert set(os.listdir(tmpdir / exp_id / run_id / 'params')) == model.hparams.keys() assert trainer.checkpoint_callback.dirpath == (tmpdir / exp_id / run_id / 'checkpoints') assert os.listdir(trainer.checkpoint_callback.dirpath) == [f'epoch=0-step={limit_batches - 1}.ckpt'] @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_experiment_id_retrieved_once(client, mlflow, tmpdir): """ Test that the logger experiment_id retrieved only once. """ logger = MLFlowLogger('test', save_dir=tmpdir) _ = logger.experiment _ = logger.experiment _ = logger.experiment assert logger.experiment.get_experiment_by_name.call_count == 1 @mock.patch('pytorch_lightning.loggers.mlflow.mlflow') @mock.patch('pytorch_lightning.loggers.mlflow.MlflowClient') def test_mlflow_logger_with_unexpected_characters(client, mlflow, tmpdir): """ Test that the logger raises warning with special characters not accepted by MLFlow. """ logger = MLFlowLogger('test', save_dir=tmpdir) metrics = {'[some_metric]': 10} with pytest.warns(RuntimeWarning, match='special characters in metric name'): logger.log_metrics(metrics)
0.584153
0.452173
import numpy as np import sys from sklearn.metrics.pairwise import euclidean_distances from scipy.optimize import linear_sum_assignment def gen_gaus_mixture(centers, mixing_prop=None, noise_sd=0.1, M=5000): # noise_sd=0.1 # M=5000 # mixing_prop=None # centers = np.random.normal(0,10,(10,500)) K, D = centers.shape if mixing_prop is None: mixing_prop = np.random.dirichlet(np.ones(K)) assignments = np.random.choice(K, size=M, p=mixing_prop) data_j = np.zeros((M,D)) for k in range(K): data_j[assignments==k] = np.random.normal(loc=centers[k], scale=noise_sd, size=((assignments==k).sum(),D)) return data_j def gen_partition(L, J, D, M=5000, base_measure='gaus', ll='gaus', local_model='mixture', local_sd=0.1, global_sd=None, mu0=0, a=1, b=1): # base_measure=='gaus' # ll = 'gaus' # local_model='mixture' # noise_local_sd=0.1 # a=1 # b=1 # L = 100 # J = 10 # D = 50 # M = 5000 if global_sd is None: global_sd = np.sqrt(L) global_p = np.random.beta(a=a, b=b, size=L) # MANUAL idxs_list = [[0, 1], [1,2], [0,2]] if base_measure=='gaus': global_atoms = np.random.normal(mu0,global_sd,size=(L,D)) else: sys.exit('unsupported base measure') data = [] used_components = set() atoms = [] for j in range(J): atoms_j_idx = [l for l in range(L) if np.random.binomial(1, global_p[l])] used_components.update(atoms_j_idx) if ll=='gaus': atoms_j = np.random.normal(global_atoms[atoms_j_idx], scale=local_sd) else: sys.exit('unsupported likelihood kernel') if local_model=='mixture': data_j = gen_gaus_mixture(atoms_j, M=M) else: sys.exit('unsupported local model') data.append(data_j) atoms.append(atoms_j) if len(used_components)<L: L = len(used_components) L_idx = list(used_components) global_p = global_p[L_idx] global_atoms = global_atoms[L_idx] print('Removing unused components; new L is %d' % L) return global_atoms, global_p, data, atoms def hungarian_match(est_atoms, true_atoms): # true_atoms = global_atoms # est_atoms = global_atoms[np.random.permutation(global_atoms.shape[0])] dist = euclidean_distances(true_atoms, est_atoms) row_ind, col_ind = linear_sum_assignment(dist) obj = [] for r, c in zip(row_ind, col_ind): obj.append(dist[r,c]) return obj def min_match(est_atoms, true_atoms): e_to_t = np.apply_along_axis(lambda x: np.sqrt(((true_atoms-x)**2).sum(axis=1)), 1, est_atoms) return max([max(np.min(e_to_t, axis=0)), max(np.min(e_to_t, axis=1))])
simulation/data_sampling.py
import numpy as np import sys from sklearn.metrics.pairwise import euclidean_distances from scipy.optimize import linear_sum_assignment def gen_gaus_mixture(centers, mixing_prop=None, noise_sd=0.1, M=5000): # noise_sd=0.1 # M=5000 # mixing_prop=None # centers = np.random.normal(0,10,(10,500)) K, D = centers.shape if mixing_prop is None: mixing_prop = np.random.dirichlet(np.ones(K)) assignments = np.random.choice(K, size=M, p=mixing_prop) data_j = np.zeros((M,D)) for k in range(K): data_j[assignments==k] = np.random.normal(loc=centers[k], scale=noise_sd, size=((assignments==k).sum(),D)) return data_j def gen_partition(L, J, D, M=5000, base_measure='gaus', ll='gaus', local_model='mixture', local_sd=0.1, global_sd=None, mu0=0, a=1, b=1): # base_measure=='gaus' # ll = 'gaus' # local_model='mixture' # noise_local_sd=0.1 # a=1 # b=1 # L = 100 # J = 10 # D = 50 # M = 5000 if global_sd is None: global_sd = np.sqrt(L) global_p = np.random.beta(a=a, b=b, size=L) # MANUAL idxs_list = [[0, 1], [1,2], [0,2]] if base_measure=='gaus': global_atoms = np.random.normal(mu0,global_sd,size=(L,D)) else: sys.exit('unsupported base measure') data = [] used_components = set() atoms = [] for j in range(J): atoms_j_idx = [l for l in range(L) if np.random.binomial(1, global_p[l])] used_components.update(atoms_j_idx) if ll=='gaus': atoms_j = np.random.normal(global_atoms[atoms_j_idx], scale=local_sd) else: sys.exit('unsupported likelihood kernel') if local_model=='mixture': data_j = gen_gaus_mixture(atoms_j, M=M) else: sys.exit('unsupported local model') data.append(data_j) atoms.append(atoms_j) if len(used_components)<L: L = len(used_components) L_idx = list(used_components) global_p = global_p[L_idx] global_atoms = global_atoms[L_idx] print('Removing unused components; new L is %d' % L) return global_atoms, global_p, data, atoms def hungarian_match(est_atoms, true_atoms): # true_atoms = global_atoms # est_atoms = global_atoms[np.random.permutation(global_atoms.shape[0])] dist = euclidean_distances(true_atoms, est_atoms) row_ind, col_ind = linear_sum_assignment(dist) obj = [] for r, c in zip(row_ind, col_ind): obj.append(dist[r,c]) return obj def min_match(est_atoms, true_atoms): e_to_t = np.apply_along_axis(lambda x: np.sqrt(((true_atoms-x)**2).sum(axis=1)), 1, est_atoms) return max([max(np.min(e_to_t, axis=0)), max(np.min(e_to_t, axis=1))])
0.276202
0.332026
import os import sys import warnings import openstackdocstheme sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('.')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'openstackdocstheme', 'enforcer' ] # openstackdocstheme options repository_name = 'openstack/openstacksdk' bug_project = '972' bug_tag = '' html_last_updated_fmt = '%Y-%m-%d %H:%M' html_theme = 'openstackdocs' # TODO(shade) Set this to true once the build-openstack-sphinx-docs job is # updated to use sphinx-build. # When True, this will raise an exception that kills sphinx-build. enforcer_warnings_as_errors = False # autodoc generation is a bit aggressive and a nuisance when doing heavy # text edit cycles. # execute "export SPHINX_DEBUG=1" in your terminal to disable # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'openstacksdk' copyright = u'2017, Various members of the OpenStack Foundation' # A few variables have to be set for the log-a-bug feature. # gitsha: The SHA checksum of the bug description. Extracted from git log. # bug_tag: Tag for categorizing the bug. Must be set manually. # bug_project: Launchpad project to file bugs against. # These variables are passed to the logabug code via html_context. git_cmd = "/usr/bin/git log | head -n1 | cut -f2 -d' '" try: gitsha = os.popen(git_cmd).read().strip('\n') except Exception: warnings.warn("Can not get git sha.") gitsha = "unknown" bug_tag = "docs" pwd = os.getcwd() # html_context allows us to pass arbitrary values into the html template html_context = {"pwd": pwd, "gitsha": gitsha, "bug_tag": bug_tag, "bug_project": bug_project} # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' autodoc_member_order = "bysource" # Locations to exclude when looking for source files. exclude_patterns = [] # -- Options for HTML output ---------------------------------------------- # Don't let openstackdocstheme insert TOCs automatically. theme_include_auto_toc = False # Output file base name for HTML help builder. htmlhelp_basename = '%sdoc' % project # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', '%s.tex' % project, u'%s Documentation' % project, u'OpenStack Foundation', 'manual'), ] # Include both the class and __init__ docstrings when describing the class autoclass_content = "both"
doc/source/conf.py
import os import sys import warnings import openstackdocstheme sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('.')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'openstackdocstheme', 'enforcer' ] # openstackdocstheme options repository_name = 'openstack/openstacksdk' bug_project = '972' bug_tag = '' html_last_updated_fmt = '%Y-%m-%d %H:%M' html_theme = 'openstackdocs' # TODO(shade) Set this to true once the build-openstack-sphinx-docs job is # updated to use sphinx-build. # When True, this will raise an exception that kills sphinx-build. enforcer_warnings_as_errors = False # autodoc generation is a bit aggressive and a nuisance when doing heavy # text edit cycles. # execute "export SPHINX_DEBUG=1" in your terminal to disable # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'openstacksdk' copyright = u'2017, Various members of the OpenStack Foundation' # A few variables have to be set for the log-a-bug feature. # gitsha: The SHA checksum of the bug description. Extracted from git log. # bug_tag: Tag for categorizing the bug. Must be set manually. # bug_project: Launchpad project to file bugs against. # These variables are passed to the logabug code via html_context. git_cmd = "/usr/bin/git log | head -n1 | cut -f2 -d' '" try: gitsha = os.popen(git_cmd).read().strip('\n') except Exception: warnings.warn("Can not get git sha.") gitsha = "unknown" bug_tag = "docs" pwd = os.getcwd() # html_context allows us to pass arbitrary values into the html template html_context = {"pwd": pwd, "gitsha": gitsha, "bug_tag": bug_tag, "bug_project": bug_project} # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' autodoc_member_order = "bysource" # Locations to exclude when looking for source files. exclude_patterns = [] # -- Options for HTML output ---------------------------------------------- # Don't let openstackdocstheme insert TOCs automatically. theme_include_auto_toc = False # Output file base name for HTML help builder. htmlhelp_basename = '%sdoc' % project # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', '%s.tex' % project, u'%s Documentation' % project, u'OpenStack Foundation', 'manual'), ] # Include both the class and __init__ docstrings when describing the class autoclass_content = "both"
0.242385
0.077762
import vtk ROOT_SPLIT = 10 TARGET_LEVEL = 8 TARGET_LEVEL = 6 CUT_OFF = TARGET_LEVEL # ----------------------------------------------------------------------------- # Helpers # ----------------------------------------------------------------------------- def mandelbrotTest(x, y, timeStep=0): count = 0 cReal = float(x) cImag = float(y) zReal = 0.0 zImag = float(timeStep) / 10.0 zReal2 = zReal * zReal zImag2 = zImag * zImag v1 = zReal2 + zImag2 while v1 < 4.0 and count < 100: zImag = 2.0 * zReal * zImag + cImag zReal = zReal2 - zImag2 + cReal zReal2 = zReal * zReal zImag2 = zImag * zImag count += 1 v1 = zReal2 + zImag2 return count == 100 def mandelbrotSide(bounds): count = 1 if mandelbrotTest(bounds[0], bounds[2]): count += 1 if mandelbrotTest(bounds[1], bounds[2]): count += 1 if mandelbrotTest(bounds[0], bounds[3]): count += 1 if mandelbrotTest(bounds[1], bounds[3]): count += 1 return count def shouldRefine(level, bounds): if level >= TARGET_LEVEL: return False origin = mandelbrotTest(bounds[0], bounds[2]) originX = mandelbrotTest(bounds[1], bounds[2]) originY = mandelbrotTest(bounds[0], bounds[3]) originXY = mandelbrotTest(bounds[1], bounds[3]) canRefine = bounds[4] < 0.01 if canRefine: if origin and originX and originY and originXY: return False if not origin and not originX and not originY and not originXY: return False return True return False def handleNode(cursor, sideArray, levelArray): cellBounds = [0, -1, 0, -1, 0, -1] cursor.GetBounds(cellBounds) # Add field idx = cursor.GetGlobalNodeIndex() side = mandelbrotSide(cellBounds) sideArray.InsertTuple1(idx, side) mask.InsertTuple1(idx, side < CUT_OFF) if cursor.IsLeaf(): if shouldRefine(cursor.GetLevel(), cellBounds): cursor.SubdivideLeaf() handleNode(cursor, sideArray, mask) else: for childIdx in range(cursor.GetNumberOfChildren()): cursor.ToChild(childIdx) handleNode(cursor, sideArray, mask) cursor.ToParent() # ----------------------------------------------------------------------------- # Create Simple HTG # ----------------------------------------------------------------------------- geoCursor = vtk.vtkHyperTreeGridNonOrientedGeometryCursor() htg = vtk.vtkHyperTreeGrid() htg.Initialize() htg.SetDimensions( [ROOT_SPLIT + 1, ROOT_SPLIT + 1, 2] ) # nb cells, not nb points : GridCell [ROOT_SPLIT, ROOT_SPLIT, 1] htg.SetBranchFactor(2) sideArray = vtk.vtkUnsignedCharArray() sideArray.SetName("sideArray") sideArray.SetNumberOfValues(0) sideArray.SetNumberOfComponents(1) htg.GetCellData().AddArray(sideArray) mask = vtk.vtkBitArray() mask.SetName("mask") # X[-1.75, 0.75] xValues = vtk.vtkDoubleArray() xValues.SetNumberOfValues(ROOT_SPLIT + 1) for i in range(ROOT_SPLIT + 1): xValues.SetValue(i, -1.75 + float(i) * 0.25) htg.SetXCoordinates(xValues) # Y[-1.25, 1.25] yValues = vtk.vtkDoubleArray() yValues.SetNumberOfValues(ROOT_SPLIT + 1) for i in range(ROOT_SPLIT + 1): yValues.SetValue(i, -1.25 + float(i) * 0.25) htg.SetYCoordinates(yValues) # Z[0, 0] zValues = vtk.vtkDoubleArray() zValues.SetNumberOfValues(2) zValues.SetValue(0, 0) zValues.SetValue(1, 0.25) htg.SetZCoordinates(zValues) offsetIndex = 0 for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedGeometryCursor(geoCursor, treeId, True) geoCursor.SetGlobalIndexStart(offsetIndex) handleNode(geoCursor, sideArray, mask) offsetIndex += geoCursor.GetTree().GetNumberOfVertices() print("offsetIndex: ", offsetIndex) # Squeeze htg.Squeeze() # Activation d'une scalaire htg.GetCellData().SetActiveScalars("sideArray") # DataRange sideArray on PointData HTG dataRange = htg.GetCellData().GetArray("sideArray").GetRange() print("sideArray on PointData HTG:", dataRange) print("HTG:", htg.GetNumberOfVertices()) # Tests cursors... in Python def recursive(cursor): if cursor.IsLeaf(): return 1 nb = 0 for ichild in range(cursor.GetNumberOfChildren()): cursor.ToChild(ichild) nb += recursive(cursor) cursor.ToParent() return nb def nonOrientedCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb expected = nonOrientedCursor(htg, None) def nonOrientedGeometryCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedGeometryCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedGeometryCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedGeometryCursor(htg, expected) def nonOrientedVonNeumannSuperCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedVonNeumannSuperCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedVonNeumannSuperCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedVonNeumannSuperCursor(htg, expected) def nonOrientedMooreSuperCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedMooreSuperCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedMooreSuperCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedMooreSuperCursor(htg, expected) # Test Find findx = [ -1.75 + float(ROOT_SPLIT) * 0.5 * 0.25, -1.75 + float(ROOT_SPLIT) * 0.5 * 0.25, 0.11, ] print("--------- FindNonOrientedGeometryCursor ---------") cursor = htg.FindNonOrientedGeometryCursor(findx) cursor.UnRegister(htg) bbox = [ -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, ] cursor.GetBounds(bbox) print("bbox: ", bbox) point = [ -1.0, -1.0, -1.0, ] cursor.GetPoint(point) print("point: ", point[0], point[1], point[2]) print("IsLeaf: ", cursor.IsLeaf()) assert cursor.IsLeaf() print(bbox[0], " <= ", findx[0], " and ", findx[0], " <= ", bbox[1]) if bbox[0] <= findx[0] and findx[0] <= bbox[1]: pass else: assert bbox[0] <= findx[0] and findx[0] <= bbox[1] print(bbox[2], " <= ", findx[1], " and ", findx[1], " <= ", bbox[3]) if bbox[2] <= findx[1] and findx[1] <= bbox[3]: pass else: assert bbox[2] <= findx[1] and findx[1] <= bbox[3] print(bbox[4], " <= ", findx[2], " and ", findx[2], " <= ", bbox[5]) if bbox[4] <= findx[2] and findx[2] <= bbox[5]: pass else: assert bbox[4] <= findx[2] and findx[2] <= bbox[5] # --- end of script --
Common/DataModel/Testing/Python/TestHyperTreeGrid3DCursorsMandel.py
import vtk ROOT_SPLIT = 10 TARGET_LEVEL = 8 TARGET_LEVEL = 6 CUT_OFF = TARGET_LEVEL # ----------------------------------------------------------------------------- # Helpers # ----------------------------------------------------------------------------- def mandelbrotTest(x, y, timeStep=0): count = 0 cReal = float(x) cImag = float(y) zReal = 0.0 zImag = float(timeStep) / 10.0 zReal2 = zReal * zReal zImag2 = zImag * zImag v1 = zReal2 + zImag2 while v1 < 4.0 and count < 100: zImag = 2.0 * zReal * zImag + cImag zReal = zReal2 - zImag2 + cReal zReal2 = zReal * zReal zImag2 = zImag * zImag count += 1 v1 = zReal2 + zImag2 return count == 100 def mandelbrotSide(bounds): count = 1 if mandelbrotTest(bounds[0], bounds[2]): count += 1 if mandelbrotTest(bounds[1], bounds[2]): count += 1 if mandelbrotTest(bounds[0], bounds[3]): count += 1 if mandelbrotTest(bounds[1], bounds[3]): count += 1 return count def shouldRefine(level, bounds): if level >= TARGET_LEVEL: return False origin = mandelbrotTest(bounds[0], bounds[2]) originX = mandelbrotTest(bounds[1], bounds[2]) originY = mandelbrotTest(bounds[0], bounds[3]) originXY = mandelbrotTest(bounds[1], bounds[3]) canRefine = bounds[4] < 0.01 if canRefine: if origin and originX and originY and originXY: return False if not origin and not originX and not originY and not originXY: return False return True return False def handleNode(cursor, sideArray, levelArray): cellBounds = [0, -1, 0, -1, 0, -1] cursor.GetBounds(cellBounds) # Add field idx = cursor.GetGlobalNodeIndex() side = mandelbrotSide(cellBounds) sideArray.InsertTuple1(idx, side) mask.InsertTuple1(idx, side < CUT_OFF) if cursor.IsLeaf(): if shouldRefine(cursor.GetLevel(), cellBounds): cursor.SubdivideLeaf() handleNode(cursor, sideArray, mask) else: for childIdx in range(cursor.GetNumberOfChildren()): cursor.ToChild(childIdx) handleNode(cursor, sideArray, mask) cursor.ToParent() # ----------------------------------------------------------------------------- # Create Simple HTG # ----------------------------------------------------------------------------- geoCursor = vtk.vtkHyperTreeGridNonOrientedGeometryCursor() htg = vtk.vtkHyperTreeGrid() htg.Initialize() htg.SetDimensions( [ROOT_SPLIT + 1, ROOT_SPLIT + 1, 2] ) # nb cells, not nb points : GridCell [ROOT_SPLIT, ROOT_SPLIT, 1] htg.SetBranchFactor(2) sideArray = vtk.vtkUnsignedCharArray() sideArray.SetName("sideArray") sideArray.SetNumberOfValues(0) sideArray.SetNumberOfComponents(1) htg.GetCellData().AddArray(sideArray) mask = vtk.vtkBitArray() mask.SetName("mask") # X[-1.75, 0.75] xValues = vtk.vtkDoubleArray() xValues.SetNumberOfValues(ROOT_SPLIT + 1) for i in range(ROOT_SPLIT + 1): xValues.SetValue(i, -1.75 + float(i) * 0.25) htg.SetXCoordinates(xValues) # Y[-1.25, 1.25] yValues = vtk.vtkDoubleArray() yValues.SetNumberOfValues(ROOT_SPLIT + 1) for i in range(ROOT_SPLIT + 1): yValues.SetValue(i, -1.25 + float(i) * 0.25) htg.SetYCoordinates(yValues) # Z[0, 0] zValues = vtk.vtkDoubleArray() zValues.SetNumberOfValues(2) zValues.SetValue(0, 0) zValues.SetValue(1, 0.25) htg.SetZCoordinates(zValues) offsetIndex = 0 for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedGeometryCursor(geoCursor, treeId, True) geoCursor.SetGlobalIndexStart(offsetIndex) handleNode(geoCursor, sideArray, mask) offsetIndex += geoCursor.GetTree().GetNumberOfVertices() print("offsetIndex: ", offsetIndex) # Squeeze htg.Squeeze() # Activation d'une scalaire htg.GetCellData().SetActiveScalars("sideArray") # DataRange sideArray on PointData HTG dataRange = htg.GetCellData().GetArray("sideArray").GetRange() print("sideArray on PointData HTG:", dataRange) print("HTG:", htg.GetNumberOfVertices()) # Tests cursors... in Python def recursive(cursor): if cursor.IsLeaf(): return 1 nb = 0 for ichild in range(cursor.GetNumberOfChildren()): cursor.ToChild(ichild) nb += recursive(cursor) cursor.ToParent() return nb def nonOrientedCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb expected = nonOrientedCursor(htg, None) def nonOrientedGeometryCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedGeometryCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedGeometryCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedGeometryCursor(htg, expected) def nonOrientedVonNeumannSuperCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedVonNeumannSuperCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedVonNeumannSuperCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedVonNeumannSuperCursor(htg, expected) def nonOrientedMooreSuperCursor(htg, expected): nb = 0 cursor = vtk.vtkHyperTreeGridNonOrientedMooreSuperCursor() for treeId in range(htg.GetMaxNumberOfTrees()): htg.InitializeNonOrientedMooreSuperCursor(cursor, treeId) if not cursor.IsMasked(): nb += recursive(cursor) print("nb: ", nb) if expected and nb != expected: print("ERROR Not corresponding expected value") return nb nonOrientedMooreSuperCursor(htg, expected) # Test Find findx = [ -1.75 + float(ROOT_SPLIT) * 0.5 * 0.25, -1.75 + float(ROOT_SPLIT) * 0.5 * 0.25, 0.11, ] print("--------- FindNonOrientedGeometryCursor ---------") cursor = htg.FindNonOrientedGeometryCursor(findx) cursor.UnRegister(htg) bbox = [ -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, ] cursor.GetBounds(bbox) print("bbox: ", bbox) point = [ -1.0, -1.0, -1.0, ] cursor.GetPoint(point) print("point: ", point[0], point[1], point[2]) print("IsLeaf: ", cursor.IsLeaf()) assert cursor.IsLeaf() print(bbox[0], " <= ", findx[0], " and ", findx[0], " <= ", bbox[1]) if bbox[0] <= findx[0] and findx[0] <= bbox[1]: pass else: assert bbox[0] <= findx[0] and findx[0] <= bbox[1] print(bbox[2], " <= ", findx[1], " and ", findx[1], " <= ", bbox[3]) if bbox[2] <= findx[1] and findx[1] <= bbox[3]: pass else: assert bbox[2] <= findx[1] and findx[1] <= bbox[3] print(bbox[4], " <= ", findx[2], " and ", findx[2], " <= ", bbox[5]) if bbox[4] <= findx[2] and findx[2] <= bbox[5]: pass else: assert bbox[4] <= findx[2] and findx[2] <= bbox[5] # --- end of script --
0.428712
0.395368
import cmath import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy.signal as signal from ..utils.Autocorrelation import Autocorrelation sns.set() class AutocorrelationMethod(): def __init__(self): self.f = None self.default_f = np.linspace(0, 0.5, 500) self.x = None self.p = None self.a = None self.var_u = None self.P = None self.r_xx = Autocorrelation() def estimate(self, x, f=None, p=2): ''' Estimates P_xx for given signal sequence x. Args: x (numpy array of doubles): Signal f (numpy array of doubles): Frequence p (integer): Polinomial order in A(f) ''' # Init values self.x = x if f is None: self.f = self.default_f else: self.f = f self.p = p self.P = np.zeros(len(self.f)) # Estimate autoccorelation self.r_xx.estimate(x) # Compose matrix Rxx Rxx = np.zeros([p, p]) for i in range(p): for j in range(p): Rxx[i][j] = self.r_xx[i - j] # Compose vector rxx rxx_vec = np.zeros([p, 1]) for i in range(p): rxx_vec[i] = self.r_xx[i + 1] # Calculate a and append [1] for a[0] self.a = np.matmul(-np.linalg.inv(Rxx), rxx_vec) self.a = np.append([[1]], self.a, axis=0) # Calculate var_u self.var_u = 0 for i in range(p + 1): self.var_u += self.a[i] * self.r_xx[-i] # Calculate P for fi in range(len(self.f)): A = 0 for i in range(p + 1): A += self.a[i] * cmath.exp(-1j * 2*cmath.pi * self.f[fi] * i) self.P[fi] = self.var_u / pow(abs(A), 2) def plot(self): ''' Plots estimated P. ''' # Check if anything is estimated. if self.f is None or self.P is None: return plt.figure() plt.semilogy(self.f, self.P) plt.title('Autocorrelation method estimation') plt.xlabel('f [Hz]') plt.ylabel('P') plt.show() def __getitem__(self, key): if key == 'f': return self.f if key == 'P': return self.P if key == 'x': return self.x if key == 'a': return self.a if key == 'var_u': return self.var_u if key == 'p': return self.p return None
python/source/parametric/AutocorrelationMethod.py
import cmath import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy.signal as signal from ..utils.Autocorrelation import Autocorrelation sns.set() class AutocorrelationMethod(): def __init__(self): self.f = None self.default_f = np.linspace(0, 0.5, 500) self.x = None self.p = None self.a = None self.var_u = None self.P = None self.r_xx = Autocorrelation() def estimate(self, x, f=None, p=2): ''' Estimates P_xx for given signal sequence x. Args: x (numpy array of doubles): Signal f (numpy array of doubles): Frequence p (integer): Polinomial order in A(f) ''' # Init values self.x = x if f is None: self.f = self.default_f else: self.f = f self.p = p self.P = np.zeros(len(self.f)) # Estimate autoccorelation self.r_xx.estimate(x) # Compose matrix Rxx Rxx = np.zeros([p, p]) for i in range(p): for j in range(p): Rxx[i][j] = self.r_xx[i - j] # Compose vector rxx rxx_vec = np.zeros([p, 1]) for i in range(p): rxx_vec[i] = self.r_xx[i + 1] # Calculate a and append [1] for a[0] self.a = np.matmul(-np.linalg.inv(Rxx), rxx_vec) self.a = np.append([[1]], self.a, axis=0) # Calculate var_u self.var_u = 0 for i in range(p + 1): self.var_u += self.a[i] * self.r_xx[-i] # Calculate P for fi in range(len(self.f)): A = 0 for i in range(p + 1): A += self.a[i] * cmath.exp(-1j * 2*cmath.pi * self.f[fi] * i) self.P[fi] = self.var_u / pow(abs(A), 2) def plot(self): ''' Plots estimated P. ''' # Check if anything is estimated. if self.f is None or self.P is None: return plt.figure() plt.semilogy(self.f, self.P) plt.title('Autocorrelation method estimation') plt.xlabel('f [Hz]') plt.ylabel('P') plt.show() def __getitem__(self, key): if key == 'f': return self.f if key == 'P': return self.P if key == 'x': return self.x if key == 'a': return self.a if key == 'var_u': return self.var_u if key == 'p': return self.p return None
0.623835
0.358044
import uuid import base64 import json from flask import jsonify, make_response from flask_restful import abort import ast as type_evaluation def is_valid_uuid(val): try: uuid.UUID(str(val), version=4) return True except ValueError: return False def get_or_create(session, model, keys, **kwargs): if not keys: keys = kwargs.keys() if isinstance(keys, str): keys = [keys] if not isinstance(keys, list): raise TypeError('keys argument must be a list or string') instance = session.query(model).filter_by(**{k: kwargs[k] for k in keys}).first() if instance: for k, v in kwargs.items(): setattr(instance, k, v) else: instance = model(**kwargs) session.add(instance) session.flush() return instance def delete_record(session, model, **kwargs): """ Deletes a record filtered by key(s) present in kwargs(contains model specific fields).""" keys = list(kwargs.keys()) instance = session.query(model).filter_by(**{k: kwargs[k] for k in keys}).first() if instance: session.delete(instance) session.commit() return instance def identity(request): ident = request.headers.get('X-RH-IDENTITY') if not ident: response = make_response( jsonify({"Error": "Authentication token not provided"}), 401) abort(response) else: return json.loads(base64.b64decode(ident)) def user_data_from_identity(identity): """ Get the user details dict from the rh-identity data or error out. """ if 'user' not in identity: return None return identity['user'] def validate_type(value, type_): """ Validate the type of a value. Currently available types: bool :param value: Value to validate. :param type_: Type to validate against. :return: True if the value is of the specified type, False otherwise. """ if type_ == bool: # ast.literal_eval does not understand lowercase 'True' or 'False' value = value.capitalize() if value in ['true', 'false'] else value evaluated_value = type_evaluation.literal_eval(value) if value else None return True if type(evaluated_value) == type_ else False def convert_to_iops_actuals(iops_dict): """ Convert IOPS to MBPS fom percentage. In case IOPS values are actual, converts them to int from str :param iops_dict: IOPS dict to convert. :return: IOPS values converted to MBPS. """ iops_in_mbps = {} for key, value in iops_dict.items(): if float(value) < 1.0: iops_in_mbps[key] = int(float(value) * 1000) else: iops_in_mbps[key] = int(value) return iops_in_mbps def sort_io_dict(performance_utilization: dict): """ Sorts io dict by max_io in descending order. """ sorted_io_dict = { 'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True)) } performance_utilization.update({**sorted_io_dict}) del performance_utilization['io'] return performance_utilization
ros/lib/utils.py
import uuid import base64 import json from flask import jsonify, make_response from flask_restful import abort import ast as type_evaluation def is_valid_uuid(val): try: uuid.UUID(str(val), version=4) return True except ValueError: return False def get_or_create(session, model, keys, **kwargs): if not keys: keys = kwargs.keys() if isinstance(keys, str): keys = [keys] if not isinstance(keys, list): raise TypeError('keys argument must be a list or string') instance = session.query(model).filter_by(**{k: kwargs[k] for k in keys}).first() if instance: for k, v in kwargs.items(): setattr(instance, k, v) else: instance = model(**kwargs) session.add(instance) session.flush() return instance def delete_record(session, model, **kwargs): """ Deletes a record filtered by key(s) present in kwargs(contains model specific fields).""" keys = list(kwargs.keys()) instance = session.query(model).filter_by(**{k: kwargs[k] for k in keys}).first() if instance: session.delete(instance) session.commit() return instance def identity(request): ident = request.headers.get('X-RH-IDENTITY') if not ident: response = make_response( jsonify({"Error": "Authentication token not provided"}), 401) abort(response) else: return json.loads(base64.b64decode(ident)) def user_data_from_identity(identity): """ Get the user details dict from the rh-identity data or error out. """ if 'user' not in identity: return None return identity['user'] def validate_type(value, type_): """ Validate the type of a value. Currently available types: bool :param value: Value to validate. :param type_: Type to validate against. :return: True if the value is of the specified type, False otherwise. """ if type_ == bool: # ast.literal_eval does not understand lowercase 'True' or 'False' value = value.capitalize() if value in ['true', 'false'] else value evaluated_value = type_evaluation.literal_eval(value) if value else None return True if type(evaluated_value) == type_ else False def convert_to_iops_actuals(iops_dict): """ Convert IOPS to MBPS fom percentage. In case IOPS values are actual, converts them to int from str :param iops_dict: IOPS dict to convert. :return: IOPS values converted to MBPS. """ iops_in_mbps = {} for key, value in iops_dict.items(): if float(value) < 1.0: iops_in_mbps[key] = int(float(value) * 1000) else: iops_in_mbps[key] = int(value) return iops_in_mbps def sort_io_dict(performance_utilization: dict): """ Sorts io dict by max_io in descending order. """ sorted_io_dict = { 'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True)) } performance_utilization.update({**sorted_io_dict}) del performance_utilization['io'] return performance_utilization
0.531696
0.177882
class AliKeyDecryptor(object): def decrypt(self, key): result = None se = ord("a") if(len(key) == 20): r = key[0] i = chr(r).lower() a = int(i, base=36) % 7 # n = key[a] # o = chr(n) # s = key[a+1] # l = chr(s) # u = int(o+l, base=36) % 3 # equal to 36*o + l, only consider "l" is enough s = key[a + 1] l = chr(s) u = int(l, base=36) % 3 if(u == 2): d = key[8] h = key[9] c = key[10] f = key[11] p = key[15] g = key[16] v = key[17] y = key[18] m = d - se + 26 * (int(chr(h)) + 1) - se b = c - se + 26 * (int(chr(f)) + 1) - se E = p - se + 26 * (int(chr(g)) + 1) - se T = v - se + 26 * (int(chr(y)) + 2) - se #result = str(key[0]) + str(key[1]) + str(key[2]) + str(key[3]) + str(key[4]) + str(key[5]) + str(key[6]) + str(key[7]) + str(m) + str(b) + str(key[12]) + str(key[13]) + str(key[14]) + str(E) + str(T) + str(key[19]) result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(m) result.append(b) result.append(key[12]) result.append(key[13]) result.append(key[14]) result.append(E) result.append(T) result.append(key[19]) elif(u == 1): result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[18]) result.append(key[16]) result.append(key[15]) result.append(key[13]) result.append(key[12]) result.append(key[11]) result.append(key[10]) result.append(key[8]) else: # u == 0 result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[8]) result.append(key[10]) result.append(key[11]) result.append(key[12]) result.append(key[14]) result.append(key[15]) result.append(key[16]) result.append(key[18]) elif(len(key) == 17): key = key[1:] result = [] result.append(key[8]) result.append(key[9]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[0]) result.append(key[1]) result.append(key[10]) result.append(key[11]) result.append(key[12]) result.append(key[13]) result.append(key[14]) result.append(key[15]) else: result = key if(type(result) == list): result = bytes(result) return result
keydecryptor/ali.py
class AliKeyDecryptor(object): def decrypt(self, key): result = None se = ord("a") if(len(key) == 20): r = key[0] i = chr(r).lower() a = int(i, base=36) % 7 # n = key[a] # o = chr(n) # s = key[a+1] # l = chr(s) # u = int(o+l, base=36) % 3 # equal to 36*o + l, only consider "l" is enough s = key[a + 1] l = chr(s) u = int(l, base=36) % 3 if(u == 2): d = key[8] h = key[9] c = key[10] f = key[11] p = key[15] g = key[16] v = key[17] y = key[18] m = d - se + 26 * (int(chr(h)) + 1) - se b = c - se + 26 * (int(chr(f)) + 1) - se E = p - se + 26 * (int(chr(g)) + 1) - se T = v - se + 26 * (int(chr(y)) + 2) - se #result = str(key[0]) + str(key[1]) + str(key[2]) + str(key[3]) + str(key[4]) + str(key[5]) + str(key[6]) + str(key[7]) + str(m) + str(b) + str(key[12]) + str(key[13]) + str(key[14]) + str(E) + str(T) + str(key[19]) result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(m) result.append(b) result.append(key[12]) result.append(key[13]) result.append(key[14]) result.append(E) result.append(T) result.append(key[19]) elif(u == 1): result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[18]) result.append(key[16]) result.append(key[15]) result.append(key[13]) result.append(key[12]) result.append(key[11]) result.append(key[10]) result.append(key[8]) else: # u == 0 result = [] result.append(key[0]) result.append(key[1]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[8]) result.append(key[10]) result.append(key[11]) result.append(key[12]) result.append(key[14]) result.append(key[15]) result.append(key[16]) result.append(key[18]) elif(len(key) == 17): key = key[1:] result = [] result.append(key[8]) result.append(key[9]) result.append(key[2]) result.append(key[3]) result.append(key[4]) result.append(key[5]) result.append(key[6]) result.append(key[7]) result.append(key[0]) result.append(key[1]) result.append(key[10]) result.append(key[11]) result.append(key[12]) result.append(key[13]) result.append(key[14]) result.append(key[15]) else: result = key if(type(result) == list): result = bytes(result) return result
0.112527
0.149967
import Tkinter import tkFont def mid(l1, l2): return (int((l1[0]+l2[0]) / 2), int((l1[1]+l2[1]) / 2)) class SimulatorUI: def __init__(self, settings): self.settings = settings self.square_size = 40 self.border_width = 1 self.padding = 0 self.arrow_width = 3 self.selection_border_width = 5 self.fill_color = "#FFF" self.obstacle_fill_color = "#555" self.bot_fill_color = ["#57C", "#C75"] self.border_color = "#333" self.selection_border_color = "#FF0" self.move_arrow_color = "#00F" self.attack_arrow_color = "#000" self.map_width = self.settings.board_size self.map_height = self.settings.board_size self.width = self.square_size*self.map_width self.height = self.square_size*self.map_height self.root = Tkinter.Tk() self.root.resizable(0, 0) self.setTitle("Robot Game") self.turn_label = Tkinter.Label(self.root, text = "") self.turn_label.pack() self.setTurn(1) self.canvas = Tkinter.Canvas(self.root, width = self.width, height = self.height) self.canvas.pack() self.squares = {} self.labels = {} self.actions = {} for x in xrange(0, self.map_width): for y in xrange(0, self.map_height): coordinates = self.getSquareCoordinates((x, y)) x1, y1 = coordinates[0] x2, y2 = coordinates[1] self.squares[(x, y)] = self.canvas.create_rectangle( x1, y1, x2, y2, fill = self.obstacle_fill_color if (x, y) in self.settings['obstacles'] else self.fill_color, outline = self.border_color, width = self.border_width ) self.labels[(x, y)] = self.canvas.create_text( x1 + self.square_size/2, y1 + self.square_size/2, text = (x+1)*(y+1)-1 if x*y == 0 else "", font = "TkFixedFont", fill = "#000" ) self.actions[(x, y)] = [] self.center = (int(self.map_width/2), int(self.map_height/2)) self.selection = self.center selection_coordinates = self.getSquareCoordinates(self.selection) selection_x1, selection_y1 = selection_coordinates[0] selection_x2, selection_y2 = selection_coordinates[1] self.selection_square = self.canvas.create_rectangle( selection_x1, selection_y1, selection_x2, selection_y2, fill = "", outline = self.selection_border_color, width = self.selection_border_width ) # I am a dirty hack, fix me text_font = tkFont.nametofont("TkTextFont") text_font.configure(weight = "bold") def run(self): self.root.mainloop() def bind(self, event, hook): self.root.bind(event, hook) def onMouseClick(self, event): self.setSelection(self.getSquareByCoordinates(event.x, event.y)) def getSquareCoordinates(self, loc): x, y = loc return ( (self.square_size*x + self.padding/2, self.square_size*y + self.padding/2), (self.square_size*(x + 1) - self.padding/2, self.square_size*(y + 1) - self.padding/2) ) def getSquareByCoordinates(self, x, y): return (x/self.square_size, y/self.square_size) def hideSelection(self): self.canvas.itemconfigure(self.selection_square, width = 0) def showSelection(self): self.canvas.itemconfigure(self.selection_square, width = self.selection_border_width) def setSelection(self, loc): if loc not in self.settings['obstacles']: selection_coordinates = self.getSquareCoordinates(loc) selection_x1, selection_y1 = selection_coordinates[0] selection_x2, selection_y2 = selection_coordinates[1] self.canvas.coords(self.selection_square, selection_x1, selection_y1, selection_x2, selection_y2) self.selection = loc def moveSelection(self, dloc): self.setSelection((self.selection[0] + dloc[0], self.selection[1] + dloc[1])) def setTitle(self, title): self.root.title(title) def setTurn(self, turn): self.turn_label.config(text = "Turn %s" % turn) def setFill(self, loc, color): self.canvas.itemconfigure(self.squares[loc], fill = color) def setText(self, loc, text): self.canvas.itemconfigure(self.labels[loc], text = text) def renderEmpty(self, loc): self.setText(loc, "") self.setFill(loc, self.obstacle_fill_color if loc in self.settings['obstacles'] else self.fill_color) def clearBots(self): for x in xrange(1, self.map_width): for y in xrange(1, self.map_height): self.renderEmpty((x, y)) def renderBot(self, loc, hp, player_id): self.setText(loc, hp) self.setFill(loc, self.bot_fill_color[player_id]) def clearAction(self, loc): for action in self.actions[loc]: self.canvas.delete(action) self.actions[loc] = [] def clearActions(self): for loc in self.actions: self.clearAction(loc) def fadeAction(self, loc): for action in self.actions[loc]: if self.canvas.type(action) == "text": old_text = self.canvas.itemcget(action, "text") new_text = old_text.strip("()") new_text = "("+new_text+")" self.canvas.itemconfig(action, fill="#CCC", text=new_text) else: self.canvas.itemconfig(action, fill="#CCC") def fadeActions(self): for loc in self.actions: self.fadeAction(loc) def renderActionChar(self, loc, char): coordinates = self.getSquareCoordinates(loc) center_coordinates = mid(coordinates[0], coordinates[1]) char_coordinates = mid(center_coordinates, coordinates[1]) x, y = char_coordinates action_char = self.canvas.create_text( x, y, text = char, font = "TkTextFont", fill = "#000" ) self.actions[loc].append(action_char) def renderActionArrow(self, loc, loc2, color): coordinates1 = self.getSquareCoordinates(loc) center_coordinates1 = mid(coordinates1[0], coordinates1[1]) coordinates2 = self.getSquareCoordinates(loc2) center_coordinates2 = mid(coordinates2[0], coordinates2[1]) mid_coordinates = mid(center_coordinates1, center_coordinates2) x1, y1 = mid(center_coordinates1, mid_coordinates) x2, y2 = mid(center_coordinates2, mid_coordinates) arrow = self.canvas.create_line(x1, y1, x2, y2, fill = color, width = self.arrow_width, arrow = Tkinter.LAST) self.actions[loc].append(arrow) def renderAction(self, loc, action): if action[0] == "guard": self.renderActionChar(loc, "G") elif action[0] == "suicide": self.renderActionChar(loc, "S") elif action[0] == "move": self.renderActionChar(loc, "M") self.renderActionArrow(loc, action[1], self.move_arrow_color) else: self.renderActionChar(loc, "A") self.renderActionArrow(loc, action[1], self.attack_arrow_color) def renderText(self, loc, text): coordinates = self.getSquareCoordinates(loc) center = mid(coordinates[0], coordinates[1]) x, y = mid(center, coordinates[0]) textobj = self.canvas.create_text(x, y, text=text) self.actions[loc].append(textobj)
rgsimulatorUI.py
import Tkinter import tkFont def mid(l1, l2): return (int((l1[0]+l2[0]) / 2), int((l1[1]+l2[1]) / 2)) class SimulatorUI: def __init__(self, settings): self.settings = settings self.square_size = 40 self.border_width = 1 self.padding = 0 self.arrow_width = 3 self.selection_border_width = 5 self.fill_color = "#FFF" self.obstacle_fill_color = "#555" self.bot_fill_color = ["#57C", "#C75"] self.border_color = "#333" self.selection_border_color = "#FF0" self.move_arrow_color = "#00F" self.attack_arrow_color = "#000" self.map_width = self.settings.board_size self.map_height = self.settings.board_size self.width = self.square_size*self.map_width self.height = self.square_size*self.map_height self.root = Tkinter.Tk() self.root.resizable(0, 0) self.setTitle("Robot Game") self.turn_label = Tkinter.Label(self.root, text = "") self.turn_label.pack() self.setTurn(1) self.canvas = Tkinter.Canvas(self.root, width = self.width, height = self.height) self.canvas.pack() self.squares = {} self.labels = {} self.actions = {} for x in xrange(0, self.map_width): for y in xrange(0, self.map_height): coordinates = self.getSquareCoordinates((x, y)) x1, y1 = coordinates[0] x2, y2 = coordinates[1] self.squares[(x, y)] = self.canvas.create_rectangle( x1, y1, x2, y2, fill = self.obstacle_fill_color if (x, y) in self.settings['obstacles'] else self.fill_color, outline = self.border_color, width = self.border_width ) self.labels[(x, y)] = self.canvas.create_text( x1 + self.square_size/2, y1 + self.square_size/2, text = (x+1)*(y+1)-1 if x*y == 0 else "", font = "TkFixedFont", fill = "#000" ) self.actions[(x, y)] = [] self.center = (int(self.map_width/2), int(self.map_height/2)) self.selection = self.center selection_coordinates = self.getSquareCoordinates(self.selection) selection_x1, selection_y1 = selection_coordinates[0] selection_x2, selection_y2 = selection_coordinates[1] self.selection_square = self.canvas.create_rectangle( selection_x1, selection_y1, selection_x2, selection_y2, fill = "", outline = self.selection_border_color, width = self.selection_border_width ) # I am a dirty hack, fix me text_font = tkFont.nametofont("TkTextFont") text_font.configure(weight = "bold") def run(self): self.root.mainloop() def bind(self, event, hook): self.root.bind(event, hook) def onMouseClick(self, event): self.setSelection(self.getSquareByCoordinates(event.x, event.y)) def getSquareCoordinates(self, loc): x, y = loc return ( (self.square_size*x + self.padding/2, self.square_size*y + self.padding/2), (self.square_size*(x + 1) - self.padding/2, self.square_size*(y + 1) - self.padding/2) ) def getSquareByCoordinates(self, x, y): return (x/self.square_size, y/self.square_size) def hideSelection(self): self.canvas.itemconfigure(self.selection_square, width = 0) def showSelection(self): self.canvas.itemconfigure(self.selection_square, width = self.selection_border_width) def setSelection(self, loc): if loc not in self.settings['obstacles']: selection_coordinates = self.getSquareCoordinates(loc) selection_x1, selection_y1 = selection_coordinates[0] selection_x2, selection_y2 = selection_coordinates[1] self.canvas.coords(self.selection_square, selection_x1, selection_y1, selection_x2, selection_y2) self.selection = loc def moveSelection(self, dloc): self.setSelection((self.selection[0] + dloc[0], self.selection[1] + dloc[1])) def setTitle(self, title): self.root.title(title) def setTurn(self, turn): self.turn_label.config(text = "Turn %s" % turn) def setFill(self, loc, color): self.canvas.itemconfigure(self.squares[loc], fill = color) def setText(self, loc, text): self.canvas.itemconfigure(self.labels[loc], text = text) def renderEmpty(self, loc): self.setText(loc, "") self.setFill(loc, self.obstacle_fill_color if loc in self.settings['obstacles'] else self.fill_color) def clearBots(self): for x in xrange(1, self.map_width): for y in xrange(1, self.map_height): self.renderEmpty((x, y)) def renderBot(self, loc, hp, player_id): self.setText(loc, hp) self.setFill(loc, self.bot_fill_color[player_id]) def clearAction(self, loc): for action in self.actions[loc]: self.canvas.delete(action) self.actions[loc] = [] def clearActions(self): for loc in self.actions: self.clearAction(loc) def fadeAction(self, loc): for action in self.actions[loc]: if self.canvas.type(action) == "text": old_text = self.canvas.itemcget(action, "text") new_text = old_text.strip("()") new_text = "("+new_text+")" self.canvas.itemconfig(action, fill="#CCC", text=new_text) else: self.canvas.itemconfig(action, fill="#CCC") def fadeActions(self): for loc in self.actions: self.fadeAction(loc) def renderActionChar(self, loc, char): coordinates = self.getSquareCoordinates(loc) center_coordinates = mid(coordinates[0], coordinates[1]) char_coordinates = mid(center_coordinates, coordinates[1]) x, y = char_coordinates action_char = self.canvas.create_text( x, y, text = char, font = "TkTextFont", fill = "#000" ) self.actions[loc].append(action_char) def renderActionArrow(self, loc, loc2, color): coordinates1 = self.getSquareCoordinates(loc) center_coordinates1 = mid(coordinates1[0], coordinates1[1]) coordinates2 = self.getSquareCoordinates(loc2) center_coordinates2 = mid(coordinates2[0], coordinates2[1]) mid_coordinates = mid(center_coordinates1, center_coordinates2) x1, y1 = mid(center_coordinates1, mid_coordinates) x2, y2 = mid(center_coordinates2, mid_coordinates) arrow = self.canvas.create_line(x1, y1, x2, y2, fill = color, width = self.arrow_width, arrow = Tkinter.LAST) self.actions[loc].append(arrow) def renderAction(self, loc, action): if action[0] == "guard": self.renderActionChar(loc, "G") elif action[0] == "suicide": self.renderActionChar(loc, "S") elif action[0] == "move": self.renderActionChar(loc, "M") self.renderActionArrow(loc, action[1], self.move_arrow_color) else: self.renderActionChar(loc, "A") self.renderActionArrow(loc, action[1], self.attack_arrow_color) def renderText(self, loc, text): coordinates = self.getSquareCoordinates(loc) center = mid(coordinates[0], coordinates[1]) x, y = mid(center, coordinates[0]) textobj = self.canvas.create_text(x, y, text=text) self.actions[loc].append(textobj)
0.486332
0.296311
"""Resource for Transaction endpoints.""" from http import HTTPStatus from flask import Response, current_app, jsonify, request from flask_restplus import Namespace, Resource, cors from pay_api.exceptions import BusinessException from pay_api.schemas import utils as schema_utils from pay_api.services import ReceiptService from pay_api.utils.auth import jwt as _jwt from pay_api.utils.util import cors_preflight API = Namespace('invoice-receipts', description='Payment System - Receipts') @cors_preflight('POST') @API.route('/receipts', methods=['POST', 'OPTIONS']) @API.route('/invoices/<int:invoice_id>/receipts', methods=['POST', 'OPTIONS']) class InvoiceReceipt(Resource): """Endpoint resource to create receipt.Use this endpoint when no invoice number is available.""" @staticmethod @cors.crossdomain(origin='*') @_jwt.requires_auth def post(payment_id, invoice_id=''): """Create the Receipt for the Payment.""" request_json = request.get_json() current_app.logger.info('<Receipt.post') try: valid_format, errors = schema_utils.validate(request_json, 'payment_receipt_input') if not valid_format: return jsonify({'code': 'PAY999', 'message': schema_utils.serialize(errors)}), HTTPStatus.BAD_REQUEST pdf = ReceiptService.create_receipt(payment_id, invoice_id, request_json, _jwt) current_app.logger.info('<InvoiceReceipt received pdf') response = Response(pdf, 201) file_name = request_json.get('fileName') file_name = 'Coops-Filing' if not file_name else file_name response.headers.set('Content-Disposition', 'attachment', filename='{}.pdf'.format(file_name)) response.headers.set('Content-Type', 'application/pdf') return response except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status current_app.logger.debug('>Transaction.post') return jsonify(response), status
pay-api/src/pay_api/resources/invoice_receipt.py
"""Resource for Transaction endpoints.""" from http import HTTPStatus from flask import Response, current_app, jsonify, request from flask_restplus import Namespace, Resource, cors from pay_api.exceptions import BusinessException from pay_api.schemas import utils as schema_utils from pay_api.services import ReceiptService from pay_api.utils.auth import jwt as _jwt from pay_api.utils.util import cors_preflight API = Namespace('invoice-receipts', description='Payment System - Receipts') @cors_preflight('POST') @API.route('/receipts', methods=['POST', 'OPTIONS']) @API.route('/invoices/<int:invoice_id>/receipts', methods=['POST', 'OPTIONS']) class InvoiceReceipt(Resource): """Endpoint resource to create receipt.Use this endpoint when no invoice number is available.""" @staticmethod @cors.crossdomain(origin='*') @_jwt.requires_auth def post(payment_id, invoice_id=''): """Create the Receipt for the Payment.""" request_json = request.get_json() current_app.logger.info('<Receipt.post') try: valid_format, errors = schema_utils.validate(request_json, 'payment_receipt_input') if not valid_format: return jsonify({'code': 'PAY999', 'message': schema_utils.serialize(errors)}), HTTPStatus.BAD_REQUEST pdf = ReceiptService.create_receipt(payment_id, invoice_id, request_json, _jwt) current_app.logger.info('<InvoiceReceipt received pdf') response = Response(pdf, 201) file_name = request_json.get('fileName') file_name = 'Coops-Filing' if not file_name else file_name response.headers.set('Content-Disposition', 'attachment', filename='{}.pdf'.format(file_name)) response.headers.set('Content-Type', 'application/pdf') return response except BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status current_app.logger.debug('>Transaction.post') return jsonify(response), status
0.68941
0.08819
if __name__ == "__main__": from psana.pscalib.geometry.SegGeometryMatrixV1 import * import sys from time import time import psana.pyalgos.generic.Graphics as gg logging.basicConfig(format='[%(levelname).1s] L%(lineno)04d: %(message)s', level=logging.DEBUG) def test_xyz_min_max(): w = segment_one w.print_xyz_min_max_um() s = 'test_xyz_min_max'\ + '\n Ymin = %.1f' % w.pixel_coord_min('Y')\ + '\n Ymax = %.1f' % w.pixel_coord_max('Y') logger.info(s) def test_xyz_maps(): w = segment_one w.print_maps_seg_um() titles = ['X map','Y map'] for i,arr2d in enumerate( w.get_seg_xy_maps_pix() ): amp_range = (arr2d.min(), arr2d.max()) gg.plotImageLarge(arr2d, amp_range=amp_range, figsize=(10,9), title=titles[i]) gg.move(200*i,100*i) gg.show() def test_img(): w = segment_one X,Y = w.get_seg_xy_maps_pix() w.print_seg_info(0o377) xmin, ymin, zmin = w.get_xyz_min_um() xmax, ymax, zmax = w.get_xyz_max_um() xmin /= w.pixel_scale_size() xmax /= w.pixel_scale_size() ymin /= w.pixel_scale_size() ymax /= w.pixel_scale_size() xsize = int(xmax - xmin + 1) ysize = int(ymax - ymin + 1) H, Xedges, Yedges = np.histogram2d(X.flatten(), Y.flatten(), bins=[xsize,ysize],\ range=[[xmin, xmax], [ymin, ymax]], normed=False, weights=X.flatten()+Y.flatten()) s = 'test_img'\ + '\n X.shape:' + str(X.shape)\ + '\n xsize = %.1f' % xsize\ + '\n ysize = %.1f' % ysize\ + '\n Xedges:' + str(Xedges)\ + '\n Yedges:' + str(Yedges)\ + '\n H.shape:' + str(H.shape) logger.info(s) gg.plotImageLarge(H, amp_range=(0, 1100), figsize=(11,10)) # range=(-1, 2), gg.show() def test_img_easy(): o = segment_one X, Y = o.get_seg_xy_maps_pix() xmin, xmax, ymin, ymax = X.min(), X.max(), Y.min(), Y.max() Xoff, Yoff = X-xmin, Y-ymin iX, iY = (Xoff+0.25).astype(int), (Yoff+0.25).astype(int) img = gg.getImageFromIndexArrays(iY,iX,X+2*Y) gg.plotImageLarge(img, amp_range=(xmin+2*ymin, xmax+2*ymax), figsize=(11,10)) gg.show() def test_pix_sizes(): w = segment_one w.print_pixel_size_arrs() size_arr = w.pixel_size_array('X') area_arr = w.pixel_area_array() s = 'test_pix_sizes\n'\ + '\n area_arr[0:10,190:198]:\n' + str(area_arr[0:10,190:198])\ + '\n area_arr.shape:' + str(area_arr.shape)\ + '\n size_arr[0:10,190:198]:\n' + str(size_arr[0:10,190:198])\ + '\n size_arr.shape:' + str(size_arr.shape) logger.info(s) def test_mask(width=0, edge_rows=5, edge_cols=5): o = segment_one X, Y = o.get_seg_xy_maps_pix_with_offset() mask = 1 + o.pixel_mask_array(width=width, edge_rows=edge_rows, edge_cols=edge_cols) iX, iY = (X+0.25).astype(int), (Y+0.25).astype(int) img = gg.getImageFromIndexArrays(iX,iY,mask) gg.plotImageLarge(img, amp_range=(0,2), figsize=(11,10)) gg.show() def usage(tname='0'): s = '' if tname in ('0',): s+='\n==== Usage: python %s <test-number>' % sys.argv[0] if tname in ('0','1'): s+='\n 1 - test_xyz_min_max()' if tname in ('0','2'): s+='\n 2 - test_xyz_maps()' if tname in ('0','3'): s+='\n 3 - test_img()' if tname in ('0','4'): s+='\n 4 - test_img_easy()' if tname in ('0','5'): s+='\n 5 - test_pix_sizes()' if tname in ('0','6'): s+='\n 6 - test_mask(width=5)' if tname in ('0','7'): s+='\n 7 - test_mask(edge_rows=5, edge_cols=10)' return s if __name__ == "__main__": logging.getLogger('matplotlib').setLevel(logging.WARNING) tname = sys.argv[1] if len(sys.argv) > 1 else '0' if len(sys.argv)==1: logger.info(usage()) elif tname=='1': test_xyz_min_max() elif tname=='2': test_xyz_maps() elif tname=='3': test_img() elif tname=='4': test_img_easy() elif tname=='5': test_pix_sizes() elif tname=='6': test_mask(width=5) elif tname=='7': test_mask(width=0, edge_rows=5, edge_cols=10) else: logger.warning('NON-EXPECTED TEST NAME: %s\n\n%s' % (tname, usage())) if len(sys.argv)>1: logger.info(usage(tname)) sys.exit('END OF TEST') # EOF
psana/psana/pscalib/geometry/test_SegGeometryMatrixV1.py
if __name__ == "__main__": from psana.pscalib.geometry.SegGeometryMatrixV1 import * import sys from time import time import psana.pyalgos.generic.Graphics as gg logging.basicConfig(format='[%(levelname).1s] L%(lineno)04d: %(message)s', level=logging.DEBUG) def test_xyz_min_max(): w = segment_one w.print_xyz_min_max_um() s = 'test_xyz_min_max'\ + '\n Ymin = %.1f' % w.pixel_coord_min('Y')\ + '\n Ymax = %.1f' % w.pixel_coord_max('Y') logger.info(s) def test_xyz_maps(): w = segment_one w.print_maps_seg_um() titles = ['X map','Y map'] for i,arr2d in enumerate( w.get_seg_xy_maps_pix() ): amp_range = (arr2d.min(), arr2d.max()) gg.plotImageLarge(arr2d, amp_range=amp_range, figsize=(10,9), title=titles[i]) gg.move(200*i,100*i) gg.show() def test_img(): w = segment_one X,Y = w.get_seg_xy_maps_pix() w.print_seg_info(0o377) xmin, ymin, zmin = w.get_xyz_min_um() xmax, ymax, zmax = w.get_xyz_max_um() xmin /= w.pixel_scale_size() xmax /= w.pixel_scale_size() ymin /= w.pixel_scale_size() ymax /= w.pixel_scale_size() xsize = int(xmax - xmin + 1) ysize = int(ymax - ymin + 1) H, Xedges, Yedges = np.histogram2d(X.flatten(), Y.flatten(), bins=[xsize,ysize],\ range=[[xmin, xmax], [ymin, ymax]], normed=False, weights=X.flatten()+Y.flatten()) s = 'test_img'\ + '\n X.shape:' + str(X.shape)\ + '\n xsize = %.1f' % xsize\ + '\n ysize = %.1f' % ysize\ + '\n Xedges:' + str(Xedges)\ + '\n Yedges:' + str(Yedges)\ + '\n H.shape:' + str(H.shape) logger.info(s) gg.plotImageLarge(H, amp_range=(0, 1100), figsize=(11,10)) # range=(-1, 2), gg.show() def test_img_easy(): o = segment_one X, Y = o.get_seg_xy_maps_pix() xmin, xmax, ymin, ymax = X.min(), X.max(), Y.min(), Y.max() Xoff, Yoff = X-xmin, Y-ymin iX, iY = (Xoff+0.25).astype(int), (Yoff+0.25).astype(int) img = gg.getImageFromIndexArrays(iY,iX,X+2*Y) gg.plotImageLarge(img, amp_range=(xmin+2*ymin, xmax+2*ymax), figsize=(11,10)) gg.show() def test_pix_sizes(): w = segment_one w.print_pixel_size_arrs() size_arr = w.pixel_size_array('X') area_arr = w.pixel_area_array() s = 'test_pix_sizes\n'\ + '\n area_arr[0:10,190:198]:\n' + str(area_arr[0:10,190:198])\ + '\n area_arr.shape:' + str(area_arr.shape)\ + '\n size_arr[0:10,190:198]:\n' + str(size_arr[0:10,190:198])\ + '\n size_arr.shape:' + str(size_arr.shape) logger.info(s) def test_mask(width=0, edge_rows=5, edge_cols=5): o = segment_one X, Y = o.get_seg_xy_maps_pix_with_offset() mask = 1 + o.pixel_mask_array(width=width, edge_rows=edge_rows, edge_cols=edge_cols) iX, iY = (X+0.25).astype(int), (Y+0.25).astype(int) img = gg.getImageFromIndexArrays(iX,iY,mask) gg.plotImageLarge(img, amp_range=(0,2), figsize=(11,10)) gg.show() def usage(tname='0'): s = '' if tname in ('0',): s+='\n==== Usage: python %s <test-number>' % sys.argv[0] if tname in ('0','1'): s+='\n 1 - test_xyz_min_max()' if tname in ('0','2'): s+='\n 2 - test_xyz_maps()' if tname in ('0','3'): s+='\n 3 - test_img()' if tname in ('0','4'): s+='\n 4 - test_img_easy()' if tname in ('0','5'): s+='\n 5 - test_pix_sizes()' if tname in ('0','6'): s+='\n 6 - test_mask(width=5)' if tname in ('0','7'): s+='\n 7 - test_mask(edge_rows=5, edge_cols=10)' return s if __name__ == "__main__": logging.getLogger('matplotlib').setLevel(logging.WARNING) tname = sys.argv[1] if len(sys.argv) > 1 else '0' if len(sys.argv)==1: logger.info(usage()) elif tname=='1': test_xyz_min_max() elif tname=='2': test_xyz_maps() elif tname=='3': test_img() elif tname=='4': test_img_easy() elif tname=='5': test_pix_sizes() elif tname=='6': test_mask(width=5) elif tname=='7': test_mask(width=0, edge_rows=5, edge_cols=10) else: logger.warning('NON-EXPECTED TEST NAME: %s\n\n%s' % (tname, usage())) if len(sys.argv)>1: logger.info(usage(tname)) sys.exit('END OF TEST') # EOF
0.152916
0.239527
import pytest from ceph_deploy.cli import get_parser from ceph_deploy.tests.util import assert_too_few_arguments class TestParserPkg(object): def setup(self): self.parser = get_parser() def test_pkg_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --help'.split()) out, err = capsys.readouterr() assert 'usage: ceph-deploy pkg' in out assert 'positional arguments:' in out assert 'optional arguments:' in out def test_pkg_install_host_required(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --install pkg1'.split()) out, err = capsys.readouterr() assert_too_few_arguments(err) def test_pkg_install_one_host(self): args = self.parser.parse_args('pkg --install pkg1 host1'.split()) assert args.hosts == ['host1'] assert args.install == "pkg1" def test_pkg_install_multiple_hosts(self): hostnames = ['host1', 'host2', 'host3'] args = self.parser.parse_args('pkg --install pkg1'.split() + hostnames) assert args.hosts == hostnames assert args.install == "pkg1" def test_pkg_install_muliple_pkgs(self): args = self.parser.parse_args('pkg --install pkg1,pkg2 host1'.split()) assert args.install == "pkg1,pkg2" def test_pkg_remove_host_required(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --remove pkg1'.split()) out, err = capsys.readouterr() assert_too_few_arguments(err) def test_pkg_remove_one_host(self): args = self.parser.parse_args('pkg --remove pkg1 host1'.split()) assert args.hosts == ['host1'] assert args.remove == "pkg1" def test_pkg_remove_multiple_hosts(self): hostnames = ['host1', 'host2', 'host3'] args = self.parser.parse_args('pkg --remove pkg1'.split() + hostnames) assert args.hosts == hostnames assert args.remove == "pkg1" def test_pkg_remove_muliple_pkgs(self): args = self.parser.parse_args('pkg --remove pkg1,pkg2 host1'.split()) assert args.remove == "pkg1,pkg2" def test_pkg_install_remove_are_mutex(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --install pkg2 --remove pkg1 host1'.split()) out, err = capsys.readouterr() assert "argument --remove: not allowed with argument --install" in err
ceph_deploy/tests/parser/test_pkg.py
import pytest from ceph_deploy.cli import get_parser from ceph_deploy.tests.util import assert_too_few_arguments class TestParserPkg(object): def setup(self): self.parser = get_parser() def test_pkg_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --help'.split()) out, err = capsys.readouterr() assert 'usage: ceph-deploy pkg' in out assert 'positional arguments:' in out assert 'optional arguments:' in out def test_pkg_install_host_required(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --install pkg1'.split()) out, err = capsys.readouterr() assert_too_few_arguments(err) def test_pkg_install_one_host(self): args = self.parser.parse_args('pkg --install pkg1 host1'.split()) assert args.hosts == ['host1'] assert args.install == "pkg1" def test_pkg_install_multiple_hosts(self): hostnames = ['host1', 'host2', 'host3'] args = self.parser.parse_args('pkg --install pkg1'.split() + hostnames) assert args.hosts == hostnames assert args.install == "pkg1" def test_pkg_install_muliple_pkgs(self): args = self.parser.parse_args('pkg --install pkg1,pkg2 host1'.split()) assert args.install == "pkg1,pkg2" def test_pkg_remove_host_required(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --remove pkg1'.split()) out, err = capsys.readouterr() assert_too_few_arguments(err) def test_pkg_remove_one_host(self): args = self.parser.parse_args('pkg --remove pkg1 host1'.split()) assert args.hosts == ['host1'] assert args.remove == "pkg1" def test_pkg_remove_multiple_hosts(self): hostnames = ['host1', 'host2', 'host3'] args = self.parser.parse_args('pkg --remove pkg1'.split() + hostnames) assert args.hosts == hostnames assert args.remove == "pkg1" def test_pkg_remove_muliple_pkgs(self): args = self.parser.parse_args('pkg --remove pkg1,pkg2 host1'.split()) assert args.remove == "pkg1,pkg2" def test_pkg_install_remove_are_mutex(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('pkg --install pkg2 --remove pkg1 host1'.split()) out, err = capsys.readouterr() assert "argument --remove: not allowed with argument --install" in err
0.355104
0.429728
class GenomeBuilder: def __init__(self, time_scale, time_per_task, min_task_time): """ A class used to generate a Genome object.""" self.time_scale = time_scale self.total_minutes = self.get_total_minutes() if self.validate_minimum_task_time(min_task_time): self.min_task_time = min_task_time if self.validate_task_times(time_per_task): self.time_per_task = time_per_task self.tasks = list(self.time_per_task.keys()) self.set_num_time_slots() self.set_genes_per_task() def get_total_minutes(self): """ Returns the number of minutes based on the time_scale.""" if self.time_scale == "daily": minutes = 24 * 60 # minutes in a day elif self.time_scale == "weekly": minutes = 7 * 24 * 60 elif self.time_scale == "biweekly": minutes = 14 * 24 * 60 return minutes def validate_minimum_task_time(self, min_task_time): """ Returns true if the minimum task time is valid. A valid minimum task time evenly divides into a day's worth of minutes. Also a valid minimum task time shall not exceed one day. A minimum task time is the minimum amount of consecutive time we wish to spend on a task.""" if min_task_time <= 24 * 60 and (24 * 60) % min_task_time == 0: return True else: msg = "min time task evenly divide 60 if less than or equal to 60 \ or evenly divide (24*60) if less than 24*60" print(msg) return False def validate_task_times(self, task_times): """ Returns True if the task times are valid. A valid task time is one that is evenly divisible by the minimum task time. """ total = 0 for task in task_times: if task_times[task] % self.min_task_time != 0: msg = "min time task evenly divide 60 if less than or equal to 60 \ or evenly divide (24*60) if less than 24*60" print(msg) return False total += task_times[task] return total <= self.total_minutes def set_num_time_slots(self): """ Calculates and returns the number of time slots. The number of time slots is determined by the time_scale, which is daily, weekly, or biweekly. In addition to the time_scale, the number of time slots is also determined by the minimum_time_per_task, which is an integer that represents the minimum number of minutes that we are to schedule a task for. """ self.n_alleles = self.total_minutes // self.min_task_time def set_genes_per_task(self): """ Converts time_per_task values which are in minutes, to # genes.""" self.genes = {} for task in self.tasks: self.genes[task] = self.time_per_task[task] // self.min_task_time def get_genome(self): """ Uses the data collected to produce a Genome.""" from .genome import Genome return Genome(self.time_scale, self.tasks, self.genes, self.n_alleles, self.min_task_time)
evoschedule/app/genome_builder.py
class GenomeBuilder: def __init__(self, time_scale, time_per_task, min_task_time): """ A class used to generate a Genome object.""" self.time_scale = time_scale self.total_minutes = self.get_total_minutes() if self.validate_minimum_task_time(min_task_time): self.min_task_time = min_task_time if self.validate_task_times(time_per_task): self.time_per_task = time_per_task self.tasks = list(self.time_per_task.keys()) self.set_num_time_slots() self.set_genes_per_task() def get_total_minutes(self): """ Returns the number of minutes based on the time_scale.""" if self.time_scale == "daily": minutes = 24 * 60 # minutes in a day elif self.time_scale == "weekly": minutes = 7 * 24 * 60 elif self.time_scale == "biweekly": minutes = 14 * 24 * 60 return minutes def validate_minimum_task_time(self, min_task_time): """ Returns true if the minimum task time is valid. A valid minimum task time evenly divides into a day's worth of minutes. Also a valid minimum task time shall not exceed one day. A minimum task time is the minimum amount of consecutive time we wish to spend on a task.""" if min_task_time <= 24 * 60 and (24 * 60) % min_task_time == 0: return True else: msg = "min time task evenly divide 60 if less than or equal to 60 \ or evenly divide (24*60) if less than 24*60" print(msg) return False def validate_task_times(self, task_times): """ Returns True if the task times are valid. A valid task time is one that is evenly divisible by the minimum task time. """ total = 0 for task in task_times: if task_times[task] % self.min_task_time != 0: msg = "min time task evenly divide 60 if less than or equal to 60 \ or evenly divide (24*60) if less than 24*60" print(msg) return False total += task_times[task] return total <= self.total_minutes def set_num_time_slots(self): """ Calculates and returns the number of time slots. The number of time slots is determined by the time_scale, which is daily, weekly, or biweekly. In addition to the time_scale, the number of time slots is also determined by the minimum_time_per_task, which is an integer that represents the minimum number of minutes that we are to schedule a task for. """ self.n_alleles = self.total_minutes // self.min_task_time def set_genes_per_task(self): """ Converts time_per_task values which are in minutes, to # genes.""" self.genes = {} for task in self.tasks: self.genes[task] = self.time_per_task[task] // self.min_task_time def get_genome(self): """ Uses the data collected to produce a Genome.""" from .genome import Genome return Genome(self.time_scale, self.tasks, self.genes, self.n_alleles, self.min_task_time)
0.921118
0.379551
from __future__ import absolute_import from __future__ import division from __future__ import print_function import oneflow as flow def add_ofrecord_args(parser): parser.add_argument("--image_size", type=int, default=224, required=False, help="image size") parser.add_argument("--resize_shorter", type=int, default=256, required=False, help="resize shorter for validation") parser.add_argument("--train_data_dir", type=str, default=None, help="train dataset directory") parser.add_argument("--train_data_part_num", type=int, default=256, help="train data part num") parser.add_argument("--val_data_dir", type=str, default=None, help="val dataset directory") parser.add_argument("--val_data_part_num", type=int, default=256, help="val data part num") return parser #old version, cancelled def load_imagenet(args, batch_size, data_dir, data_part_num, codec): image_blob_conf = flow.data.BlobConf( "encoded", shape=(args.image_size, args.image_size, 3), dtype=flow.float, codec=codec, preprocessors=[flow.data.NormByChannelPreprocessor(args.rgb_mean[::-1], args.rgb_std[::-1])], # preprocessors=[flow.data.NormByChannelPreprocessor(args.rgb_mean, args.rgb_std)], #bgr2rgb ) label_blob_conf = flow.data.BlobConf( "class/label", shape=(), dtype=flow.int32, codec=flow.data.RawCodec() ) return flow.data.decode_ofrecord( data_dir, (label_blob_conf, image_blob_conf), batch_size=batch_size, data_part_num=data_part_num, part_name_suffix_length=5, #shuffle = True, # buffer_size=32768, name="decode") #old version, cancelled def load_cifar10(data_dir, batch_size, data_part_num, image_size=32): image_blob_conf = flow.data.BlobConf( "images", shape=(image_size, image_size, 3), dtype=flow.float, codec=flow.data.RawCodec(), preprocessors=[flow.data.NormByChannelPreprocessor((125.31, 122.96, 113.86), (61.252, 60.767, 65.852))], ) label_blob_conf = flow.data.BlobConf("labels", shape=(), dtype=flow.int32, codec=flow.data.RawCodec()) return flow.data.decode_ofrecord( data_dir, (label_blob_conf, image_blob_conf), batch_size=batch_size, data_part_num=data_part_num, name="decode", ) def load_synthetic(args): total_device_num = args.num_nodes * args.gpu_num_per_node batch_size = total_device_num * args.batch_size_per_device label = flow.data.decode_random( shape=(), dtype=flow.int32, batch_size=batch_size, initializer=flow.zeros_initializer(flow.int32), ) image = flow.data.decode_random( shape=(args.image_size, args.image_size, 3), dtype=flow.float, batch_size=batch_size ) return label, image def load_imagenet_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) image = flow.data.OFRecordImageDecoderRandomCrop(ofrecord, "encoded", # seed=seed, color_space=color_space) label = flow.data.OFRecordRawDecoder(ofrecord, "class/label", shape=(), dtype=flow.int32) rsz = flow.image.Resize(image, resize_x=args.image_size, resize_y=args.image_size, color_space=color_space) rng = flow.random.CoinFlip(batch_size=train_batch_size) # , seed=seed) normal = flow.image.CropMirrorNormalize(rsz, mirror_blob=rng, color_space=color_space, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_imagenet_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) image = flow.data.OFRecordImageDecoder(ofrecord, "encoded", color_space=color_space) label = flow.data.OFRecordRawDecoder(ofrecord, "class/label", shape=(), dtype=flow.int32) rsz = flow.image.Resize(image, resize_shorter=args.resize_shorter, color_space=color_space) normal = flow.image.CropMirrorNormalize(rsz, color_space=color_space, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_cifar_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_cifar_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_mnist_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(1, args.image_size, args.image_size), dtype=flow.float) # print(image.shape) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, color_space="GRAY", mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_mnist_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(1, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, color_space="GRAY", mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_svhn_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(args.image_size, args.image_size, 3), dtype=flow.float) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_svhn_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(args.image_size, args.image_size, 3), dtype=flow.float) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_mydata_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_mydata_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal if __name__ == "__main__": import os import config as configs from util import Summary, Metric from job_function_util import get_val_config parser = configs.get_parser() args = parser.parse_args() configs.print_args(args) flow.config.gpu_device_num(args.gpu_num_per_node) flow.config.enable_debug_mode(True) @flow.global_function(get_val_config(args)) def IOTest(): if args.train_data_dir: assert os.path.exists(args.train_data_dir) print("Loading data from {}".format(args.train_data_dir)) (labels, images) = load_imagenet_for_training(args) else: print("Loading synthetic data.") (labels, images) = load_synthetic(args) outputs = {"images": images, "labels": labels} return outputs total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device summary = Summary(args.log_dir, args, filename='io_test.csv') metric = Metric(desc='io_test', calculate_batches=args.loss_print_every_n_iter, summary=summary, save_summary_steps=args.loss_print_every_n_iter, batch_size=train_batch_size, prediction_key=None) for i in range(1000): IOTest().async_get(metric.metric_cb(0, i))
model_compress/ChannelSlimming/util/ofrecord_util.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import oneflow as flow def add_ofrecord_args(parser): parser.add_argument("--image_size", type=int, default=224, required=False, help="image size") parser.add_argument("--resize_shorter", type=int, default=256, required=False, help="resize shorter for validation") parser.add_argument("--train_data_dir", type=str, default=None, help="train dataset directory") parser.add_argument("--train_data_part_num", type=int, default=256, help="train data part num") parser.add_argument("--val_data_dir", type=str, default=None, help="val dataset directory") parser.add_argument("--val_data_part_num", type=int, default=256, help="val data part num") return parser #old version, cancelled def load_imagenet(args, batch_size, data_dir, data_part_num, codec): image_blob_conf = flow.data.BlobConf( "encoded", shape=(args.image_size, args.image_size, 3), dtype=flow.float, codec=codec, preprocessors=[flow.data.NormByChannelPreprocessor(args.rgb_mean[::-1], args.rgb_std[::-1])], # preprocessors=[flow.data.NormByChannelPreprocessor(args.rgb_mean, args.rgb_std)], #bgr2rgb ) label_blob_conf = flow.data.BlobConf( "class/label", shape=(), dtype=flow.int32, codec=flow.data.RawCodec() ) return flow.data.decode_ofrecord( data_dir, (label_blob_conf, image_blob_conf), batch_size=batch_size, data_part_num=data_part_num, part_name_suffix_length=5, #shuffle = True, # buffer_size=32768, name="decode") #old version, cancelled def load_cifar10(data_dir, batch_size, data_part_num, image_size=32): image_blob_conf = flow.data.BlobConf( "images", shape=(image_size, image_size, 3), dtype=flow.float, codec=flow.data.RawCodec(), preprocessors=[flow.data.NormByChannelPreprocessor((125.31, 122.96, 113.86), (61.252, 60.767, 65.852))], ) label_blob_conf = flow.data.BlobConf("labels", shape=(), dtype=flow.int32, codec=flow.data.RawCodec()) return flow.data.decode_ofrecord( data_dir, (label_blob_conf, image_blob_conf), batch_size=batch_size, data_part_num=data_part_num, name="decode", ) def load_synthetic(args): total_device_num = args.num_nodes * args.gpu_num_per_node batch_size = total_device_num * args.batch_size_per_device label = flow.data.decode_random( shape=(), dtype=flow.int32, batch_size=batch_size, initializer=flow.zeros_initializer(flow.int32), ) image = flow.data.decode_random( shape=(args.image_size, args.image_size, 3), dtype=flow.float, batch_size=batch_size ) return label, image def load_imagenet_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) image = flow.data.OFRecordImageDecoderRandomCrop(ofrecord, "encoded", # seed=seed, color_space=color_space) label = flow.data.OFRecordRawDecoder(ofrecord, "class/label", shape=(), dtype=flow.int32) rsz = flow.image.Resize(image, resize_x=args.image_size, resize_y=args.image_size, color_space=color_space) rng = flow.random.CoinFlip(batch_size=train_batch_size) # , seed=seed) normal = flow.image.CropMirrorNormalize(rsz, mirror_blob=rng, color_space=color_space, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_imagenet_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) image = flow.data.OFRecordImageDecoder(ofrecord, "encoded", color_space=color_space) label = flow.data.OFRecordRawDecoder(ofrecord, "class/label", shape=(), dtype=flow.int32) rsz = flow.image.Resize(image, resize_shorter=args.resize_shorter, color_space=color_space) normal = flow.image.CropMirrorNormalize(rsz, color_space=color_space, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_cifar_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_cifar_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_mnist_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(1, args.image_size, args.image_size), dtype=flow.float) # print(image.shape) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, color_space="GRAY", mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_mnist_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(1, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, color_space="GRAY", mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_svhn_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(args.image_size, args.image_size, 3), dtype=flow.float) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_svhn_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(args.image_size, args.image_size, 3), dtype=flow.float) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal def load_mydata_for_training(args): total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.train_data_dir, batch_size=train_batch_size, data_part_num=args.train_data_part_num, part_name_suffix_length=5, random_shuffle=True, shuffle_after_epoch=True) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) rng = flow.random.CoinFlip(batch_size=train_batch_size) normal = flow.image.CropMirrorNormalize(image_uint8, mirror_blob=rng, mean=args.rgb_mean, std=args.rgb_std) return label, normal def load_mydata_for_validation(args): total_device_num = args.num_nodes * args.gpu_num_per_node val_batch_size = total_device_num * args.val_batch_size_per_device # color_space = 'RGB' ofrecord = flow.data.ofrecord_reader(args.val_data_dir, batch_size=val_batch_size, data_part_num=args.val_data_part_num, part_name_suffix_length=5, shuffle_after_epoch=False) label = flow.data.OFRecordRawDecoder(ofrecord, "labels", shape=(), dtype=flow.int32) image = flow.data.OFRecordRawDecoder(ofrecord, "images", shape=(3, args.image_size, args.image_size), dtype=flow.float) image = flow.transpose(image, perm=[0, 2, 3, 1]) image_uint8 = flow.cast(image, flow.uint8) normal = flow.image.CropMirrorNormalize(image_uint8, crop_h=args.image_size, crop_w=args.image_size, crop_pos_y=0.5, crop_pos_x=0.5, mean=args.rgb_mean, std=args.rgb_std, output_dtype=flow.float) return label, normal if __name__ == "__main__": import os import config as configs from util import Summary, Metric from job_function_util import get_val_config parser = configs.get_parser() args = parser.parse_args() configs.print_args(args) flow.config.gpu_device_num(args.gpu_num_per_node) flow.config.enable_debug_mode(True) @flow.global_function(get_val_config(args)) def IOTest(): if args.train_data_dir: assert os.path.exists(args.train_data_dir) print("Loading data from {}".format(args.train_data_dir)) (labels, images) = load_imagenet_for_training(args) else: print("Loading synthetic data.") (labels, images) = load_synthetic(args) outputs = {"images": images, "labels": labels} return outputs total_device_num = args.num_nodes * args.gpu_num_per_node train_batch_size = total_device_num * args.batch_size_per_device summary = Summary(args.log_dir, args, filename='io_test.csv') metric = Metric(desc='io_test', calculate_batches=args.loss_print_every_n_iter, summary=summary, save_summary_steps=args.loss_print_every_n_iter, batch_size=train_batch_size, prediction_key=None) for i in range(1000): IOTest().async_get(metric.metric_cb(0, i))
0.609292
0.134804
from django import template from django.core.urlresolvers import reverse from django.template import Token, Parser, TOKEN_BLOCK import fudge import random from .._utils import TestCase from ... import context_processors from ...templatetags.esi import EsiNode from ...templatetags.esi import esi def create_context(): request = fudge.Fake() context = template.Context() context.update(context_processors.esi(request)) return context def create_token(content): return Token(TOKEN_BLOCK, content) class TestOfEsiNode(TestCase): def test_renders_actual_code(self): context = create_context() node = esi(Parser([]), create_token('esi hello_world')) result = node.render(context) expected_url = reverse('hello_world') self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_renders_relative_esi(self): context = create_context() node = esi(Parser([]), create_token('esi ./blah/')) result = node.render(context) expected_url = './blah/' self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_renders_kwargs(self): context = create_context() number = random.randint(100, 200) node = esi(Parser([]), create_token('esi hello_number number=%s' % number)) result = node.render(context) expected_url = reverse('hello_number', kwargs={'number': number}) self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_sets_esi_used_to_true_on_context(self): context = create_context() node = EsiNode('hello_world', [], {}, None) node.render(context) self.assertTrue(context['_esi']['used']) class TestOfEsiHandler(TestCase): def test_extracts_view_out_of_templatetag_call(self): random_view_name = 'hello_world_%d' % random.randint(100, 200) token = fudge.Fake() token.expects('split_contents').returns(('esi', random_view_name)) fudge.clear_calls() result = esi(None, token) self.assertEquals(result.view_name, random_view_name) fudge.verify() def test_is_registered_as_a_templatetag_at_esi(self): library = template.get_library('esi') self.assert_('esi' in library.tags) self.assert_(library.tags['esi'] is esi) def test_can_be_rendered_from_a_template(self): raw_template = """ {% load esi %} {% esi hello_world %} """ t = template.Template(raw_template) context = create_context() result = t.render(context).strip() expected_url = reverse('hello_world') self.assertEquals(result, '<esi:include src="%s" />' % expected_url)
armstrong/esi/tests/templatetags/esi.py
from django import template from django.core.urlresolvers import reverse from django.template import Token, Parser, TOKEN_BLOCK import fudge import random from .._utils import TestCase from ... import context_processors from ...templatetags.esi import EsiNode from ...templatetags.esi import esi def create_context(): request = fudge.Fake() context = template.Context() context.update(context_processors.esi(request)) return context def create_token(content): return Token(TOKEN_BLOCK, content) class TestOfEsiNode(TestCase): def test_renders_actual_code(self): context = create_context() node = esi(Parser([]), create_token('esi hello_world')) result = node.render(context) expected_url = reverse('hello_world') self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_renders_relative_esi(self): context = create_context() node = esi(Parser([]), create_token('esi ./blah/')) result = node.render(context) expected_url = './blah/' self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_renders_kwargs(self): context = create_context() number = random.randint(100, 200) node = esi(Parser([]), create_token('esi hello_number number=%s' % number)) result = node.render(context) expected_url = reverse('hello_number', kwargs={'number': number}) self.assertEquals(result, '<esi:include src="%s" />' % expected_url) def test_sets_esi_used_to_true_on_context(self): context = create_context() node = EsiNode('hello_world', [], {}, None) node.render(context) self.assertTrue(context['_esi']['used']) class TestOfEsiHandler(TestCase): def test_extracts_view_out_of_templatetag_call(self): random_view_name = 'hello_world_%d' % random.randint(100, 200) token = fudge.Fake() token.expects('split_contents').returns(('esi', random_view_name)) fudge.clear_calls() result = esi(None, token) self.assertEquals(result.view_name, random_view_name) fudge.verify() def test_is_registered_as_a_templatetag_at_esi(self): library = template.get_library('esi') self.assert_('esi' in library.tags) self.assert_(library.tags['esi'] is esi) def test_can_be_rendered_from_a_template(self): raw_template = """ {% load esi %} {% esi hello_world %} """ t = template.Template(raw_template) context = create_context() result = t.render(context).strip() expected_url = reverse('hello_world') self.assertEquals(result, '<esi:include src="%s" />' % expected_url)
0.545044
0.259222
from vue import * def test_app_with_props_and_data(selenium): def app_with_props_data(el): class App(VueComponent): text: str template = """ <div id="el">{{ text }}</div> """ return App(el, props_data={"text": "TEXT"}) with selenium.app(app_with_props_data): assert selenium.element_has_text("el", "TEXT") def test_emit_method(selenium): def call_emit(el): class Emitter(VueComponent): template = "<p></p>" def created(self): self.emit("creation", "YES") Emitter.register() class App(VueComponent): text = "NO" template = """ <div> <emitter @creation="change"></emitter> <div id='el'>{{ text }}</div> </div> """ def change(self, ev=None): self.text = ev return App(el) with selenium.app(call_emit): assert selenium.element_has_text("el", "YES") def test_extend(selenium): def extended_component(el): class Base(VueComponent): template = "<div id='comps'>{{ components_string }}</div>" comps = [] def created(self): self.comps.append("BASE") @computed def components_string(self): return " ".join(self.comps) class Sub(Base): extends = True def created(self): self.comps.append("SUB") return Sub(el) with selenium.app(extended_component): assert selenium.element_has_text("comps", "BASE SUB") def test_extend_from_dict(selenium): class Component(VueComponent): template = "<div id='done'>{{ done }}</div>" done = "NO" extends = {"created": lambda: print("CREATED BASE")} def created(self): print("CREATED SUB") self.done = "YES" with selenium.app(Component): assert selenium.element_has_text("done", "YES") assert "CREATED BASE" in selenium.logs[-2]["message"] assert "CREATED SUB" in selenium.logs[-1]["message"]
tests/selenium/test_api.py
from vue import * def test_app_with_props_and_data(selenium): def app_with_props_data(el): class App(VueComponent): text: str template = """ <div id="el">{{ text }}</div> """ return App(el, props_data={"text": "TEXT"}) with selenium.app(app_with_props_data): assert selenium.element_has_text("el", "TEXT") def test_emit_method(selenium): def call_emit(el): class Emitter(VueComponent): template = "<p></p>" def created(self): self.emit("creation", "YES") Emitter.register() class App(VueComponent): text = "NO" template = """ <div> <emitter @creation="change"></emitter> <div id='el'>{{ text }}</div> </div> """ def change(self, ev=None): self.text = ev return App(el) with selenium.app(call_emit): assert selenium.element_has_text("el", "YES") def test_extend(selenium): def extended_component(el): class Base(VueComponent): template = "<div id='comps'>{{ components_string }}</div>" comps = [] def created(self): self.comps.append("BASE") @computed def components_string(self): return " ".join(self.comps) class Sub(Base): extends = True def created(self): self.comps.append("SUB") return Sub(el) with selenium.app(extended_component): assert selenium.element_has_text("comps", "BASE SUB") def test_extend_from_dict(selenium): class Component(VueComponent): template = "<div id='done'>{{ done }}</div>" done = "NO" extends = {"created": lambda: print("CREATED BASE")} def created(self): print("CREATED SUB") self.done = "YES" with selenium.app(Component): assert selenium.element_has_text("done", "YES") assert "CREATED BASE" in selenium.logs[-2]["message"] assert "CREATED SUB" in selenium.logs[-1]["message"]
0.538498
0.201518
from __future__ import unicode_literals import datetime import uuid from dagster import ExecutionTargetHandle from dagster.utils import script_relative_path # pylint: disable=unused-import from dagster_airflow.test_fixtures import ( dagster_airflow_docker_operator_pipeline, dagster_airflow_python_operator_pipeline, ) from dagster_airflow.factory import _rename_for_airflow, AIRFLOW_MAX_DAG_NAME_LEN from dagster_airflow_tests.conftest import IMAGE from dagster_airflow_tests.marks import nettest from dagster_airflow_tests.test_project.dagster_airflow_demo import define_demo_execution_pipeline class TestExecuteDagPythonFilesystemStorage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_filesystem.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() # pylint: disable=redefined-outer-name def test_execute_dag(self, dagster_airflow_python_operator_pipeline): for result in dagster_airflow_python_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue class TestExecuteDagPythonS3Storage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_s3.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() # pylint: disable=redefined-outer-name def test_execute_dag(self, dagster_airflow_python_operator_pipeline): for result in dagster_airflow_python_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue @nettest class TestExecuteDagContainerizedS3Storage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_s3.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() image = IMAGE # pylint: disable=redefined-outer-name def test_execute_dag_containerized(self, dagster_airflow_docker_operator_pipeline): for result in dagster_airflow_docker_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue class TestExecuteDagContainerizedFilesystemStorage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_filesystem.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() op_kwargs = {'host_tmp_dir': '/tmp'} image = IMAGE # pylint: disable=redefined-outer-name def test_execute_dag_containerized(self, dagster_airflow_docker_operator_pipeline): for result in dagster_airflow_docker_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue def test_rename_for_airflow(): pairs = [ ('foo', 'foo'), ('this-is-valid', 'this-is-valid'), ( 'a' * AIRFLOW_MAX_DAG_NAME_LEN + 'very long strings are disallowed', 'a' * AIRFLOW_MAX_DAG_NAME_LEN, ), ('a name with illegal spaces', 'a_name_with_illegal_spaces'), ('a#name$with@special*chars!!!', 'a_name_with_special_chars___'), ] for before, after in pairs: assert after == _rename_for_airflow(before)
python_modules/dagster-airflow/dagster_airflow_tests/test_factory.py
from __future__ import unicode_literals import datetime import uuid from dagster import ExecutionTargetHandle from dagster.utils import script_relative_path # pylint: disable=unused-import from dagster_airflow.test_fixtures import ( dagster_airflow_docker_operator_pipeline, dagster_airflow_python_operator_pipeline, ) from dagster_airflow.factory import _rename_for_airflow, AIRFLOW_MAX_DAG_NAME_LEN from dagster_airflow_tests.conftest import IMAGE from dagster_airflow_tests.marks import nettest from dagster_airflow_tests.test_project.dagster_airflow_demo import define_demo_execution_pipeline class TestExecuteDagPythonFilesystemStorage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_filesystem.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() # pylint: disable=redefined-outer-name def test_execute_dag(self, dagster_airflow_python_operator_pipeline): for result in dagster_airflow_python_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue class TestExecuteDagPythonS3Storage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_s3.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() # pylint: disable=redefined-outer-name def test_execute_dag(self, dagster_airflow_python_operator_pipeline): for result in dagster_airflow_python_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue @nettest class TestExecuteDagContainerizedS3Storage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_s3.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() image = IMAGE # pylint: disable=redefined-outer-name def test_execute_dag_containerized(self, dagster_airflow_docker_operator_pipeline): for result in dagster_airflow_docker_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue class TestExecuteDagContainerizedFilesystemStorage(object): handle = ExecutionTargetHandle.for_pipeline_fn(define_demo_execution_pipeline) pipeline_name = 'demo_pipeline' environment_yaml = [ script_relative_path('test_project/env.yaml'), script_relative_path('test_project/env_filesystem.yaml'), ] run_id = str(uuid.uuid4()) execution_date = datetime.datetime.utcnow() op_kwargs = {'host_tmp_dir': '/tmp'} image = IMAGE # pylint: disable=redefined-outer-name def test_execute_dag_containerized(self, dagster_airflow_docker_operator_pipeline): for result in dagster_airflow_docker_operator_pipeline: assert 'data' in result assert 'executePlan' in result['data'] assert '__typename' in result['data']['executePlan'] assert result['data']['executePlan']['__typename'] == 'ExecutePlanSuccess' result = list( filter( lambda x: x['__typename'] == 'ExecutionStepOutputEvent', result['data']['executePlan']['stepEvents'], ) )[0] if result['step']['kind'] == 'INPUT_THUNK': continue def test_rename_for_airflow(): pairs = [ ('foo', 'foo'), ('this-is-valid', 'this-is-valid'), ( 'a' * AIRFLOW_MAX_DAG_NAME_LEN + 'very long strings are disallowed', 'a' * AIRFLOW_MAX_DAG_NAME_LEN, ), ('a name with illegal spaces', 'a_name_with_illegal_spaces'), ('a#name$with@special*chars!!!', 'a_name_with_special_chars___'), ] for before, after in pairs: assert after == _rename_for_airflow(before)
0.430746
0.233553
import asyncio import traceback from nextcord.ext import commands import nextcord import os import sys from nextcord import Interaction, SlashOption, ChannelType from cogs.debug import save sys.path.append('../') from util import admin_check, n_fc, eh # join message system # Copilotでちょっとだけ楽をした。 #loggingの設定 import logging dir = sys.path[0] class NoTokenLogFilter(logging.Filter): def filter(self, record): message = record.getMessage() return 'token' not in message logger = logging.getLogger(__name__) logger.addFilter(NoTokenLogFilter()) formatter = '%(asctime)s$%(filename)s$%(lineno)d$%(funcName)s$%(levelname)s:%(message)s' logging.basicConfig(format=formatter, filename=f'{dir}/nira.log', level=logging.INFO) class welcome(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.command(name="welcome", aliases=("youkoso","goodbye","ようこそ","Welcome"), help="""\ ユーザーが加入/離脱したときに、特定のメッセージをこのチャンネルに送信するようにします。 書き方: `n!welcome [join/leave]` `[メッセージ]` (メッセージは複数行可能です。) メッセージ内には`%name%`/`%count%`/`%ment%`と入れることで、それぞれ`ユーザー名`/`ユーザー数`/`メンション`に置き換わります。 ・例 ``` n!welcome join %name%さんこんちゃ!!!!! ``` ``` n!welcome leave %name%さんばいばい!!! ``` メッセージの部分に`off`と入力すると、設定を削除します。 ・例 ``` n!welcome join off ``` ``` n!welcome leave off ``` """) async def welcome(self, ctx: commands.Context): if not admin_check.admin_check(ctx.guild, ctx.author): await ctx.reply("・Welcomeメッセージコマンド\nエラー:権限がありません。") return args = ctx.message.content.split(" ", 3) if len(args) != 3: await ctx.reply(f"・Welcomeメッセージコマンド\nエラー:書き方が間違っています。") return if args[1] != "join" and args[1] != "leave": await ctx.reply(f"・Welcomeメッセージコマンド\nエラー:書き方が間違っています。") return if args[2] == "off": if ctx.guild.id in n_fc.welcome_message_list: if args[1] in n_fc.welcome_message_list[ctx.guild.id]: del n_fc.welcome_message_list[ctx.guid.id][args[1]] else: await ctx.reply(f"・Welcomeメッセージコマンド\n{args[1]}用メッセージは設定されていません。") else: await ctx.reply(f"・Welcomeメッセージコマンド\n`{ctx.guild.name}`には設定されていません。") return if ctx.guild.id not in n_fc.welcome_message_list: n_fc.welcome_message_list[ctx.guild.id] = {args[1]: (args[2], ctx.channel.id)} else: n_fc.welcome_message_list[ctx.guild.id][args[1]] = (args[2], ctx.channel.id) await ctx.reply(f"・Welcomeメッセージコマンド\n・成功\n```\n{args[2]}```\n`{ctx.channel.name}`にメッセージを設定しました。") save() return @nextcord.slash_command(name="welcome",description="誰かがサーバー加入/離脱した時にメッセージを送信します。", guild_ids=n_fc.GUILD_IDS) async def welcome_slash(self, interaction: Interaction): pass @welcome_slash.subcommand(name="set",description="サーバー加入/離脱時のメッセージを指定します") async def set_slash( self, interaction: Interaction, MessageType: int = SlashOption( name="MessageType", description="サーバー参加時か離脱時かを選択してください", required=True, choices={"参加時": 1, "離脱時": 2} ), message: str = SlashOption( name="message", description="送信するメッセージ内容", required=True ) ): await interaction.response.defer() try: if MessageType == 1: if interaction.guild.id not in n_fc.welcome_message_list: n_fc.welcome_message_list[interaction.guild.id] = {'join': (message, interaction.channel.id)} else: n_fc.welcome_message_list[interaction.guild.id]['join'] = (message, interaction.channel.id) await interaction.followup.send(embed=nextcord.Embed(title=f"参加時のメッセージ表示", description=f"・成功\n```\n{message}```\n`{interaction.channel.name}`にメッセージを設定しました。", color=0x00ff00), ephemeral=True) elif MessageType == 2: if interaction.guild.id not in n_fc.welcome_message_list: n_fc.welcome_message_list[interaction.guild.id] = {'leave': (message, interaction.channel.id)} else: n_fc.welcome_message_list[interaction.guild.id]['leave'] = (message, interaction.channel.id) await interaction.followup.send(embed=nextcord.Embed(title=f"離脱時のメッセージ表示", description=f"・成功\n```\n{message}```\n`{interaction.channel.name}`にメッセージを設定しました。", color=0x00ff00), ephemeral=True) save() return except BaseException as err: await interaction.followup.send("コマンド実行時にエラーが発生しました。", embed=nextcord.Embed(title=f"An error has occurred during `/welcome set [**kwargs]`", description=f"```py\n{err}```\n```py\n{traceback.format_exc()}```", color=0xff0000), ephemeral=True) return @welcome_slash.subcommand(name="del",description="サーバー加入/離脱時のメッセージ設定を削除します") async def del_slash( self, interaction: Interaction, MessageType: int = SlashOption( name="MessageType", description="サーバー参加時か離脱時かを選択してください", required=True, choices={"参加時": 1, "離脱時": 2} ) ): await interaction.response.defer() try: if MessageType == 1: if interaction.guild.id in n_fc.welcome_message_list: del n_fc.welcome_message_list[interaction.guild.id]["join"] await interaction.followup.send(embed=nextcord.Embed(title=f"参加時のメッセージ表示", description=f"・成功\n設定を削除しました。", color=0x00ff00), ephemeral=True) save() else: await interaction.followup.send(embed=nextcord.Embed(title=f"参加時のメッセージ表示", description=f"このサーバーには参加時のメッセージ表示が設定されていません。", color=0xff0000), ephemeral=True) elif MessageType == 2: if interaction.guild.id in n_fc.welcome_message_list: del n_fc.welcome_message_list[interaction.guild.id]["leave"] await interaction.followup.send(embed=nextcord.Embed(title=f"離脱時のメッセージ表示", description=f"・成功\n設定を削除しました。", color=0x00ff00), ephemeral=True) save() else: await interaction.followup.send(embed=nextcord.Embed(title=f"離脱時のメッセージ表示", description=f"このサーバーには離脱時のメッセージ表示が設定されていません。", color=0xff0000), ephemeral=True) return except BaseException as err: await interaction.followup.send("コマンド実行時にエラーが発生しました。", embed=nextcord.Embed(title=f"An error has occurred during `/welcome del [**kwargs]`", description=f"```py\n{err}```\n```py\n{traceback.format_exc()}```", color=0xff0000), ephemeral=True) return @welcome_slash.subcommand(name="status",description="サーバー加入/離脱時のメッセージ設定を表示します") async def status_slash( self, interaction: Interaction, MessageType: int = SlashOption( name="MessageType", description="サーバー参加時か離脱時かを選択してください", required=True, choices={"参加時": 1, "離脱時": 2} ) ): await interaction.response.defer() try: if MessageType == 1: if interaction.guild.id in n_fc.welcome_message_list: await interaction.followup.send(embed=nextcord.Embed(title=f"参加時のメッセージ表示", description=n_fc.welcome_message_list[interaction.guild.id]["join"][0], color=0x00ff00), ephemeral=True) else: await interaction.followup.send(embed=nextcord.Embed(title=f"参加時のメッセージ表示", description=f"このサーバーには参加時のメッセージ表示が設定されていません。", color=0xff0000), ephemeral=True) elif MessageType == 2: if interaction.guild.id in n_fc.welcome_message_list: await interaction.followup.send(embed=nextcord.Embed(title=f"離脱時のメッセージ表示", description=n_fc.welcome_message_list[interaction.guild.id]["leave"][0], color=0x00ff00), ephemeral=True) else: await interaction.followup.send(embed=nextcord.Embed(title=f"離脱時のメッセージ表示", description=f"このサーバーには離脱時のメッセージ表示が設定されていません。", color=0xff0000), ephemeral=True) return except BaseException as err: await interaction.followup.send("コマンド実行時にエラーが発生しました。", embed=nextcord.Embed(title=f"An error has occurred during `/welcome status`", description=f"```py\n{err}```\n```py\n{traceback.format_exc()}```", color=0xff0000), ephemeral=True) return @commands.Cog.listener() async def on_member_join(self, member): if member.guild.id not in n_fc.welcome_message_list: return if "join" not in n_fc.welcome_message_list[member.guild.id]: return message = n_fc.welcome_message_list[member.guild.id]["join"][0] message = message.replace("%name%", member.name) message = message.replace("%count%", str(len(member.guild.members))) message = message.replace("%ment%", member.mention) CHANNEL = member.guild.get_channel(n_fc.welcome_message_list[member.guild.id]["join"][1]) await CHANNEL.send(message) return @commands.Cog.listener() async def on_member_remove(self, member): if member.guild.id not in n_fc.welcome_message_list: return if "leave" not in n_fc.welcome_message_list[member.guild.id]: return message = n_fc.welcome_message_list[member.guild.id]["leave"][0] message = message.replace("%name%", member.name) message = message.replace("%count%", str(len(member.guild.members))) message = message.replace("%ment%", member.mention) CHANNEL = member.guild.get_channel(n_fc.welcome_message_list[member.guild.id]["leave"][1]) await CHANNEL.send(message) return def setup(bot): bot.add_cog(welcome(bot))
cogs/welcome.py
n!welcome join %name%さんこんちゃ!!!!! n!welcome leave %name%さんばいばい!!! n!welcome join off n!welcome leave off
0.119216
0.363675
import os, sys import shutil import time import logging import collections import json, yaml from easydict import EasyDict import pprint from .dirs import create_dirs from . import logging_utils from . import config_utils from . import torch_utils from . import shutil_utils from . import modelarts_utils from . import tensorboardX_utils def get_config_from_file(config_file, saved_path): try: if config_file.endswith('.json'): with open(config_file, 'r') as f: config_dict = json.load(f) config = EasyDict(config_dict) elif config_file.endswith('.yaml'): config_parser = config_utils.YamlConfigParser(fname=config_file, saved_fname=saved_path) config = config_parser.config_dotdict return config except ValueError: print("INVALID JSON file format.. Please provide a good json file") exit(-1) def setup_dirs_and_files(args): # create some important directories to be used for that experiment. args.ckptdir = os.path.join(args.outdir, "models/") args.tbdir = os.path.join(args.outdir, "tb/") args.textlogdir = os.path.join(args.outdir, 'textlog/') args.imgdir = os.path.join(args.outdir, 'saved_imgs/') create_dirs([args.ckptdir, args.tbdir, args.textlogdir, args.imgdir]) args.logfile = os.path.join(args.outdir, "log.txt") args.configfile = os.path.join(args.outdir, "config.yaml") def setup_outdir(args, resume_root, resume): TIME_STR = bool(int(os.getenv('TIME_STR', 0))) time_str = time.strftime("%Y%m%d-%H_%M_%S") args.outdir = args.outdir if not TIME_STR else (args.outdir + '_' + time_str) if resume_root and resume: args.outdir = resume_root print('Using config.yaml in resume_root: %s'%resume_root) args.config = os.path.join(args.outdir, "config.yaml") else: shutil.rmtree(args.outdir, ignore_errors=True) os.makedirs(args.outdir, exist_ok=True) try: print('Start copying code to outdir.') shutil.copytree('.', os.path.join(args.outdir, 'code'), ignore=shutil_utils.ignoreAbsPath(['results', ])) shutil.copytree( '../submodule/template_lib', os.path.join(args.outdir, 'submodule/template_lib'), ignore=shutil_utils.ignoreNamePath(['results', 'submodule'])) print('End copying code to outdir.') except: print("Error! Copying code to results.") return def setup_logger_and_redirect_stdout(logfile, myargs): # setup logging in the project logger = logging_utils.get_logger(filename=logfile) myargs.logger = logger myargs.stdout = sys.stdout myargs.stderr = sys.stderr logging_utils.redirect_print_to_logger(logger=logger) return def setup_config(config_file, saved_config_file, myargs): # Parse config file config = get_config_from_file(config_file, saved_path=saved_config_file) myargs.config = config # print(" THE config of experiment:") # print(pprint.pformat(config)) return def setup_tensorboardX(tbdir, args, config, myargs, start_tb=True): # tensorboard tbtool = tensorboardX_utils.TensorBoardTool(tbdir=tbdir) writer = tbtool.writer myargs.writer = writer if start_tb: tbtool.run() tbtool.add_text_md_args(args=args, name='args') tbtool.add_text_str_args(args=config, name='config') if hasattr(args, 'command'): command_config = getattr(config, args.command, 'None') tbtool.add_text_str_args(args=command_config, name='command') print(pprint.pformat(command_config)) return def setup_checkpoint(ckptdir, myargs): checkpoint = torch_utils.CheckpointTool(ckptdir=ckptdir) myargs.checkpoint = checkpoint myargs.checkpoint_dict = collections.OrderedDict() def setup_args_and_myargs(args, myargs, start_tb=True): setup_outdir(args=args, resume_root=args.resume_root, resume=args.resume) setup_dirs_and_files(args=args) setup_logger_and_redirect_stdout(args.logfile, myargs) myargs.textlogger = logging_utils.TextLogger( log_root=args.textlogdir, reinitialize=(not args.resume), logstyle='%10.3f') print("The outdir is {}".format(args.outdir)) print("The args: ") print(pprint.pformat(args)) setup_config(config_file=args.config, saved_config_file=args.configfile, myargs=myargs) setup_tensorboardX(tbdir=args.tbdir, args=args, config=myargs.config, myargs=myargs, start_tb=start_tb) modelarts_utils.modelarts_setup(args, myargs) setup_checkpoint(ckptdir=args.ckptdir, myargs=myargs) args = EasyDict(args) myargs.config = EasyDict(myargs.config) return args, myargs
submodule/template_lib/utils/config.py
import os, sys import shutil import time import logging import collections import json, yaml from easydict import EasyDict import pprint from .dirs import create_dirs from . import logging_utils from . import config_utils from . import torch_utils from . import shutil_utils from . import modelarts_utils from . import tensorboardX_utils def get_config_from_file(config_file, saved_path): try: if config_file.endswith('.json'): with open(config_file, 'r') as f: config_dict = json.load(f) config = EasyDict(config_dict) elif config_file.endswith('.yaml'): config_parser = config_utils.YamlConfigParser(fname=config_file, saved_fname=saved_path) config = config_parser.config_dotdict return config except ValueError: print("INVALID JSON file format.. Please provide a good json file") exit(-1) def setup_dirs_and_files(args): # create some important directories to be used for that experiment. args.ckptdir = os.path.join(args.outdir, "models/") args.tbdir = os.path.join(args.outdir, "tb/") args.textlogdir = os.path.join(args.outdir, 'textlog/') args.imgdir = os.path.join(args.outdir, 'saved_imgs/') create_dirs([args.ckptdir, args.tbdir, args.textlogdir, args.imgdir]) args.logfile = os.path.join(args.outdir, "log.txt") args.configfile = os.path.join(args.outdir, "config.yaml") def setup_outdir(args, resume_root, resume): TIME_STR = bool(int(os.getenv('TIME_STR', 0))) time_str = time.strftime("%Y%m%d-%H_%M_%S") args.outdir = args.outdir if not TIME_STR else (args.outdir + '_' + time_str) if resume_root and resume: args.outdir = resume_root print('Using config.yaml in resume_root: %s'%resume_root) args.config = os.path.join(args.outdir, "config.yaml") else: shutil.rmtree(args.outdir, ignore_errors=True) os.makedirs(args.outdir, exist_ok=True) try: print('Start copying code to outdir.') shutil.copytree('.', os.path.join(args.outdir, 'code'), ignore=shutil_utils.ignoreAbsPath(['results', ])) shutil.copytree( '../submodule/template_lib', os.path.join(args.outdir, 'submodule/template_lib'), ignore=shutil_utils.ignoreNamePath(['results', 'submodule'])) print('End copying code to outdir.') except: print("Error! Copying code to results.") return def setup_logger_and_redirect_stdout(logfile, myargs): # setup logging in the project logger = logging_utils.get_logger(filename=logfile) myargs.logger = logger myargs.stdout = sys.stdout myargs.stderr = sys.stderr logging_utils.redirect_print_to_logger(logger=logger) return def setup_config(config_file, saved_config_file, myargs): # Parse config file config = get_config_from_file(config_file, saved_path=saved_config_file) myargs.config = config # print(" THE config of experiment:") # print(pprint.pformat(config)) return def setup_tensorboardX(tbdir, args, config, myargs, start_tb=True): # tensorboard tbtool = tensorboardX_utils.TensorBoardTool(tbdir=tbdir) writer = tbtool.writer myargs.writer = writer if start_tb: tbtool.run() tbtool.add_text_md_args(args=args, name='args') tbtool.add_text_str_args(args=config, name='config') if hasattr(args, 'command'): command_config = getattr(config, args.command, 'None') tbtool.add_text_str_args(args=command_config, name='command') print(pprint.pformat(command_config)) return def setup_checkpoint(ckptdir, myargs): checkpoint = torch_utils.CheckpointTool(ckptdir=ckptdir) myargs.checkpoint = checkpoint myargs.checkpoint_dict = collections.OrderedDict() def setup_args_and_myargs(args, myargs, start_tb=True): setup_outdir(args=args, resume_root=args.resume_root, resume=args.resume) setup_dirs_and_files(args=args) setup_logger_and_redirect_stdout(args.logfile, myargs) myargs.textlogger = logging_utils.TextLogger( log_root=args.textlogdir, reinitialize=(not args.resume), logstyle='%10.3f') print("The outdir is {}".format(args.outdir)) print("The args: ") print(pprint.pformat(args)) setup_config(config_file=args.config, saved_config_file=args.configfile, myargs=myargs) setup_tensorboardX(tbdir=args.tbdir, args=args, config=myargs.config, myargs=myargs, start_tb=start_tb) modelarts_utils.modelarts_setup(args, myargs) setup_checkpoint(ckptdir=args.ckptdir, myargs=myargs) args = EasyDict(args) myargs.config = EasyDict(myargs.config) return args, myargs
0.145631
0.053108
from django.contrib.auth import get_user_model from .testCases import RelayTestCase, DefaultTestCase from graphql_auth.constants import Messages from graphql_auth.utils import get_token, get_token_paylod class PasswordResetTestCaseMixin: def setUp(self): self.user1 = self.register_user( email="<EMAIL>", username="gaa", verified=True, archived=False ) self.user1_old_pass = self.user1.password def test_reset_password(self): token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) def test_reset_password_invalid_form(self): token = get_token(self.user1, "password_reset") query = self.get_query(token, "wrong_pass") executed = self.make_request(query) self.assertEqual(executed["success"], False) self.assertTrue(executed["errors"]) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass != self.user1.password) def test_reset_password_invalid_token(self): query = self.get_query("fake_token") executed = self.make_request(query) self.assertEqual(executed["success"], False) self.assertTrue(executed["errors"]["nonFieldErrors"]) self.user1.refresh_from_db() self.assertTrue(self.user1_old_pass == self.user1.password) def test_revoke_refresh_tokens_on_password_reset(self): executed = self.make_request(self.get_login_query()) self.user1.refresh_from_db() refresh_tokens = self.user1.refresh_tokens.all() for token in refresh_tokens: self.assertFalse(token.revoked) token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) refresh_tokens = self.user1.refresh_tokens.all() for token in refresh_tokens: self.assertTrue(token.revoked) def test_reset_password_verify_user(self): self.user1.verified = False self.user1.save() token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) self.assertTrue(self.user1.status.verified) class PasswordResetTestCase(PasswordResetTestCaseMixin, DefaultTestCase): def get_login_query(self): return """ mutation { tokenAuth( username: "foo_username", password: <PASSWORD>", ) { success, errors, refreshToken } } """ % ( self.default_password, ) def get_query( self, token, new_password1="<PASSWORD>", new_password2="<PASSWORD>" ): return """ mutation { passwordReset( token: "%s", newPassword1: "%s", newPassword2: "%s" ) { success, errors } } """ % ( token, new_password1, new_password2, ) class PasswordResetRelayTestCase(PasswordResetTestCaseMixin, RelayTestCase): def get_login_query(self): return """ mutation { tokenAuth( input: { username: "foo_username", password: <PASSWORD>", } ) { success, errors, refreshToken } } """ % ( self.default_password, ) def get_query( self, token, new_password1="<PASSWORD>", new_password2="<PASSWORD>" ): return """ mutation { passwordReset( input: { token: "%s", newPassword1: "%s", newPassword2: "%s" }) { success, errors } } """ % ( token, new_password1, new_password2, )
tests/test_password_reset.py
from django.contrib.auth import get_user_model from .testCases import RelayTestCase, DefaultTestCase from graphql_auth.constants import Messages from graphql_auth.utils import get_token, get_token_paylod class PasswordResetTestCaseMixin: def setUp(self): self.user1 = self.register_user( email="<EMAIL>", username="gaa", verified=True, archived=False ) self.user1_old_pass = self.user1.password def test_reset_password(self): token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) def test_reset_password_invalid_form(self): token = get_token(self.user1, "password_reset") query = self.get_query(token, "wrong_pass") executed = self.make_request(query) self.assertEqual(executed["success"], False) self.assertTrue(executed["errors"]) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass != self.user1.password) def test_reset_password_invalid_token(self): query = self.get_query("fake_token") executed = self.make_request(query) self.assertEqual(executed["success"], False) self.assertTrue(executed["errors"]["nonFieldErrors"]) self.user1.refresh_from_db() self.assertTrue(self.user1_old_pass == self.user1.password) def test_revoke_refresh_tokens_on_password_reset(self): executed = self.make_request(self.get_login_query()) self.user1.refresh_from_db() refresh_tokens = self.user1.refresh_tokens.all() for token in refresh_tokens: self.assertFalse(token.revoked) token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) refresh_tokens = self.user1.refresh_tokens.all() for token in refresh_tokens: self.assertTrue(token.revoked) def test_reset_password_verify_user(self): self.user1.verified = False self.user1.save() token = get_token(self.user1, "password_reset") query = self.get_query(token) executed = self.make_request(query) self.assertEqual(executed["success"], True) self.assertEqual(executed["errors"], None) self.user1.refresh_from_db() self.assertFalse(self.user1_old_pass == self.user1.password) self.assertTrue(self.user1.status.verified) class PasswordResetTestCase(PasswordResetTestCaseMixin, DefaultTestCase): def get_login_query(self): return """ mutation { tokenAuth( username: "foo_username", password: <PASSWORD>", ) { success, errors, refreshToken } } """ % ( self.default_password, ) def get_query( self, token, new_password1="<PASSWORD>", new_password2="<PASSWORD>" ): return """ mutation { passwordReset( token: "%s", newPassword1: "%s", newPassword2: "%s" ) { success, errors } } """ % ( token, new_password1, new_password2, ) class PasswordResetRelayTestCase(PasswordResetTestCaseMixin, RelayTestCase): def get_login_query(self): return """ mutation { tokenAuth( input: { username: "foo_username", password: <PASSWORD>", } ) { success, errors, refreshToken } } """ % ( self.default_password, ) def get_query( self, token, new_password1="<PASSWORD>", new_password2="<PASSWORD>" ): return """ mutation { passwordReset( input: { token: "%s", newPassword1: "%s", newPassword2: "%s" }) { success, errors } } """ % ( token, new_password1, new_password2, )
0.499268
0.29305
from datetime import datetime from requests.auth import HTTPBasicAuth from libqtile.widget import base from libqtile import bar, images from libqtile.log_utils import logger from libqtile.popup import Popup from .tvhlib import TVHJobServer, TVHTimeOut, ICON_PATH, ICONS class TVHWidget(base._Widget, base.MarginMixin): orientations = base.ORIENTATION_HORIZONTAL defaults = [ ("refresh_interval", 30, "Time to update data"), ("startup_delay", 5, "Time before sending first web request"), ("host", "http://localhost:9981/api", "TVHeadend server address"), ("auth", None, "Auth details for accessing tvh. " "Can be None, tuple of (username, password)."), ("tvh_timeout", 5, "Seconds before timeout for timeout request"), ("popup_format", "{start:%a %d %b %H:%M}: {title:.40}", "Upcoming recording text."), ("popup_display_timeout", 10, "Seconds to show recordings."), ("warning_colour", "aaaa00", "Highlight when there is an error."), ("recording_colour", "bb0000", "Highlight when TVHeadend is recording") ] def __init__(self, **config): base._Widget.__init__(self, bar.CALCULATED, **config) self.add_defaults(TVHWidget.defaults) self.add_defaults(base.MarginMixin.defaults) self.data = [] self.surfaces = {} self.iconsize = 0 def _configure(self, qtile, bar): base._Widget._configure(self, qtile, bar) self.setup_images() if type(self.auth) == tuple: self.auth = HTTPBasicAuth(*self.auth) self.tvh = TVHJobServer(host=self.host, auth=self.auth, timeout=self.tvh_timeout) self.timeout_add(self.startup_delay, self.refresh) def _get_data(self, queue=None): try: data = self.tvh.get_upcoming() except TVHTimeOut: logger.warning("Couldn't connect to TVH server") data = [] return data def _read_data(self, future): self.data = future.result() self.timeout_add(1, self.draw) self.timeout_add(self.refresh_interval, self.refresh) def setup_images(self): d_images = images.Loader(ICON_PATH)(*ICONS) for name, img in d_images.items(): new_height = self.bar.height - 1 img.resize(height=new_height) self.iconsize = img.width self.surfaces[name] = img.pattern def refresh(self): future = self.qtile.run_in_executor(self._get_data) future.add_done_callback(self._read_data) def set_refresh_timer(self): pass def calculate_length(self): return self.iconsize def draw_highlight(self, top=False, colour="000000"): self.drawer.set_source_rgb(colour) y = 0 if top else self.bar.height - 2 # Draw the bar self.drawer.fillrect(0, y, self.width, 2, 2) def draw(self): # Remove background self.drawer.clear(self.background or self.bar.background) self.drawer.ctx.set_source(self.surfaces["icon"]) self.drawer.ctx.paint() if not self.data: self.draw_highlight(top=True, colour=self.warning_colour) elif self.is_recording: self.draw_highlight(top=False, colour=self.recording_colour) self.drawer.draw(offsetx=self.offset, width=self.length) def button_press(self, x, y, button): self.show_recs() @property def is_recording(self): if not self.data: return False dtnow = datetime.now() for prog in self.data: if prog["start"] <= dtnow <= prog["stop"]: return True return False def mouse_enter(self, x, y): pass def show_recs(self): lines = [] if not self.data: lines.append("No upcoming recordings.") else: lines.append("Upcoming recordings:") for rec in self.data: lines.append(self.popup_format.format(**rec)) self.popup = Popup(self.qtile, y=self.bar.height, width=900, height=900, font="monospace", horizontal_padding=10, vertical_padding=10, opacity=0.8) self.popup.text = "\n".join(lines) self.popup.height = (self.popup.layout.height + (2 * self.popup.vertical_padding)) self.popup.width = (self.popup.layout.width + (2 * self.popup.horizontal_padding)) self.popup.x = min(self.offsetx, self.bar.width - self.popup.width) self.popup.place() self.popup.draw_text() self.popup.unhide() self.popup.draw() self.timeout_add(self.popup_display_timeout, self.popup.kill)
tvhwidget/tvhwidget.py
from datetime import datetime from requests.auth import HTTPBasicAuth from libqtile.widget import base from libqtile import bar, images from libqtile.log_utils import logger from libqtile.popup import Popup from .tvhlib import TVHJobServer, TVHTimeOut, ICON_PATH, ICONS class TVHWidget(base._Widget, base.MarginMixin): orientations = base.ORIENTATION_HORIZONTAL defaults = [ ("refresh_interval", 30, "Time to update data"), ("startup_delay", 5, "Time before sending first web request"), ("host", "http://localhost:9981/api", "TVHeadend server address"), ("auth", None, "Auth details for accessing tvh. " "Can be None, tuple of (username, password)."), ("tvh_timeout", 5, "Seconds before timeout for timeout request"), ("popup_format", "{start:%a %d %b %H:%M}: {title:.40}", "Upcoming recording text."), ("popup_display_timeout", 10, "Seconds to show recordings."), ("warning_colour", "aaaa00", "Highlight when there is an error."), ("recording_colour", "bb0000", "Highlight when TVHeadend is recording") ] def __init__(self, **config): base._Widget.__init__(self, bar.CALCULATED, **config) self.add_defaults(TVHWidget.defaults) self.add_defaults(base.MarginMixin.defaults) self.data = [] self.surfaces = {} self.iconsize = 0 def _configure(self, qtile, bar): base._Widget._configure(self, qtile, bar) self.setup_images() if type(self.auth) == tuple: self.auth = HTTPBasicAuth(*self.auth) self.tvh = TVHJobServer(host=self.host, auth=self.auth, timeout=self.tvh_timeout) self.timeout_add(self.startup_delay, self.refresh) def _get_data(self, queue=None): try: data = self.tvh.get_upcoming() except TVHTimeOut: logger.warning("Couldn't connect to TVH server") data = [] return data def _read_data(self, future): self.data = future.result() self.timeout_add(1, self.draw) self.timeout_add(self.refresh_interval, self.refresh) def setup_images(self): d_images = images.Loader(ICON_PATH)(*ICONS) for name, img in d_images.items(): new_height = self.bar.height - 1 img.resize(height=new_height) self.iconsize = img.width self.surfaces[name] = img.pattern def refresh(self): future = self.qtile.run_in_executor(self._get_data) future.add_done_callback(self._read_data) def set_refresh_timer(self): pass def calculate_length(self): return self.iconsize def draw_highlight(self, top=False, colour="000000"): self.drawer.set_source_rgb(colour) y = 0 if top else self.bar.height - 2 # Draw the bar self.drawer.fillrect(0, y, self.width, 2, 2) def draw(self): # Remove background self.drawer.clear(self.background or self.bar.background) self.drawer.ctx.set_source(self.surfaces["icon"]) self.drawer.ctx.paint() if not self.data: self.draw_highlight(top=True, colour=self.warning_colour) elif self.is_recording: self.draw_highlight(top=False, colour=self.recording_colour) self.drawer.draw(offsetx=self.offset, width=self.length) def button_press(self, x, y, button): self.show_recs() @property def is_recording(self): if not self.data: return False dtnow = datetime.now() for prog in self.data: if prog["start"] <= dtnow <= prog["stop"]: return True return False def mouse_enter(self, x, y): pass def show_recs(self): lines = [] if not self.data: lines.append("No upcoming recordings.") else: lines.append("Upcoming recordings:") for rec in self.data: lines.append(self.popup_format.format(**rec)) self.popup = Popup(self.qtile, y=self.bar.height, width=900, height=900, font="monospace", horizontal_padding=10, vertical_padding=10, opacity=0.8) self.popup.text = "\n".join(lines) self.popup.height = (self.popup.layout.height + (2 * self.popup.vertical_padding)) self.popup.width = (self.popup.layout.width + (2 * self.popup.horizontal_padding)) self.popup.x = min(self.offsetx, self.bar.width - self.popup.width) self.popup.place() self.popup.draw_text() self.popup.unhide() self.popup.draw() self.timeout_add(self.popup_display_timeout, self.popup.kill)
0.635562
0.097005
import datetime import logging from pathlib import Path from centralpy.client import CentralClient from centralpy.responses import CsvZip logger = logging.getLogger(__name__) # pylint: disable=too-many-arguments def pull_csv_zip( client: CentralClient, project: str, form_id: str, csv_dir: Path, zip_dir: Path, no_attachments: bool, no_progress: bool, ): """Download the CSV zip from ODK Central.""" csv_zip = client.get_submissions_csv_zip( project, form_id, no_attachments, zip_dir, no_progress ) logger.info( "CSV zip download complete for form_id %s. Attachments included: %s", form_id, not no_attachments, ) logger.info("Zip saved to %s", csv_zip.filename) files = csv_zip.extract_files_to(csv_dir) for item in files: logger.info('Into directory %s, CSV data file saved: "%s"', csv_dir, item) def keep_recent_zips(keep: int, form_id: str, zip_dir: Path, suffix_format: str = None): """Keep only the specified number of CSV zip files in a directory.""" if keep < 1: return zips = list(zip_dir.glob(f"{form_id}*.zip")) result = [] for zip_path in zips: stem = zip_path.stem form_id_len = len(form_id) time_suffix = stem[form_id_len:] fmt = CsvZip.ZIPFILE_SUFFIX_FMT if suffix_format is None else suffix_format try: date_time = datetime.datetime.strptime(time_suffix, fmt) result.append((date_time, zip_path)) except ValueError: pass if len(zips) != len(result): logger.warning( ( 'In directory %s, %d zip files start with "%s", but only %d have date ' "information in the file name." ), zip_dir, len(zips), form_id, len(result), ) if len(result) <= keep: return result.sort(reverse=True) for _, zip_path in result[keep:]: zip_path.unlink() logger.info("While deleting old zips, deleted %s", zip_path)
centralpy/use_cases/pull_csv_zip.py
import datetime import logging from pathlib import Path from centralpy.client import CentralClient from centralpy.responses import CsvZip logger = logging.getLogger(__name__) # pylint: disable=too-many-arguments def pull_csv_zip( client: CentralClient, project: str, form_id: str, csv_dir: Path, zip_dir: Path, no_attachments: bool, no_progress: bool, ): """Download the CSV zip from ODK Central.""" csv_zip = client.get_submissions_csv_zip( project, form_id, no_attachments, zip_dir, no_progress ) logger.info( "CSV zip download complete for form_id %s. Attachments included: %s", form_id, not no_attachments, ) logger.info("Zip saved to %s", csv_zip.filename) files = csv_zip.extract_files_to(csv_dir) for item in files: logger.info('Into directory %s, CSV data file saved: "%s"', csv_dir, item) def keep_recent_zips(keep: int, form_id: str, zip_dir: Path, suffix_format: str = None): """Keep only the specified number of CSV zip files in a directory.""" if keep < 1: return zips = list(zip_dir.glob(f"{form_id}*.zip")) result = [] for zip_path in zips: stem = zip_path.stem form_id_len = len(form_id) time_suffix = stem[form_id_len:] fmt = CsvZip.ZIPFILE_SUFFIX_FMT if suffix_format is None else suffix_format try: date_time = datetime.datetime.strptime(time_suffix, fmt) result.append((date_time, zip_path)) except ValueError: pass if len(zips) != len(result): logger.warning( ( 'In directory %s, %d zip files start with "%s", but only %d have date ' "information in the file name." ), zip_dir, len(zips), form_id, len(result), ) if len(result) <= keep: return result.sort(reverse=True) for _, zip_path in result[keep:]: zip_path.unlink() logger.info("While deleting old zips, deleted %s", zip_path)
0.435421
0.116764
from app import db from app import login from sqlalchemy.sql import func from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) profile_image = db.Column(db.LargeBinary) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(140)) node_id = db.Column(db.Integer, db.ForeignKey('node.id')) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) def __init__(self, message, node_id): self.message = message self.node_id = node_id def __repr__(self): return '<Post {}>'.format(self.message) class Node(db.Model): id = db.Column(db.Integer, primary_key=True) mac = db.Column(db.String(140)) name = db.Column(db.String(140)) pool_id = db.Column(db.Integer, db.ForeignKey('pool.id')) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __init__(self, mac, name, user_id): self.mac = mac self.name = name self.user_id = user_id def __repr__(self): return '<Node {}>'.format(self.name) class Object(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(140)) pool_id = db.Column(db.Integer, db.ForeignKey('pool.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __init__(self, name, data): self.name = name self.data = data def __repr__(self): return '<Node {}>'.format(self.name) class Pool(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(140)) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) repository = db.Column(db.String(140)) def __init__(self, name, repository): self.name = name self.repository = repository def __repr__(self): return '<Node {}>'.format(self.name) @login.user_loader def load_user(id): return User.query.get(int(id))
app/models.py
from app import db from app import login from sqlalchemy.sql import func from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) profile_image = db.Column(db.LargeBinary) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(140)) node_id = db.Column(db.Integer, db.ForeignKey('node.id')) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) def __init__(self, message, node_id): self.message = message self.node_id = node_id def __repr__(self): return '<Post {}>'.format(self.message) class Node(db.Model): id = db.Column(db.Integer, primary_key=True) mac = db.Column(db.String(140)) name = db.Column(db.String(140)) pool_id = db.Column(db.Integer, db.ForeignKey('pool.id')) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __init__(self, mac, name, user_id): self.mac = mac self.name = name self.user_id = user_id def __repr__(self): return '<Node {}>'.format(self.name) class Object(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(140)) pool_id = db.Column(db.Integer, db.ForeignKey('pool.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __init__(self, name, data): self.name = name self.data = data def __repr__(self): return '<Node {}>'.format(self.name) class Pool(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(140)) timestamp = db.Column(db.DateTime(timezone=True), index=True, server_default=func.now()) repository = db.Column(db.String(140)) def __init__(self, name, repository): self.name = name self.repository = repository def __repr__(self): return '<Node {}>'.format(self.name) @login.user_loader def load_user(id): return User.query.get(int(id))
0.519278
0.059319
import requests as http from aqt.addons import ConfigEditor from aqt import mw from aqt.qt import * from aqt.utils import showWarning from .config import get_credentials from .const import LANGUAGE_CODES # If user is authenticated return authorization token otherwise return None def authenticate(): # Get username and password if they exist username, password = get_credentials() if username and password: authenticate_url = "https://www.lingq.com/api/api-token-auth/" response = http.post( authenticate_url, data={"username": username, "password": password}, ) if response.status_code == http.codes.ok: return response.json()["token"] return def get_cards(language): token = authenticate() if token: # Retrieve language code for the language with given title language_code = LANGUAGE_CODES[language] cards_url = "https://www.lingq.com/api/v2/{}/cards/?page_size=100".format( language_code ) response = http.get( cards_url, headers={"Authorization": "Token {}".format(token)} ).json() cards = [] # Iterate over paginated response until all cards collected while True: # collect page of cards cards.extend(response["results"]) if not response["next"]: break cards_url = response["next"] # get next page of cards response = http.get( cards_url, headers={"Authorization": "Token {}".format(token)} ).json() return cards showWarning("Failed to load cards") def get_active_languages(): token = authenticate() if token: active_lang_url = "https://www.lingq.com/api/v2/contexts" response = http.get( active_lang_url, headers={"Authorization": "Token {}".format(token)} ) languages = [] for context in response.json()["results"]: languages.append(context["language"]["title"]) return languages showWarning("Failed to get active languages")
sync_lingq/lingq.py
import requests as http from aqt.addons import ConfigEditor from aqt import mw from aqt.qt import * from aqt.utils import showWarning from .config import get_credentials from .const import LANGUAGE_CODES # If user is authenticated return authorization token otherwise return None def authenticate(): # Get username and password if they exist username, password = get_credentials() if username and password: authenticate_url = "https://www.lingq.com/api/api-token-auth/" response = http.post( authenticate_url, data={"username": username, "password": password}, ) if response.status_code == http.codes.ok: return response.json()["token"] return def get_cards(language): token = authenticate() if token: # Retrieve language code for the language with given title language_code = LANGUAGE_CODES[language] cards_url = "https://www.lingq.com/api/v2/{}/cards/?page_size=100".format( language_code ) response = http.get( cards_url, headers={"Authorization": "Token {}".format(token)} ).json() cards = [] # Iterate over paginated response until all cards collected while True: # collect page of cards cards.extend(response["results"]) if not response["next"]: break cards_url = response["next"] # get next page of cards response = http.get( cards_url, headers={"Authorization": "Token {}".format(token)} ).json() return cards showWarning("Failed to load cards") def get_active_languages(): token = authenticate() if token: active_lang_url = "https://www.lingq.com/api/v2/contexts" response = http.get( active_lang_url, headers={"Authorization": "Token {}".format(token)} ) languages = [] for context in response.json()["results"]: languages.append(context["language"]["title"]) return languages showWarning("Failed to get active languages")
0.507812
0.091544
import argparse import logging import yaml import datetime import time import urllib import os from kubernetes import client as k8s_client from kubernetes.client import rest from benchmark.test import deploy_utils from kubeflow.testing import util def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--namespace", default='default', type=str, help=("The namespace to use.")) parser.add_argument( "--base_dir", default=None, type=str, help=("The source directory of all repositories.")) parser.add_argument( "--github_secret_name", default="github-token", type=str, help=("The github token to be created.")) parser.add_argument( "--kubeflow_registry", default="github.com/jeffwan/kubeflow/tree/master/kubeflow", type=str, help=("The github token to be created.")) parser.add_argument( "--kubebench_registry", default="github.com/kubeflow/kubebench/tree/master/kubebench", type=str, help=("The github token to be created.")) args, _ = parser.parse_known_args() return args def install_gpu_drivers(api_client): """Install GPU drivers on the cluster. Return: ds: Daemonset for the GPU installer """ logging.info("Install GPU Drivers.") # Fetch the daemonset to install the drivers. link = "https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.11/nvidia-device-plugin.yml" # pylint: disable=line-too-long logging.info("Using daemonset file: %s", link) f = urllib.urlopen(link) daemonset_spec = yaml.load(f) ext_client = k8s_client.ExtensionsV1beta1Api(api_client) try: namespace = daemonset_spec["metadata"]["namespace"] ext_client.create_namespaced_daemon_set(namespace, daemonset_spec) except rest.ApiException as e: # Status appears to be a string. if e.status == 409: logging.info("GPU driver daemon set has already been installed") else: raise def wait_for_gpu_driver_install(api_client, timeout=datetime.timedelta(minutes=10)): """Wait until some nodes are available with GPUs.""" end_time = datetime.datetime.now() + timeout api = k8s_client.CoreV1Api(api_client) while datetime.datetime.now() <= end_time: nodes = api.list_node() for n in nodes.items: if n.status.capacity.get("nvidia.com/gpu", 0) > 0: logging.info("GPUs are available.") return logging.info("Waiting for GPUs to be ready.") time.sleep(15) logging.error("Timeout waiting for GPU nodes to be ready.") raise TimeoutError("Timeout waiting for GPU nodes to be ready.") def install_kubeflow(api_client, app_dir, namespace): """Deploy required kubeflow packages to run benchmark""" util.run(["ks", "generate", "argo", "argo"], cwd=app_dir) util.run(["ks", "generate", "tf-job-operator", "tf-job-operator"], cwd=app_dir) util.run(["ks", "generate", "mpi-operator", "mpi-operator"], cwd=app_dir) if namespace != 'default': cmd = "ks param set tf-job-operator namespace " + namespace util.run(cmd.split(), cwd=app_dir) cmd = "ks param set mpi-operator namespace " + namespace util.run(cmd.split(), cwd=app_dir) cmd = "ks param set argo namespace " + namespace util.run(cmd.split(), cwd=app_dir) util.run(cmd.split(), cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "argo", "-c", "tf-job-operator", "-c", "mpi-operator"] util.run(apply_command, cwd=app_dir) def wait_for_kubeflow_install(api_client, namespace): """Wait until kubeflow components are up.""" # Verify that the Argo operator is deployed. argo_deployment_name = "workflow-controller" logging.info("Verifying Argo controller started.") util.wait_for_deployment(api_client, namespace, argo_deployment_name) # Verify that the TfJob operator is actually deployed. tf_job_deployment_name = "tf-job-operator" logging.info("Verifying TfJob controller started.") util.wait_for_deployment(api_client, namespace, tf_job_deployment_name) # Verify that the Argo operator is deployed. mpi_job_deployment_name = "mpi-operator" logging.info("Verifying MPIJob controller started.") util.wait_for_deployment(api_client, namespace, mpi_job_deployment_name) def install_kubebench_nfs(api_client, app_dir, namespace): """Deploy required kubeflow packages to run benchmark""" util.run(["ks", "pkg", "install", "kubebench/kubebench-quickstarter"], cwd=app_dir) util.run(["ks", "generate", "kubebench-quickstarter-service", "kubebench-quickstarter-service"], cwd=app_dir) util.run(["ks", "generate", "kubebench-quickstarter-volume", "kubebench-quickstarter-volume"], cwd=app_dir) util.run(["ks", "param", "set", "kubebench-quickstarter-service", "namespace", namespace], cwd=app_dir) util.run(["ks", "param", "set", "kubebench-quickstarter-volume", "namespace", namespace], cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "kubebench-quickstarter-service"] util.run(apply_command, cwd=app_dir) kubebench_nfs_deployment_name = "kubebench-nfs-deploy" kubebench_nfs_service_name = "kubebench-nfs-svc" logging.info("Verifying NFS deployment started") util.wait_for_deployment(api_client, namespace, kubebench_nfs_deployment_name) service = get_k8s_service(api_client, namespace, kubebench_nfs_service_name) util.run(["ks", "param", "set", "kubebench-quickstarter-volume", "nfsServiceIP", service.spec.cluster_ip], cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "kubebench-quickstarter-volume"] util.run(apply_command, cwd=app_dir) def get_k8s_service(api_client, namespace, service_name): """Get service cluster IP. Args: api_client: K8s api client to use. namespace: The name space for the service. name: The name of the service. Returns: service: The deploy object describing the service. Raises: TimeoutError: If timeout waiting for service to be ready. """ end_time = datetime.datetime.now() + datetime.timedelta(minutes=1) api_client = k8s_client.CoreV1Api(api_client) while datetime.datetime.now() <= end_time: service = api_client.read_namespaced_service(service_name, namespace) if not service.spec or not service.spec.cluster_ip: logging.info("Waiting for service to be ready.") time.sleep(15) continue logging.info("Service %s is available.", service_name) return service logging.error("Timeout waiting for service %s to be ready.", service_name) raise TimeoutError("Timeout waiting for service %s to be ready.", service_name) def install_addon(): """Install Benchmark Addons.""" logging.basicConfig(level=logging.INFO, format=('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'), datefmt='%Y-%m-%dT%H:%M:%S', ) logging.getLogger().setLevel(logging.INFO) args = parse_args() namespace = args.namespace base_dir = args.base_dir kubeconfig_path = str(os.environ['KUBECONFIG']) api_client = deploy_utils.create_k8s_client(kubeconfig_path) # Setup GPU Device Plugin install_gpu_drivers(api_client) wait_for_gpu_driver_install(api_client) # Setup ksonnet application app_dir = deploy_utils.setup_ks_app(base_dir, namespace, api_client, args.kubeflow_registry, args.kubebench_registry) # Deploy Kubeflow install_kubeflow(api_client, app_dir, namespace) wait_for_kubeflow_install(api_client, namespace) # change the namespace to default to set up nfs-volume and nfs-server namespace = "default" # Deploy NFS for kubebench install_kubebench_nfs(api_client, app_dir, namespace) # Deploy Github Secret github_token = str(os.environ['GITHUB_TOKEN']) install_github_secret(api_client, namespace, args.github_secret_name, github_token) def install_github_secret(api_client, namespace, secret_name, github_token): """Install Github secret on the cluster. Return: secret: Secret for Github token """ logging.info("Install Github secret.") corev1_api = k8s_client.CoreV1Api(api_client) try: secret = client.V1Secret() secret.metadata = client.V1ObjectMeta(name=secret_name) secret.type = "Opaque" secret.data = {"GITHUB_TOKEN": github_token} corev1_api.create_namespaced_secret(namespace, secret) except rest.ApiException as e: # Status appears to be a string. if e.status == 409: logging.info("GPU driver daemon set has already been installed") else: raise if __name__ == "__main__": install_addon()
src/benchmark/test/install_addon.py
import argparse import logging import yaml import datetime import time import urllib import os from kubernetes import client as k8s_client from kubernetes.client import rest from benchmark.test import deploy_utils from kubeflow.testing import util def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--namespace", default='default', type=str, help=("The namespace to use.")) parser.add_argument( "--base_dir", default=None, type=str, help=("The source directory of all repositories.")) parser.add_argument( "--github_secret_name", default="github-token", type=str, help=("The github token to be created.")) parser.add_argument( "--kubeflow_registry", default="github.com/jeffwan/kubeflow/tree/master/kubeflow", type=str, help=("The github token to be created.")) parser.add_argument( "--kubebench_registry", default="github.com/kubeflow/kubebench/tree/master/kubebench", type=str, help=("The github token to be created.")) args, _ = parser.parse_known_args() return args def install_gpu_drivers(api_client): """Install GPU drivers on the cluster. Return: ds: Daemonset for the GPU installer """ logging.info("Install GPU Drivers.") # Fetch the daemonset to install the drivers. link = "https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.11/nvidia-device-plugin.yml" # pylint: disable=line-too-long logging.info("Using daemonset file: %s", link) f = urllib.urlopen(link) daemonset_spec = yaml.load(f) ext_client = k8s_client.ExtensionsV1beta1Api(api_client) try: namespace = daemonset_spec["metadata"]["namespace"] ext_client.create_namespaced_daemon_set(namespace, daemonset_spec) except rest.ApiException as e: # Status appears to be a string. if e.status == 409: logging.info("GPU driver daemon set has already been installed") else: raise def wait_for_gpu_driver_install(api_client, timeout=datetime.timedelta(minutes=10)): """Wait until some nodes are available with GPUs.""" end_time = datetime.datetime.now() + timeout api = k8s_client.CoreV1Api(api_client) while datetime.datetime.now() <= end_time: nodes = api.list_node() for n in nodes.items: if n.status.capacity.get("nvidia.com/gpu", 0) > 0: logging.info("GPUs are available.") return logging.info("Waiting for GPUs to be ready.") time.sleep(15) logging.error("Timeout waiting for GPU nodes to be ready.") raise TimeoutError("Timeout waiting for GPU nodes to be ready.") def install_kubeflow(api_client, app_dir, namespace): """Deploy required kubeflow packages to run benchmark""" util.run(["ks", "generate", "argo", "argo"], cwd=app_dir) util.run(["ks", "generate", "tf-job-operator", "tf-job-operator"], cwd=app_dir) util.run(["ks", "generate", "mpi-operator", "mpi-operator"], cwd=app_dir) if namespace != 'default': cmd = "ks param set tf-job-operator namespace " + namespace util.run(cmd.split(), cwd=app_dir) cmd = "ks param set mpi-operator namespace " + namespace util.run(cmd.split(), cwd=app_dir) cmd = "ks param set argo namespace " + namespace util.run(cmd.split(), cwd=app_dir) util.run(cmd.split(), cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "argo", "-c", "tf-job-operator", "-c", "mpi-operator"] util.run(apply_command, cwd=app_dir) def wait_for_kubeflow_install(api_client, namespace): """Wait until kubeflow components are up.""" # Verify that the Argo operator is deployed. argo_deployment_name = "workflow-controller" logging.info("Verifying Argo controller started.") util.wait_for_deployment(api_client, namespace, argo_deployment_name) # Verify that the TfJob operator is actually deployed. tf_job_deployment_name = "tf-job-operator" logging.info("Verifying TfJob controller started.") util.wait_for_deployment(api_client, namespace, tf_job_deployment_name) # Verify that the Argo operator is deployed. mpi_job_deployment_name = "mpi-operator" logging.info("Verifying MPIJob controller started.") util.wait_for_deployment(api_client, namespace, mpi_job_deployment_name) def install_kubebench_nfs(api_client, app_dir, namespace): """Deploy required kubeflow packages to run benchmark""" util.run(["ks", "pkg", "install", "kubebench/kubebench-quickstarter"], cwd=app_dir) util.run(["ks", "generate", "kubebench-quickstarter-service", "kubebench-quickstarter-service"], cwd=app_dir) util.run(["ks", "generate", "kubebench-quickstarter-volume", "kubebench-quickstarter-volume"], cwd=app_dir) util.run(["ks", "param", "set", "kubebench-quickstarter-service", "namespace", namespace], cwd=app_dir) util.run(["ks", "param", "set", "kubebench-quickstarter-volume", "namespace", namespace], cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "kubebench-quickstarter-service"] util.run(apply_command, cwd=app_dir) kubebench_nfs_deployment_name = "kubebench-nfs-deploy" kubebench_nfs_service_name = "kubebench-nfs-svc" logging.info("Verifying NFS deployment started") util.wait_for_deployment(api_client, namespace, kubebench_nfs_deployment_name) service = get_k8s_service(api_client, namespace, kubebench_nfs_service_name) util.run(["ks", "param", "set", "kubebench-quickstarter-volume", "nfsServiceIP", service.spec.cluster_ip], cwd=app_dir) apply_command = ["ks", "apply", "default", "-c", "kubebench-quickstarter-volume"] util.run(apply_command, cwd=app_dir) def get_k8s_service(api_client, namespace, service_name): """Get service cluster IP. Args: api_client: K8s api client to use. namespace: The name space for the service. name: The name of the service. Returns: service: The deploy object describing the service. Raises: TimeoutError: If timeout waiting for service to be ready. """ end_time = datetime.datetime.now() + datetime.timedelta(minutes=1) api_client = k8s_client.CoreV1Api(api_client) while datetime.datetime.now() <= end_time: service = api_client.read_namespaced_service(service_name, namespace) if not service.spec or not service.spec.cluster_ip: logging.info("Waiting for service to be ready.") time.sleep(15) continue logging.info("Service %s is available.", service_name) return service logging.error("Timeout waiting for service %s to be ready.", service_name) raise TimeoutError("Timeout waiting for service %s to be ready.", service_name) def install_addon(): """Install Benchmark Addons.""" logging.basicConfig(level=logging.INFO, format=('%(asctime)s %(name)-12s %(levelname)-8s %(message)s'), datefmt='%Y-%m-%dT%H:%M:%S', ) logging.getLogger().setLevel(logging.INFO) args = parse_args() namespace = args.namespace base_dir = args.base_dir kubeconfig_path = str(os.environ['KUBECONFIG']) api_client = deploy_utils.create_k8s_client(kubeconfig_path) # Setup GPU Device Plugin install_gpu_drivers(api_client) wait_for_gpu_driver_install(api_client) # Setup ksonnet application app_dir = deploy_utils.setup_ks_app(base_dir, namespace, api_client, args.kubeflow_registry, args.kubebench_registry) # Deploy Kubeflow install_kubeflow(api_client, app_dir, namespace) wait_for_kubeflow_install(api_client, namespace) # change the namespace to default to set up nfs-volume and nfs-server namespace = "default" # Deploy NFS for kubebench install_kubebench_nfs(api_client, app_dir, namespace) # Deploy Github Secret github_token = str(os.environ['GITHUB_TOKEN']) install_github_secret(api_client, namespace, args.github_secret_name, github_token) def install_github_secret(api_client, namespace, secret_name, github_token): """Install Github secret on the cluster. Return: secret: Secret for Github token """ logging.info("Install Github secret.") corev1_api = k8s_client.CoreV1Api(api_client) try: secret = client.V1Secret() secret.metadata = client.V1ObjectMeta(name=secret_name) secret.type = "Opaque" secret.data = {"GITHUB_TOKEN": github_token} corev1_api.create_namespaced_secret(namespace, secret) except rest.ApiException as e: # Status appears to be a string. if e.status == 409: logging.info("GPU driver daemon set has already been installed") else: raise if __name__ == "__main__": install_addon()
0.568176
0.10325
import sys, os, time, traceback from ixnetwork_restpy import SessionAssistant apiServerIp = '172.16.101.3' ixChassisIpList = ['172.16.102.5'] portList = [[ixChassisIpList[0], 1,1], [ixChassisIpList[0], 1, 2]] # For Linux API server only username = 'admin' password = '<PASSWORD>' # For linux and connection_manager only. Set to True to leave the session alive for debugging. debugMode = False forceTakePortOwnership = True vtepMultiplier = '64' l2LabelStartValue = '1001' l3LabelStartValue = '1001001' # eviCount has to be evenly divisable by l3RtCount for the script to work. eviCount = '128' l3RtCount = 8 l3RtRepeatValue = (int(eviCount) / l3RtCount) try: # LogLevel: none, info, warning, request, request_response, all session = SessionAssistant(IpAddress=apiServerIp, RestPort=None, UserName=username, Password=password, SessionName=None, SessionId=None, ApiKey=None, ClearConfig=True, LogLevel='all', LogFilename='restpy.log') ixNetwork = session.Ixnetwork ixNetwork.info('Assign ports') portMap = session.PortMapAssistant() vport = dict() for index,port in enumerate(portList): portName = 'Port_{}'.format(index+1) vport[portName] = portMap.Map(IpAddress=port[0], CardId=port[1], PortId=port[2], Name=portName) portMap.Connect(forceTakePortOwnership) ixNetwork.info('Creating Topology Group 1') topology1 = ixNetwork.Topology.add(Name='Topo1', Ports=vport['Port_1']) deviceGroup1 = topology1.DeviceGroup.add(Name='DG1', Multiplier=vtepMultiplier) ethernet1 = deviceGroup1.Ethernet.add(Name='Eth1') ethernet1.Mac.Increment(start_value='00:01:01:01:00:01', step_value='00:00:00:00:00:01') ixNetwork.info('Configuring IPv4') ipv4 = ethernet1.Ipv4.add(Name='Ipv4') ipv4.Address.Increment(start_value='10.1.1.1', step_value='0.0.0.1') ipv4.GatewayIp.Increment(start_value='10.1.2.1', step_value='0.0.0.1') ixNetwork.info('Configuring BgpIpv4Peer 1') bgp1 = ipv4.BgpIpv4Peer.add(Name='Bgp1') bgp1.DutIp.Increment(start_value='10.1.2.1', step_value='0.0.0.1') bgp1.Type.Single('internal') bgp1.LocalAs2Bytes.Increment(start_value=101, step_value=0) bgp1.AdvertiseEvpnRoutesForOtherVtep = 'True' bgp1.FilterEvpn.Single(True) ixNetwork.info('Configuring EVPN 1') evpn1 = bgp1.BgpIPv4EvpnVXLAN.add(Name='EVPN_VXLAN_1') bgp1.BgpEthernetSegmentV4.EvisCount = eviCount bgp1.BgpEthernetSegmentV4.VtepIpv4Address.Increment(start_value='10.1.1.1', step_value='0.0.0.1') evpn1.NumBroadcastDomainV4 = '1' evpn1.RdEvi.Custom(start_value='1', step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn1.BgpL3VNIExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn1.BgpExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) ixNetwork.info('Configuring Network Group 1') networkGroup1 = deviceGroup1.NetworkGroup.add(Name='BGP-Routes1', Multiplier='1') macPool = networkGroup1.MacPools.add(NumberOfAddresses='1') CMacProperties = macPool.CMacProperties.add() connectorMac= macPool.Connector.find() connectorMac.ConnectedTo='/api/v1/sessions/1/ixnetwork/topology/1/deviceGroup/1/ethernet/1/ipv4/1/bgpIpv4Peer/1/bgpIPv4EvpnVXLAN/1' ipv4PrefixPool = macPool.Ipv4PrefixPools.add(NumberOfAddresses='1') ipv4PrefixPool.NetworkAddress.Increment(start_value='172.16.58.3', step_value='0.0.1.0') ipv4PrefixPool.PrefixLength.Single(16) macPool.CMacProperties.find()[0].FirstLabelStart.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) macPool.CMacProperties.find()[0].EnableSecondLabel.Single (True) macPool.CMacProperties.find()[0].SecondLabelStart.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) macPool.CMacProperties.find()[0].AdvertiseIpv4Address.Single (True) macPool.CMacProperties.find()[0].Ipv4AddressPrefixLength.Single(32) ixNetwork.info('Creating Topology Group 2') topology2 = ixNetwork.Topology.add(Name='Topo2', Ports=vport['Port_2']) deviceGroup2 = topology2.DeviceGroup.add(Name='DG2', Multiplier=vtepMultiplier) ethernet2 = deviceGroup2.Ethernet.add(Name='Eth2') ethernet2.Mac.Increment(start_value='00:01:01:02:00:01', step_value='00:00:00:00:00:01') ixNetwork.info('Configuring IPv4 2') ipv4 = ethernet2.Ipv4.add(Name='Ipv4-2') ipv4.Address.Increment(start_value='10.1.2.1', step_value='0.0.0.1') ipv4.GatewayIp.Increment(start_value='10.1.1.1', step_value='0.0.0.1') ixNetwork.info('Configuring BgpIpv4Peer 2') bgp2 = ipv4.BgpIpv4Peer.add(Name='Bgp2') bgp2.DutIp.Increment(start_value='10.1.1.1', step_value='0.0.0.1') bgp2.Type.Single('internal') bgp2.LocalAs2Bytes.Increment(start_value=101, step_value=0) bgp2.AdvertiseEvpnRoutesForOtherVtep = 'True' bgp2.FilterEvpn.Single(True) ixNetwork.info('Configuring EVPN 2') evpn2 = bgp2.BgpIPv4EvpnVXLAN.add(Name= 'EVPN_VXLAN_2') bgp2.BgpEthernetSegmentV4.EvisCount = eviCount bgp2.BgpEthernetSegmentV4.VtepIpv4Address.Increment(start_value='10.1.2.1', step_value='0.0.0.1') evpn2.NumBroadcastDomainV4 = '1' evpn2.RdEvi.Custom(start_value='1', step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn2.BgpL3VNIExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn2.BgpExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) ixNetwork.info('Configuring Network Group 2') networkGroup2=deviceGroup2.NetworkGroup.add(Name='BGP-Routes-2', Multiplier='1') macPool2 = networkGroup2.MacPools.add(NumberOfAddresses='1') CMacProperties2 = macPool2.CMacProperties.add() connectorMac2= macPool2.Connector.find() connectorMac2.ConnectedTo='/api/v1/sessions/1/ixnetwork/topology/2/deviceGroup/1/ethernet/1/ipv4/1/bgpIpv4Peer/1/bgpIPv4EvpnVXLAN/1' ipv4PrefixPool = macPool2.Ipv4PrefixPools.add(NumberOfAddresses='1') ipv4PrefixPool.NetworkAddress.Increment(start_value='192.168.127.12', step_value='0.0.1.0') ipv4PrefixPool.PrefixLength.Single(16) macPool2.CMacProperties.find()[0].FirstLabelStart.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) macPool2.CMacProperties.find()[0].EnableSecondLabel.Single (True) macPool2.CMacProperties.find()[0].SecondLabelStart.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) macPool2.CMacProperties.find()[0].AdvertiseIpv4Address.Single (True) macPool2.CMacProperties.find()[0].Ipv4AddressPrefixLength.Single(32) ixNetwork.StartAllProtocols(Arg1='sync') ixNetwork.info('Verify protocol sessions\n') protocolSummary = session.StatViewAssistant('Protocols Summary') protocolSummary.CheckCondition('Sessions Not Started', protocolSummary.EQUAL, 0) protocolSummary.CheckCondition('Sessions Down', protocolSummary.EQUAL, 0) ixNetwork.info(protocolSummary) ixNetwork.info('Create Traffic Item') trafficItem = ixNetwork.Traffic.TrafficItem.add(Name='Traffic Item 1', BiDirectional=False, TrafficType='ipv4') ixNetwork.info('Add endpoint flow group') trafficItem.EndpointSet.add(Sources=topology1, Destinations=topology2) ixNetwork.info('Configuring config elements') configElement = trafficItem.ConfigElement.find()[0] configElement.FrameRate.update(Type='percentLineRate', Rate=50) configElement.FrameRateDistribution.PortDistribution = 'splitRateEvenly' configElement.FrameSize.FixedSize = 128 trafficItem.Tracking.find()[0].TrackBy = ['flowGroup0'] trafficItem.Generate() ixNetwork.Traffic.Apply() ixNetwork.Traffic.StartStatelessTrafficBlocking() flowStatistics = session.StatViewAssistant('Flow Statistics') ixNetwork.info('{}\n'.format(flowStatistics)) for rowNumber,flowStat in enumerate(flowStatistics.Rows): ixNetwork.info('\n\nSTATS: {}\n\n'.format(flowStat)) ixNetwork.info('\nRow:{} TxPort:{} RxPort:{} TxFrames:{} RxFrames:{}\n'.format( rowNumber, flowStat['Tx Port'], flowStat['Rx Port'], flowStat['Tx Frames'], flowStat['Rx Frames'])) ixNetwork.Traffic.StopStatelessTrafficBlocking() if debugMode == False: # For linux and connection_manager only for vport in ixNetwork.Vport.find(): vport.ReleasePort() session.Session.remove() print ('Releasing ports and Removing Session') except Exception as errMsg: print('\n%s' % traceback.format_exc(None, errMsg)) if debugMode == False and 'session' in locals(): session.Session.remove()
RestPy/SampleScripts/evpnNgpf2.py
import sys, os, time, traceback from ixnetwork_restpy import SessionAssistant apiServerIp = '172.16.101.3' ixChassisIpList = ['172.16.102.5'] portList = [[ixChassisIpList[0], 1,1], [ixChassisIpList[0], 1, 2]] # For Linux API server only username = 'admin' password = '<PASSWORD>' # For linux and connection_manager only. Set to True to leave the session alive for debugging. debugMode = False forceTakePortOwnership = True vtepMultiplier = '64' l2LabelStartValue = '1001' l3LabelStartValue = '1001001' # eviCount has to be evenly divisable by l3RtCount for the script to work. eviCount = '128' l3RtCount = 8 l3RtRepeatValue = (int(eviCount) / l3RtCount) try: # LogLevel: none, info, warning, request, request_response, all session = SessionAssistant(IpAddress=apiServerIp, RestPort=None, UserName=username, Password=password, SessionName=None, SessionId=None, ApiKey=None, ClearConfig=True, LogLevel='all', LogFilename='restpy.log') ixNetwork = session.Ixnetwork ixNetwork.info('Assign ports') portMap = session.PortMapAssistant() vport = dict() for index,port in enumerate(portList): portName = 'Port_{}'.format(index+1) vport[portName] = portMap.Map(IpAddress=port[0], CardId=port[1], PortId=port[2], Name=portName) portMap.Connect(forceTakePortOwnership) ixNetwork.info('Creating Topology Group 1') topology1 = ixNetwork.Topology.add(Name='Topo1', Ports=vport['Port_1']) deviceGroup1 = topology1.DeviceGroup.add(Name='DG1', Multiplier=vtepMultiplier) ethernet1 = deviceGroup1.Ethernet.add(Name='Eth1') ethernet1.Mac.Increment(start_value='00:01:01:01:00:01', step_value='00:00:00:00:00:01') ixNetwork.info('Configuring IPv4') ipv4 = ethernet1.Ipv4.add(Name='Ipv4') ipv4.Address.Increment(start_value='10.1.1.1', step_value='0.0.0.1') ipv4.GatewayIp.Increment(start_value='10.1.2.1', step_value='0.0.0.1') ixNetwork.info('Configuring BgpIpv4Peer 1') bgp1 = ipv4.BgpIpv4Peer.add(Name='Bgp1') bgp1.DutIp.Increment(start_value='10.1.2.1', step_value='0.0.0.1') bgp1.Type.Single('internal') bgp1.LocalAs2Bytes.Increment(start_value=101, step_value=0) bgp1.AdvertiseEvpnRoutesForOtherVtep = 'True' bgp1.FilterEvpn.Single(True) ixNetwork.info('Configuring EVPN 1') evpn1 = bgp1.BgpIPv4EvpnVXLAN.add(Name='EVPN_VXLAN_1') bgp1.BgpEthernetSegmentV4.EvisCount = eviCount bgp1.BgpEthernetSegmentV4.VtepIpv4Address.Increment(start_value='10.1.1.1', step_value='0.0.0.1') evpn1.NumBroadcastDomainV4 = '1' evpn1.RdEvi.Custom(start_value='1', step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn1.BgpL3VNIExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn1.BgpExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) ixNetwork.info('Configuring Network Group 1') networkGroup1 = deviceGroup1.NetworkGroup.add(Name='BGP-Routes1', Multiplier='1') macPool = networkGroup1.MacPools.add(NumberOfAddresses='1') CMacProperties = macPool.CMacProperties.add() connectorMac= macPool.Connector.find() connectorMac.ConnectedTo='/api/v1/sessions/1/ixnetwork/topology/1/deviceGroup/1/ethernet/1/ipv4/1/bgpIpv4Peer/1/bgpIPv4EvpnVXLAN/1' ipv4PrefixPool = macPool.Ipv4PrefixPools.add(NumberOfAddresses='1') ipv4PrefixPool.NetworkAddress.Increment(start_value='172.16.58.3', step_value='0.0.1.0') ipv4PrefixPool.PrefixLength.Single(16) macPool.CMacProperties.find()[0].FirstLabelStart.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) macPool.CMacProperties.find()[0].EnableSecondLabel.Single (True) macPool.CMacProperties.find()[0].SecondLabelStart.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) macPool.CMacProperties.find()[0].AdvertiseIpv4Address.Single (True) macPool.CMacProperties.find()[0].Ipv4AddressPrefixLength.Single(32) ixNetwork.info('Creating Topology Group 2') topology2 = ixNetwork.Topology.add(Name='Topo2', Ports=vport['Port_2']) deviceGroup2 = topology2.DeviceGroup.add(Name='DG2', Multiplier=vtepMultiplier) ethernet2 = deviceGroup2.Ethernet.add(Name='Eth2') ethernet2.Mac.Increment(start_value='00:01:01:02:00:01', step_value='00:00:00:00:00:01') ixNetwork.info('Configuring IPv4 2') ipv4 = ethernet2.Ipv4.add(Name='Ipv4-2') ipv4.Address.Increment(start_value='10.1.2.1', step_value='0.0.0.1') ipv4.GatewayIp.Increment(start_value='10.1.1.1', step_value='0.0.0.1') ixNetwork.info('Configuring BgpIpv4Peer 2') bgp2 = ipv4.BgpIpv4Peer.add(Name='Bgp2') bgp2.DutIp.Increment(start_value='10.1.1.1', step_value='0.0.0.1') bgp2.Type.Single('internal') bgp2.LocalAs2Bytes.Increment(start_value=101, step_value=0) bgp2.AdvertiseEvpnRoutesForOtherVtep = 'True' bgp2.FilterEvpn.Single(True) ixNetwork.info('Configuring EVPN 2') evpn2 = bgp2.BgpIPv4EvpnVXLAN.add(Name= 'EVPN_VXLAN_2') bgp2.BgpEthernetSegmentV4.EvisCount = eviCount bgp2.BgpEthernetSegmentV4.VtepIpv4Address.Increment(start_value='10.1.2.1', step_value='0.0.0.1') evpn2.NumBroadcastDomainV4 = '1' evpn2.RdEvi.Custom(start_value='1', step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn2.BgpL3VNIExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) evpn2.BgpExportRouteTargetList.find()[0].TargetAssignedNumber.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) ixNetwork.info('Configuring Network Group 2') networkGroup2=deviceGroup2.NetworkGroup.add(Name='BGP-Routes-2', Multiplier='1') macPool2 = networkGroup2.MacPools.add(NumberOfAddresses='1') CMacProperties2 = macPool2.CMacProperties.add() connectorMac2= macPool2.Connector.find() connectorMac2.ConnectedTo='/api/v1/sessions/1/ixnetwork/topology/2/deviceGroup/1/ethernet/1/ipv4/1/bgpIpv4Peer/1/bgpIPv4EvpnVXLAN/1' ipv4PrefixPool = macPool2.Ipv4PrefixPools.add(NumberOfAddresses='1') ipv4PrefixPool.NetworkAddress.Increment(start_value='192.168.127.12', step_value='0.0.1.0') ipv4PrefixPool.PrefixLength.Single(16) macPool2.CMacProperties.find()[0].FirstLabelStart.Custom(start_value=l2LabelStartValue, step_value='0',increments=[('1', eviCount, [])]) macPool2.CMacProperties.find()[0].EnableSecondLabel.Single (True) macPool2.CMacProperties.find()[0].SecondLabelStart.Custom(start_value=l3LabelStartValue, step_value='0',increments=[('1', l3RtCount, [('0', l3RtRepeatValue , [])])]) macPool2.CMacProperties.find()[0].AdvertiseIpv4Address.Single (True) macPool2.CMacProperties.find()[0].Ipv4AddressPrefixLength.Single(32) ixNetwork.StartAllProtocols(Arg1='sync') ixNetwork.info('Verify protocol sessions\n') protocolSummary = session.StatViewAssistant('Protocols Summary') protocolSummary.CheckCondition('Sessions Not Started', protocolSummary.EQUAL, 0) protocolSummary.CheckCondition('Sessions Down', protocolSummary.EQUAL, 0) ixNetwork.info(protocolSummary) ixNetwork.info('Create Traffic Item') trafficItem = ixNetwork.Traffic.TrafficItem.add(Name='Traffic Item 1', BiDirectional=False, TrafficType='ipv4') ixNetwork.info('Add endpoint flow group') trafficItem.EndpointSet.add(Sources=topology1, Destinations=topology2) ixNetwork.info('Configuring config elements') configElement = trafficItem.ConfigElement.find()[0] configElement.FrameRate.update(Type='percentLineRate', Rate=50) configElement.FrameRateDistribution.PortDistribution = 'splitRateEvenly' configElement.FrameSize.FixedSize = 128 trafficItem.Tracking.find()[0].TrackBy = ['flowGroup0'] trafficItem.Generate() ixNetwork.Traffic.Apply() ixNetwork.Traffic.StartStatelessTrafficBlocking() flowStatistics = session.StatViewAssistant('Flow Statistics') ixNetwork.info('{}\n'.format(flowStatistics)) for rowNumber,flowStat in enumerate(flowStatistics.Rows): ixNetwork.info('\n\nSTATS: {}\n\n'.format(flowStat)) ixNetwork.info('\nRow:{} TxPort:{} RxPort:{} TxFrames:{} RxFrames:{}\n'.format( rowNumber, flowStat['Tx Port'], flowStat['Rx Port'], flowStat['Tx Frames'], flowStat['Rx Frames'])) ixNetwork.Traffic.StopStatelessTrafficBlocking() if debugMode == False: # For linux and connection_manager only for vport in ixNetwork.Vport.find(): vport.ReleasePort() session.Session.remove() print ('Releasing ports and Removing Session') except Exception as errMsg: print('\n%s' % traceback.format_exc(None, errMsg)) if debugMode == False and 'session' in locals(): session.Session.remove()
0.183082
0.108378
from bs4 import BeautifulSoup import json import datetime from pf2helpers import Pf2Helpers import os import re data_holder = {} data_holder['name'] = 'Pathfinder 2.0 ItemList v2' data_holder['date'] = datetime.date.today().strftime("%B %d, %Y") class ItemBuilder(): item_keywords = ['name','source', 'rarity', 'category', 'subcategory'] blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','i','a','b','h3'] pf = Pf2Helpers() weapons = [] def load_all_items(self): all_data = [] cur_path = os.getcwd() i = 1 while i < 5: file_name = cur_path+"/itemcsv/RadGridExport-%s.csv" % i raw_data = self.pf.load_csv(file_name) all_data.extend(raw_data) i += 1 self.load_weapons() return all_data def load_weapons(self): cur_path = os.getcwd() raw_data = self.pf.load_csv(cur_path+"/itemcsv/BaseWeapons.csv") link_list = ['name','source', 'rarity', 'group'] self.weapons = self.normalize_data(raw_data, link_list) #""Price","Damage","Hands","Range","Reload","Bulk","Group" def normalize_data(self, data_list, link_list): norm_data = [] for data in data_list: keys = list(data.keys()) new_data = {} for key in keys: if key in link_list: new_data[key] = self.pf.norm_link(data[key]) elif key == 'pfs': new_data[key] = self.pf.norm_pfs(data[key]) elif key == 'level': value = data[key] if value == "—": new_data[key] = value else: new_data[key] = int(value) elif key == 'traits': new_data[key] = self.pf.norm_multi(data[key]) else: new_data[key] = data[key] new_data['link'] = self.pf.norm_url(data['name']) norm_data.append(new_data) return norm_data def populate_data(self, data): new_data = {} new_data.update(data) main = self.pf.load_html(new_data['link']) if new_data['category'] == "Snares": new_data = self.parse_others(new_data, main) if new_data['category'] == "Vehicles": new_data = self.parse_vehicles(new_data, main) elif new_data['category'] != "Wands": new_data = self.parse_regular(new_data, main) #print('HTML', main) if new_data['category'] == "Weapons": new_data = self.parse_weapon_preload_stats(new_data) return new_data def parse_vehicles(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2', 'h1'] children = self.pf.split_children_by_rule(main, "<h2") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 0: stats = self.pf.parse_text_from_html(children[0], blacklist) key_words = ['Price', 'Hands', 'Range', 'Category', 'Group', 'Traits', 'Damage', 'Bulk', 'Source', 'Favored Weapon', 'Usage', 'Space', 'Crew', 'Piloting Check', 'AC', 'Fort', 'Hardness', 'HP', 'Immunities', 'Speed', 'Collision','Passengers'] objectified = self.pf.objectify_attributes(stats, key_words) new_data.update(objectified) new_data.pop("raw", None) child_pos += 1 return new_data def parse_others(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] children = self.pf.split_children_by_rule(main, "<hr") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 1: description = self.pf.parse_text_from_html(children[child_pos], blacklist) new_data['description'] = description child_pos += 1 return new_data def parse_regular(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] children = self.pf.split_children_by_rule(main, "<h2") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 0: pos = children[0].find("<hr") stats= self.parse_details(children[0][0:pos]) if new_data['category'] == 'Weapons'and "Category" in stats: weapon_cat = stats['Category'] stats.pop("Category", None) stats['weaponCat'] = weapon_cat for key in stats: new_data[key.lower()] = stats[key] new_data.pop("raw", None) new_data['description'] = self.pf.parse_text_from_html(children[0][pos:], blacklist) elif child_pos > 0: if "Critical Specialization Effects" in children[child_pos]: crit = self.parse_crit(children[child_pos]) new_data['critEffects'] = crit elif "Traits" in children[child_pos]: traits = self.parse_traits(children[child_pos]) new_data['traitDetails'] = traits #print(attack) child_pos += 1 return new_data def parse_details(self, text): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] stripped_text = self.pf.parse_text_from_html(text, blacklist) #Source Core Rulebook pg. 282 2.0 Price — (Varies); Damage Varies; Bulk L Hands 1; Range 20 ft. Category Martial Group Bomb; Traits Varies, ' key_words = ['Price', 'Hands', 'Range', 'Category', 'Group', 'Traits', 'Damage', 'Bulk', 'Source', 'Favored Weapon', 'Usage', 'Space', 'Crew', 'Piloting Check', 'AC', 'Fort', 'Hardness', 'HP', 'Immunities', 'Speed', 'Collision','Passengers'] objectified = self.pf.objectify_attributes(stripped_text, key_words) #objectified.pop("Source", None) return objectified def parse_crit(self, text): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2'] found_list = re.finditer("<b>(.*?)</b>", text) for match in found_list: key = text[match.start():match.end()] #print("Key:", key) if "Source" not in key: #print("Match:", text[match.start():]) stripped_text = self.pf.parse_text_from_html(text[match.start():], blacklist) return stripped_text def parse_traits(self, text): #print("Traits:", text) blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2'] traits = [] found_list = re.finditer('<div class="trait-entry">(.*?)</div>', text) for match in found_list: trait = {} #print(match.group()) key = re.findall('<b>(.*?)</b>', match.group())[0] pos = match.group().find("</b>") trait[key] = self.pf.parse_text_from_html(match.group()[pos:], blacklist) traits.append(trait) return traits def parse_weapon_preload_stats(self, data): key_list = ['type', 'range', 'reload'] #print("never called") weapon_name = data['name'] for weapon in self.weapons: if weapon['name'] == weapon_name: for key in weapon.keys(): if key in key_list: data[key] = weapon[key] return data def save_data(self, data): data_holder['items'] = data json_data = json.dumps(data_holder, indent=4) # print(json_data) filename = "json/items-pf2-v2.json" f = open(filename, "w") f.write(json_data) f.close return json_data def main(): bf = ItemBuilder() data = bf.load_all_items() norm_data = bf.normalize_data(data, bf.item_keywords) final_data = [] for data_point in norm_data: final_data.append(bf.populate_data(data_point)) bf.save_data(final_data) #bf.save_data(bf.build_monsters()) if __name__ == '__main__': main()
buildItems.py
from bs4 import BeautifulSoup import json import datetime from pf2helpers import Pf2Helpers import os import re data_holder = {} data_holder['name'] = 'Pathfinder 2.0 ItemList v2' data_holder['date'] = datetime.date.today().strftime("%B %d, %Y") class ItemBuilder(): item_keywords = ['name','source', 'rarity', 'category', 'subcategory'] blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','i','a','b','h3'] pf = Pf2Helpers() weapons = [] def load_all_items(self): all_data = [] cur_path = os.getcwd() i = 1 while i < 5: file_name = cur_path+"/itemcsv/RadGridExport-%s.csv" % i raw_data = self.pf.load_csv(file_name) all_data.extend(raw_data) i += 1 self.load_weapons() return all_data def load_weapons(self): cur_path = os.getcwd() raw_data = self.pf.load_csv(cur_path+"/itemcsv/BaseWeapons.csv") link_list = ['name','source', 'rarity', 'group'] self.weapons = self.normalize_data(raw_data, link_list) #""Price","Damage","Hands","Range","Reload","Bulk","Group" def normalize_data(self, data_list, link_list): norm_data = [] for data in data_list: keys = list(data.keys()) new_data = {} for key in keys: if key in link_list: new_data[key] = self.pf.norm_link(data[key]) elif key == 'pfs': new_data[key] = self.pf.norm_pfs(data[key]) elif key == 'level': value = data[key] if value == "—": new_data[key] = value else: new_data[key] = int(value) elif key == 'traits': new_data[key] = self.pf.norm_multi(data[key]) else: new_data[key] = data[key] new_data['link'] = self.pf.norm_url(data['name']) norm_data.append(new_data) return norm_data def populate_data(self, data): new_data = {} new_data.update(data) main = self.pf.load_html(new_data['link']) if new_data['category'] == "Snares": new_data = self.parse_others(new_data, main) if new_data['category'] == "Vehicles": new_data = self.parse_vehicles(new_data, main) elif new_data['category'] != "Wands": new_data = self.parse_regular(new_data, main) #print('HTML', main) if new_data['category'] == "Weapons": new_data = self.parse_weapon_preload_stats(new_data) return new_data def parse_vehicles(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2', 'h1'] children = self.pf.split_children_by_rule(main, "<h2") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 0: stats = self.pf.parse_text_from_html(children[0], blacklist) key_words = ['Price', 'Hands', 'Range', 'Category', 'Group', 'Traits', 'Damage', 'Bulk', 'Source', 'Favored Weapon', 'Usage', 'Space', 'Crew', 'Piloting Check', 'AC', 'Fort', 'Hardness', 'HP', 'Immunities', 'Speed', 'Collision','Passengers'] objectified = self.pf.objectify_attributes(stats, key_words) new_data.update(objectified) new_data.pop("raw", None) child_pos += 1 return new_data def parse_others(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] children = self.pf.split_children_by_rule(main, "<hr") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 1: description = self.pf.parse_text_from_html(children[child_pos], blacklist) new_data['description'] = description child_pos += 1 return new_data def parse_regular(self, new_data, main): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] children = self.pf.split_children_by_rule(main, "<h2") while("" in children) : children.remove("") child_pos = 0 while child_pos < len(children): if child_pos == 0: pos = children[0].find("<hr") stats= self.parse_details(children[0][0:pos]) if new_data['category'] == 'Weapons'and "Category" in stats: weapon_cat = stats['Category'] stats.pop("Category", None) stats['weaponCat'] = weapon_cat for key in stats: new_data[key.lower()] = stats[key] new_data.pop("raw", None) new_data['description'] = self.pf.parse_text_from_html(children[0][pos:], blacklist) elif child_pos > 0: if "Critical Specialization Effects" in children[child_pos]: crit = self.parse_crit(children[child_pos]) new_data['critEffects'] = crit elif "Traits" in children[child_pos]: traits = self.parse_traits(children[child_pos]) new_data['traitDetails'] = traits #print(attack) child_pos += 1 return new_data def parse_details(self, text): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3'] stripped_text = self.pf.parse_text_from_html(text, blacklist) #Source Core Rulebook pg. 282 2.0 Price — (Varies); Damage Varies; Bulk L Hands 1; Range 20 ft. Category Martial Group Bomb; Traits Varies, ' key_words = ['Price', 'Hands', 'Range', 'Category', 'Group', 'Traits', 'Damage', 'Bulk', 'Source', 'Favored Weapon', 'Usage', 'Space', 'Crew', 'Piloting Check', 'AC', 'Fort', 'Hardness', 'HP', 'Immunities', 'Speed', 'Collision','Passengers'] objectified = self.pf.objectify_attributes(stripped_text, key_words) #objectified.pop("Source", None) return objectified def parse_crit(self, text): blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2'] found_list = re.finditer("<b>(.*?)</b>", text) for match in found_list: key = text[match.start():match.end()] #print("Key:", key) if "Source" not in key: #print("Match:", text[match.start():]) stripped_text = self.pf.parse_text_from_html(text[match.start():], blacklist) return stripped_text def parse_traits(self, text): #print("Traits:", text) blacklist = ['[document]','noscript','header','html','meta','head', 'input','script', 'h1','img','h3', 'h2'] traits = [] found_list = re.finditer('<div class="trait-entry">(.*?)</div>', text) for match in found_list: trait = {} #print(match.group()) key = re.findall('<b>(.*?)</b>', match.group())[0] pos = match.group().find("</b>") trait[key] = self.pf.parse_text_from_html(match.group()[pos:], blacklist) traits.append(trait) return traits def parse_weapon_preload_stats(self, data): key_list = ['type', 'range', 'reload'] #print("never called") weapon_name = data['name'] for weapon in self.weapons: if weapon['name'] == weapon_name: for key in weapon.keys(): if key in key_list: data[key] = weapon[key] return data def save_data(self, data): data_holder['items'] = data json_data = json.dumps(data_holder, indent=4) # print(json_data) filename = "json/items-pf2-v2.json" f = open(filename, "w") f.write(json_data) f.close return json_data def main(): bf = ItemBuilder() data = bf.load_all_items() norm_data = bf.normalize_data(data, bf.item_keywords) final_data = [] for data_point in norm_data: final_data.append(bf.populate_data(data_point)) bf.save_data(final_data) #bf.save_data(bf.build_monsters()) if __name__ == '__main__': main()
0.082822
0.143938
__all__ = [ 'tower_list', 'tower_receive', 'tower_send', 'log', ] import json import textwrap import re import click import tower_cli from tower_cli.cli.transfer.send import Sender from tower_cli.cli.transfer.receive import Receiver from tower_cli.cli.transfer.common import SEND_ORDER as ASSET_TYPES import yaml from dogpile.cache import make_region LOG_COLORS = { 'INFO': 'white', 'DEBUG': 'white', 'WARNING': 'yellow', 'ERROR': 'red', } cache = make_region().configure( 'dogpile.cache.memory' ) class Error(Exception): def __init__(self, message, error_code=1): self.message = message self.error_code = error_code def log(level, message, fatal=False): """ Print mesage prefixed with styled log level (eg. ERROR will be red). Arguments: level (str) -- INFO | DEBUG | WARNING | ERROR """ level = level.upper() if level == 'WARN': level = 'WARNING' level_styled = click.style(level, fg=LOG_COLORS.get(level), bold=fatal) message_styled = textwrap.indent(message, level_styled + ' ', predicate=lambda _: True) click.echo(message_styled) if fatal: raise click.Abort @cache.cache_on_arguments() def tower_list(asset_type, query): """ List all assets of certain type in Tower. Arguments: asset_type -- asset type, eg. job_template query -- search query, list of tuples (key, value) where the value is the ID e.g. label=3SN is label=1 Returns: list of assets as a dict {id: ..., name: ...} """ if asset_type not in ASSET_TYPES: raise Error(f"Unsupported asset type '{asset_type}'!") resource = tower_cli.get_resource(asset_type) return [ { 'id': item['id'], 'name': item['name'] } for item in resource.list(all_pages=True, query=query)['results'] ] @cache.cache_on_arguments() def tower_list_all(query): """ Find all assets including dependencies; job templates with provided label_id and related projects and inventories. Arguments: label_id -- label ID Returns: list of assets as a dict {id: ..., type: ..., name: ...} """ dependencies_types = ['project', 'inventory'] # set of tuple(type, id, name) assets_set = set() for item in tower_list('job_template', query): assets_set.add(('job_template', item['id'], item['name'])) for asset_data in tower_receive('job_template', item['name']): for dep_type in dependencies_types: for dep_data in tower_list(dep_type, [('name', asset_data[dep_type])]): assets_set.add((dep_type, dep_data['id'], dep_data['name'])) return [{'id': id, 'type': type, 'name': name} for type, id, name in assets_set] @cache.cache_on_arguments() def tower_receive(asset_type, asset_name): """ Receive assets from Tower Arguments: asset_type -- asset type, eg. job_template asset_name Returns: assets objects """ if asset_type not in ASSET_TYPES: raise Error(f"Unsupported asset type '{asset_type}'!") to_export = {asset_type: [asset_name]} receiver = Receiver() assets = receiver.export_assets(all=False, asset_input=to_export) # recursively convert OrderedDict to Dict # source: https://stackoverflow.com/a/27373073 return json.loads(json.dumps(assets)) def tower_send(asset): """ Upload assets to Tower. Arguments: asset -- asset object or list of assets objects """ source = asset if isinstance(asset, list) else [asset] sender = Sender(False) sender.send(source, None, None, 'default') def load_asset(file_path): """ Load asset file to dict. Now simply opens file and parses YAML. """ try: with open(file_path) as f: return yaml.safe_load(f) except IOError: raise Error(f"Failed to read content of '{file_path}'") def sanitize_filename(filename): """ Sanitize filename so it contains only alphanumeric characters, dot, underscore or dash. All other characters are replaced with single underscore and multiple consecutive uderscores is collapsed into one (eg. `a_%$#@_b` -> `a_b`). """ return re.sub(r'[^a-zA-Z0-9.-]+', '_', filename)
atacac/_utils.py
__all__ = [ 'tower_list', 'tower_receive', 'tower_send', 'log', ] import json import textwrap import re import click import tower_cli from tower_cli.cli.transfer.send import Sender from tower_cli.cli.transfer.receive import Receiver from tower_cli.cli.transfer.common import SEND_ORDER as ASSET_TYPES import yaml from dogpile.cache import make_region LOG_COLORS = { 'INFO': 'white', 'DEBUG': 'white', 'WARNING': 'yellow', 'ERROR': 'red', } cache = make_region().configure( 'dogpile.cache.memory' ) class Error(Exception): def __init__(self, message, error_code=1): self.message = message self.error_code = error_code def log(level, message, fatal=False): """ Print mesage prefixed with styled log level (eg. ERROR will be red). Arguments: level (str) -- INFO | DEBUG | WARNING | ERROR """ level = level.upper() if level == 'WARN': level = 'WARNING' level_styled = click.style(level, fg=LOG_COLORS.get(level), bold=fatal) message_styled = textwrap.indent(message, level_styled + ' ', predicate=lambda _: True) click.echo(message_styled) if fatal: raise click.Abort @cache.cache_on_arguments() def tower_list(asset_type, query): """ List all assets of certain type in Tower. Arguments: asset_type -- asset type, eg. job_template query -- search query, list of tuples (key, value) where the value is the ID e.g. label=3SN is label=1 Returns: list of assets as a dict {id: ..., name: ...} """ if asset_type not in ASSET_TYPES: raise Error(f"Unsupported asset type '{asset_type}'!") resource = tower_cli.get_resource(asset_type) return [ { 'id': item['id'], 'name': item['name'] } for item in resource.list(all_pages=True, query=query)['results'] ] @cache.cache_on_arguments() def tower_list_all(query): """ Find all assets including dependencies; job templates with provided label_id and related projects and inventories. Arguments: label_id -- label ID Returns: list of assets as a dict {id: ..., type: ..., name: ...} """ dependencies_types = ['project', 'inventory'] # set of tuple(type, id, name) assets_set = set() for item in tower_list('job_template', query): assets_set.add(('job_template', item['id'], item['name'])) for asset_data in tower_receive('job_template', item['name']): for dep_type in dependencies_types: for dep_data in tower_list(dep_type, [('name', asset_data[dep_type])]): assets_set.add((dep_type, dep_data['id'], dep_data['name'])) return [{'id': id, 'type': type, 'name': name} for type, id, name in assets_set] @cache.cache_on_arguments() def tower_receive(asset_type, asset_name): """ Receive assets from Tower Arguments: asset_type -- asset type, eg. job_template asset_name Returns: assets objects """ if asset_type not in ASSET_TYPES: raise Error(f"Unsupported asset type '{asset_type}'!") to_export = {asset_type: [asset_name]} receiver = Receiver() assets = receiver.export_assets(all=False, asset_input=to_export) # recursively convert OrderedDict to Dict # source: https://stackoverflow.com/a/27373073 return json.loads(json.dumps(assets)) def tower_send(asset): """ Upload assets to Tower. Arguments: asset -- asset object or list of assets objects """ source = asset if isinstance(asset, list) else [asset] sender = Sender(False) sender.send(source, None, None, 'default') def load_asset(file_path): """ Load asset file to dict. Now simply opens file and parses YAML. """ try: with open(file_path) as f: return yaml.safe_load(f) except IOError: raise Error(f"Failed to read content of '{file_path}'") def sanitize_filename(filename): """ Sanitize filename so it contains only alphanumeric characters, dot, underscore or dash. All other characters are replaced with single underscore and multiple consecutive uderscores is collapsed into one (eg. `a_%$#@_b` -> `a_b`). """ return re.sub(r'[^a-zA-Z0-9.-]+', '_', filename)
0.569374
0.12166
from tensorflow.keras.models import model_from_json, load_model import os from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 as cv from utils import * import numpy as np from tkinter import * from tkinter.ttk import * import PIL.Image import PIL.ImageTk REPODIR = "/home/pi/one-man-rps/" PADDING = 12 BORDER = 2 VERTICAL_FLIP = True camera = PiCamera() camera.vflip = VERTICAL_FLIP camera.resolution = IMG_NET_SIZE camera.framerate = 32 rawCapture = PiRGBArray(camera, size=IMG_NET_SIZE) time.sleep(0.5) model_backups = os.path.join(REPODIR, "data/model_backups") path = os.path.join(model_backups, "v7_model_architecture.json") with open(path, "r") as f: model = model_from_json(f.read()) path = os.path.join(model_backups, "v7_model_weights.h5") model.load_weights(path) print("Loaded model!") # Window created with tkinter window = Tk() window.attributes("-fullscreen", True) window.update() image_size = window.winfo_width() // 2 - PADDING * 2 - BORDER * 2 Style().configure("TFrame", background="white") Style().configure("CustomPanel.TLabel", borderwidth=BORDER, relief="flat", background="black") Style().configure("CustomLabel.TLabel", background="white", font="jetbrainsmono 32") def key_up(e): if e.keysym == 'Escape': sys.exit(0) window.bind('<KeyRelease>', key_up) # pre loaded images images = os.path.join(REPODIR, "prototype-scripts/src") cv_img = cv.cvtColor(cv.imread(os.path.join(images, "rock.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_rock = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "paper.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_paper = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "scissors.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_scissors = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "blank.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_empty = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "error.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_error = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) # tk panels panel_frame = Frame(window) label_frame = Frame(window) panel_gesture = Label(panel_frame, image=photo_empty, style="CustomPanel.TLabel") panel_gesture.pack(side="left", fill="x", expand=False, padx=(PADDING, PADDING), pady=(PADDING, PADDING)) panel_cam = Label(panel_frame, image=photo_empty, style="CustomPanel.TLabel") panel_cam.pack(side="right", fill="x", expand=False, padx=(PADDING, PADDING), pady=(PADDING, PADDING)) panel_frame.pack(side="top") panel_frame.update() label = Label(label_frame, text="sandbox-text", style="CustomLabel.TLabel") label.pack(side="bottom", fill="y", anchor="n", expand=TRUE) label_frame.pack(side="bottom", fill="both", anchor="center", expand=True) label_frame.update() window.update() for frame in camera.capture_continuous(rawCapture, format="rgb", use_video_port=True): image = frame.array image = cv.cvtColor(image, cv.COLOR_RGB2GRAY) / 255 input = image.reshape(1, IMG_NET_SIZE[0], IMG_NET_SIZE[1], 1) prediction = model.predict([input]) # print prediction percent prediction_text = "_" THRESHOLD = 0.6 prediction = prediction[0] highest = -1 if prediction[0] < THRESHOLD and prediction[1] < THRESHOLD and prediction[2] < THRESHOLD and prediction[3] < THRESHOLD: prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, "--") panel_gesture.configure(image=photo_error) else: CATEGORIES = ["EMPTY", "PAPER", "ROCK", "SCISSORS"] out = np.argmax(prediction) if isinstance(out, list): prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, CATEGORIES[out[0]]) highest = out[0] else: prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, CATEGORIES[out]) highest = out print(prediction_text) label.configure(text=prediction_text) if highest == 0: panel_gesture.configure(image=photo_empty) if highest == 1: panel_gesture.configure(image=photo_scissors) if highest == 2: panel_gesture.configure(image=photo_paper) if highest == 3: panel_gesture.configure(image=photo_rock) cam_photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv.resize(image * 255, (image_size, image_size)))) panel_cam.configure(image=cam_photo) rawCapture.truncate(0) window.update()
prototype-scripts/src/test_network_ui.py
from tensorflow.keras.models import model_from_json, load_model import os from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 as cv from utils import * import numpy as np from tkinter import * from tkinter.ttk import * import PIL.Image import PIL.ImageTk REPODIR = "/home/pi/one-man-rps/" PADDING = 12 BORDER = 2 VERTICAL_FLIP = True camera = PiCamera() camera.vflip = VERTICAL_FLIP camera.resolution = IMG_NET_SIZE camera.framerate = 32 rawCapture = PiRGBArray(camera, size=IMG_NET_SIZE) time.sleep(0.5) model_backups = os.path.join(REPODIR, "data/model_backups") path = os.path.join(model_backups, "v7_model_architecture.json") with open(path, "r") as f: model = model_from_json(f.read()) path = os.path.join(model_backups, "v7_model_weights.h5") model.load_weights(path) print("Loaded model!") # Window created with tkinter window = Tk() window.attributes("-fullscreen", True) window.update() image_size = window.winfo_width() // 2 - PADDING * 2 - BORDER * 2 Style().configure("TFrame", background="white") Style().configure("CustomPanel.TLabel", borderwidth=BORDER, relief="flat", background="black") Style().configure("CustomLabel.TLabel", background="white", font="jetbrainsmono 32") def key_up(e): if e.keysym == 'Escape': sys.exit(0) window.bind('<KeyRelease>', key_up) # pre loaded images images = os.path.join(REPODIR, "prototype-scripts/src") cv_img = cv.cvtColor(cv.imread(os.path.join(images, "rock.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_rock = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "paper.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_paper = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "scissors.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_scissors = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "blank.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_empty = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) cv_img = cv.cvtColor(cv.imread(os.path.join(images, "error.png")), cv.COLOR_BGR2RGB) cv_img = cv.resize(cv_img, (image_size, image_size)) photo_error = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img)) # tk panels panel_frame = Frame(window) label_frame = Frame(window) panel_gesture = Label(panel_frame, image=photo_empty, style="CustomPanel.TLabel") panel_gesture.pack(side="left", fill="x", expand=False, padx=(PADDING, PADDING), pady=(PADDING, PADDING)) panel_cam = Label(panel_frame, image=photo_empty, style="CustomPanel.TLabel") panel_cam.pack(side="right", fill="x", expand=False, padx=(PADDING, PADDING), pady=(PADDING, PADDING)) panel_frame.pack(side="top") panel_frame.update() label = Label(label_frame, text="sandbox-text", style="CustomLabel.TLabel") label.pack(side="bottom", fill="y", anchor="n", expand=TRUE) label_frame.pack(side="bottom", fill="both", anchor="center", expand=True) label_frame.update() window.update() for frame in camera.capture_continuous(rawCapture, format="rgb", use_video_port=True): image = frame.array image = cv.cvtColor(image, cv.COLOR_RGB2GRAY) / 255 input = image.reshape(1, IMG_NET_SIZE[0], IMG_NET_SIZE[1], 1) prediction = model.predict([input]) # print prediction percent prediction_text = "_" THRESHOLD = 0.6 prediction = prediction[0] highest = -1 if prediction[0] < THRESHOLD and prediction[1] < THRESHOLD and prediction[2] < THRESHOLD and prediction[3] < THRESHOLD: prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, "--") panel_gesture.configure(image=photo_error) else: CATEGORIES = ["EMPTY", "PAPER", "ROCK", "SCISSORS"] out = np.argmax(prediction) if isinstance(out, list): prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, CATEGORIES[out[0]]) highest = out[0] else: prediction_text = "E: {:>5.1f} P: {:>5.1f} R: {:>5.1f} S: {:>5.1f} {:>8}".format( prediction[0] * 100, prediction[1] * 100, prediction[2] * 100, prediction[3] * 100, CATEGORIES[out]) highest = out print(prediction_text) label.configure(text=prediction_text) if highest == 0: panel_gesture.configure(image=photo_empty) if highest == 1: panel_gesture.configure(image=photo_scissors) if highest == 2: panel_gesture.configure(image=photo_paper) if highest == 3: panel_gesture.configure(image=photo_rock) cam_photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv.resize(image * 255, (image_size, image_size)))) panel_cam.configure(image=cam_photo) rawCapture.truncate(0) window.update()
0.41324
0.228619
import pika import sys import time import os import multiprocessing import ctypes def create_test_msg(msg_size): class TEST(ctypes.Structure): _fields_ = [('data', ctypes.c_byte * msg_size)] return TEST def publisher_loop(pub_id=0, num_msgs=10000, msg_size=512, num_subscribers=1, ready_flag=None, server='localhost'): # Setup Client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='TEST', exchange_type='direct') channel.exchange_declare(exchange='SUBSCRIBER_READY', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) sub_ready_queue_name = result.method.queue channel.queue_bind( exchange='SUBSCRIBER_READY', queue=sub_ready_queue_name) # Signal that publisher is ready if ready_flag is not None: ready_flag.set() # Wait for the subscribers to be ready num_subscribers_ready = 0 def sub_ready_callback(channel, method, properties, body): nonlocal num_subscribers_ready num_subscribers_ready += 1 if num_subscribers_ready >= num_subscribers: channel.stop_consuming() # subscribers are ready if num_subscribers_ready < num_subscribers: channel.basic_consume( queue=sub_ready_queue_name, on_message_callback=sub_ready_callback, auto_ack=True) channel.start_consuming() # wait for subscribers to be ready # Create TEST message with dummy data data = create_test_msg(msg_size)() data.data[:] = list(range(msg_size)) # Send loop tic = time.perf_counter() for n in range(num_msgs): channel.basic_publish(exchange='TEST', routing_key='TEST_DATA', body=bytes(data.data)) toc = time.perf_counter() # Stats test_msg_size = ctypes.sizeof(data) #HEADER_SIZE + ctypes.sizeof(data) dur = (toc-tic) data_rate = test_msg_size * num_msgs / 1e6 / dur print(f"Publisher[{pub_id}] -> {num_msgs} messages | {int((num_msgs)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") connection.close() def subscriber_loop(sub_id, num_msgs, msg_size=512, server='localhost'): # Setup Client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='SUBSCRIBER_READY', exchange_type='fanout') channel.exchange_declare(exchange='TEST', exchange_type='direct') channel.exchange_declare(exchange='EXIT', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) test_data_queue_name = result.method.queue result = channel.queue_declare(queue='', exclusive=True) exit_queue_name = result.method.queue channel.queue_bind( exchange='TEST', queue=test_data_queue_name, routing_key='TEST_DATA') channel.queue_bind( exchange='EXIT', queue=exit_queue_name) # Send Subscriber Ready channel.basic_publish(exchange='SUBSCRIBER_READY', routing_key='', body='') # Read Loop (Start clock after first TEST msg received) abort_timeout = max(num_msgs/10000, 10) #seconds abort_start = time.perf_counter() msg_count = 0 while msg_count < num_msgs: method, properties, body = channel.basic_get(test_data_queue_name, auto_ack = True) if body is not None: if msg_count == 0: tic = time.perf_counter() toc = time.perf_counter() msg_count += 1 method, properties, body = channel.basic_get(exit_queue_name, auto_ack = True) if method is not None: print('Got EXIT') break if time.perf_counter() - abort_start > abort_timeout: print(f"Subscriber [{sub_id:d}] Timed out.") break # Stats msg_data = create_test_msg(msg_size)() test_msg_size = ctypes.sizeof(msg_data) dur = toc - tic data_rate = (test_msg_size * num_msgs) / 1e6 / dur if msg_count == num_msgs: print(f"Subscriber [{sub_id:d}] -> {msg_count} messages | {int((msg_count-1)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") else: print(f"Subscriber [{sub_id:d}] -> {msg_count} ({int(msg_count/num_msgs *100):0d}%) messages | {int((msg_count-1)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") connection.close() if __name__ == '__main__': import argparse # Configuration flags for bench utility parser = argparse.ArgumentParser(description='RabbittMQ Client bench test utility') parser.add_argument('-ms', default=128, type=int, dest='msg_size', help='Messge size in bytes.') parser.add_argument('-n', default=10000, type=int, dest='num_msgs', help='Number of messages.') parser.add_argument('-np', default=1, type=int, dest='num_publishers', help='Number of concurrent publishers.') parser.add_argument('-ns', default=1, type=int, dest='num_subscribers', help='Number of concurrent subscribers.') parser.add_argument('-s',default='localhost', dest='server', help='RabbitMQ message broker ip address (default: ''localhost'')') args = parser.parse_args() # Main Thread client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='EXIT', exchange_type='fanout') #channel.queue_declare(queue='', exclusive=True) print("Initializing producer processses...") publisher_ready = [] publishers = [] for n in range(args.num_publishers): publisher_ready.append(multiprocessing.Event()) publishers.append( multiprocessing.Process( target=publisher_loop, kwargs={ 'pub_id': n+1, 'num_msgs': int(args.num_msgs/args.num_publishers), 'msg_size': args.msg_size, 'num_subscribers': args.num_subscribers, 'ready_flag': publisher_ready[n], 'server': args.server}) ) publishers[n].start() # Wait for publisher processes to be established for flag in publisher_ready: flag.wait() print('Waiting for subscriber processes...') subscribers = [] for n in range(args.num_subscribers): subscribers.append( multiprocessing.Process( target=subscriber_loop, args=(n+1, args.num_msgs, args.msg_size), kwargs={'server':args.server})) subscribers[n].start() print("Starting Test...") #print(f"RabbitMQ packet size: {HEADER_SIZE + args.msg_size}") print(f'Sending {args.num_msgs} messages...') # Wait for publishers to finish for publisher in publishers: publisher.join() # Wait for subscribers to finish abort_timeout = max(args.num_msgs/10000, 10) #seconds abort_start = time.perf_counter() abort = False while not abort: subscribers_finished = 0 for subscriber in subscribers: if subscriber.exitcode is not None: subscribers_finished += 1 if subscribers_finished == len(subscribers): break if time.perf_counter() - abort_start > abort_timeout: channel.basic_publish(exchange='EXIT', routing_key='', body='') print('Test Timeout! Sending Exit Signal...') abort = True for subscriber in subscribers: subscriber.join() connection.close() print('Done!')
rmq_bench_synchronous.py
import pika import sys import time import os import multiprocessing import ctypes def create_test_msg(msg_size): class TEST(ctypes.Structure): _fields_ = [('data', ctypes.c_byte * msg_size)] return TEST def publisher_loop(pub_id=0, num_msgs=10000, msg_size=512, num_subscribers=1, ready_flag=None, server='localhost'): # Setup Client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='TEST', exchange_type='direct') channel.exchange_declare(exchange='SUBSCRIBER_READY', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) sub_ready_queue_name = result.method.queue channel.queue_bind( exchange='SUBSCRIBER_READY', queue=sub_ready_queue_name) # Signal that publisher is ready if ready_flag is not None: ready_flag.set() # Wait for the subscribers to be ready num_subscribers_ready = 0 def sub_ready_callback(channel, method, properties, body): nonlocal num_subscribers_ready num_subscribers_ready += 1 if num_subscribers_ready >= num_subscribers: channel.stop_consuming() # subscribers are ready if num_subscribers_ready < num_subscribers: channel.basic_consume( queue=sub_ready_queue_name, on_message_callback=sub_ready_callback, auto_ack=True) channel.start_consuming() # wait for subscribers to be ready # Create TEST message with dummy data data = create_test_msg(msg_size)() data.data[:] = list(range(msg_size)) # Send loop tic = time.perf_counter() for n in range(num_msgs): channel.basic_publish(exchange='TEST', routing_key='TEST_DATA', body=bytes(data.data)) toc = time.perf_counter() # Stats test_msg_size = ctypes.sizeof(data) #HEADER_SIZE + ctypes.sizeof(data) dur = (toc-tic) data_rate = test_msg_size * num_msgs / 1e6 / dur print(f"Publisher[{pub_id}] -> {num_msgs} messages | {int((num_msgs)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") connection.close() def subscriber_loop(sub_id, num_msgs, msg_size=512, server='localhost'): # Setup Client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='SUBSCRIBER_READY', exchange_type='fanout') channel.exchange_declare(exchange='TEST', exchange_type='direct') channel.exchange_declare(exchange='EXIT', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) test_data_queue_name = result.method.queue result = channel.queue_declare(queue='', exclusive=True) exit_queue_name = result.method.queue channel.queue_bind( exchange='TEST', queue=test_data_queue_name, routing_key='TEST_DATA') channel.queue_bind( exchange='EXIT', queue=exit_queue_name) # Send Subscriber Ready channel.basic_publish(exchange='SUBSCRIBER_READY', routing_key='', body='') # Read Loop (Start clock after first TEST msg received) abort_timeout = max(num_msgs/10000, 10) #seconds abort_start = time.perf_counter() msg_count = 0 while msg_count < num_msgs: method, properties, body = channel.basic_get(test_data_queue_name, auto_ack = True) if body is not None: if msg_count == 0: tic = time.perf_counter() toc = time.perf_counter() msg_count += 1 method, properties, body = channel.basic_get(exit_queue_name, auto_ack = True) if method is not None: print('Got EXIT') break if time.perf_counter() - abort_start > abort_timeout: print(f"Subscriber [{sub_id:d}] Timed out.") break # Stats msg_data = create_test_msg(msg_size)() test_msg_size = ctypes.sizeof(msg_data) dur = toc - tic data_rate = (test_msg_size * num_msgs) / 1e6 / dur if msg_count == num_msgs: print(f"Subscriber [{sub_id:d}] -> {msg_count} messages | {int((msg_count-1)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") else: print(f"Subscriber [{sub_id:d}] -> {msg_count} ({int(msg_count/num_msgs *100):0d}%) messages | {int((msg_count-1)/dur)} messages/sec | {data_rate:0.1f} MB/sec | {dur:0.6f} sec ") connection.close() if __name__ == '__main__': import argparse # Configuration flags for bench utility parser = argparse.ArgumentParser(description='RabbittMQ Client bench test utility') parser.add_argument('-ms', default=128, type=int, dest='msg_size', help='Messge size in bytes.') parser.add_argument('-n', default=10000, type=int, dest='num_msgs', help='Number of messages.') parser.add_argument('-np', default=1, type=int, dest='num_publishers', help='Number of concurrent publishers.') parser.add_argument('-ns', default=1, type=int, dest='num_subscribers', help='Number of concurrent subscribers.') parser.add_argument('-s',default='localhost', dest='server', help='RabbitMQ message broker ip address (default: ''localhost'')') args = parser.parse_args() # Main Thread client connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='EXIT', exchange_type='fanout') #channel.queue_declare(queue='', exclusive=True) print("Initializing producer processses...") publisher_ready = [] publishers = [] for n in range(args.num_publishers): publisher_ready.append(multiprocessing.Event()) publishers.append( multiprocessing.Process( target=publisher_loop, kwargs={ 'pub_id': n+1, 'num_msgs': int(args.num_msgs/args.num_publishers), 'msg_size': args.msg_size, 'num_subscribers': args.num_subscribers, 'ready_flag': publisher_ready[n], 'server': args.server}) ) publishers[n].start() # Wait for publisher processes to be established for flag in publisher_ready: flag.wait() print('Waiting for subscriber processes...') subscribers = [] for n in range(args.num_subscribers): subscribers.append( multiprocessing.Process( target=subscriber_loop, args=(n+1, args.num_msgs, args.msg_size), kwargs={'server':args.server})) subscribers[n].start() print("Starting Test...") #print(f"RabbitMQ packet size: {HEADER_SIZE + args.msg_size}") print(f'Sending {args.num_msgs} messages...') # Wait for publishers to finish for publisher in publishers: publisher.join() # Wait for subscribers to finish abort_timeout = max(args.num_msgs/10000, 10) #seconds abort_start = time.perf_counter() abort = False while not abort: subscribers_finished = 0 for subscriber in subscribers: if subscriber.exitcode is not None: subscribers_finished += 1 if subscribers_finished == len(subscribers): break if time.perf_counter() - abort_start > abort_timeout: channel.basic_publish(exchange='EXIT', routing_key='', body='') print('Test Timeout! Sending Exit Signal...') abort = True for subscriber in subscribers: subscriber.join() connection.close() print('Done!')
0.327023
0.10942
from django import forms from django.utils.translation import gettext as _ from dcim.models import DeviceRole, Platform, Region, Site, SiteGroup from extras.forms import CustomFieldModelFilterForm, LocalConfigContextFilterForm from tenancy.forms import TenancyFilterForm, ContactModelFilterForm from utilities.forms import ( DynamicModelMultipleChoiceField, StaticSelect, StaticSelectMultiple, TagFilterField, BOOLEAN_WITH_BLANK_CHOICES, ) from virtualization.choices import * from virtualization.models import * __all__ = ( 'ClusterFilterForm', 'ClusterGroupFilterForm', 'ClusterTypeFilterForm', 'VirtualMachineFilterForm', 'VMInterfaceFilterForm', ) class ClusterTypeFilterForm(CustomFieldModelFilterForm): model = ClusterType tag = TagFilterField(model) class ClusterGroupFilterForm(ContactModelFilterForm, CustomFieldModelFilterForm): model = ClusterGroup tag = TagFilterField(model) class ClusterFilterForm(TenancyFilterForm, ContactModelFilterForm, CustomFieldModelFilterForm): model = Cluster field_groups = [ ['q', 'tag'], ['group_id', 'type_id'], ['region_id', 'site_group_id', 'site_id'], ['tenant_group_id', 'tenant_id'], ['contact', 'contact_role'], ] type_id = DynamicModelMultipleChoiceField( queryset=ClusterType.objects.all(), required=False, label=_('Type') ) region_id = DynamicModelMultipleChoiceField( queryset=Region.objects.all(), required=False, label=_('Region') ) site_group_id = DynamicModelMultipleChoiceField( queryset=SiteGroup.objects.all(), required=False, label=_('Site group') ) site_id = DynamicModelMultipleChoiceField( queryset=Site.objects.all(), required=False, null_option='None', query_params={ 'region_id': '$region_id', 'site_group_id': '$site_group_id', }, label=_('Site') ) group_id = DynamicModelMultipleChoiceField( queryset=ClusterGroup.objects.all(), required=False, null_option='None', label=_('Group') ) tag = TagFilterField(model) class VirtualMachineFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, ContactModelFilterForm, CustomFieldModelFilterForm): model = VirtualMachine field_groups = [ ['q', 'tag'], ['cluster_group_id', 'cluster_type_id', 'cluster_id'], ['region_id', 'site_group_id', 'site_id'], ['status', 'role_id', 'platform_id', 'mac_address', 'has_primary_ip', 'local_context_data'], ['tenant_group_id', 'tenant_id'], ['contact', 'contact_role'], ] cluster_group_id = DynamicModelMultipleChoiceField( queryset=ClusterGroup.objects.all(), required=False, null_option='None', label=_('Cluster group') ) cluster_type_id = DynamicModelMultipleChoiceField( queryset=ClusterType.objects.all(), required=False, null_option='None', label=_('Cluster type') ) cluster_id = DynamicModelMultipleChoiceField( queryset=Cluster.objects.all(), required=False, label=_('Cluster') ) region_id = DynamicModelMultipleChoiceField( queryset=Region.objects.all(), required=False, label=_('Region') ) site_group_id = DynamicModelMultipleChoiceField( queryset=SiteGroup.objects.all(), required=False, label=_('Site group') ) site_id = DynamicModelMultipleChoiceField( queryset=Site.objects.all(), required=False, null_option='None', query_params={ 'region_id': '$region_id', 'group_id': '$site_group_id', }, label=_('Site') ) role_id = DynamicModelMultipleChoiceField( queryset=DeviceRole.objects.all(), required=False, null_option='None', query_params={ 'vm_role': "True" }, label=_('Role') ) status = forms.MultipleChoiceField( choices=VirtualMachineStatusChoices, required=False, widget=StaticSelectMultiple() ) platform_id = DynamicModelMultipleChoiceField( queryset=Platform.objects.all(), required=False, null_option='None', label=_('Platform') ) mac_address = forms.CharField( required=False, label='MAC address' ) has_primary_ip = forms.NullBooleanField( required=False, label='Has a primary IP', widget=StaticSelect( choices=BOOLEAN_WITH_BLANK_CHOICES ) ) tag = TagFilterField(model) class VMInterfaceFilterForm(CustomFieldModelFilterForm): model = VMInterface field_groups = [ ['q', 'tag'], ['cluster_id', 'virtual_machine_id'], ['enabled', 'mac_address'], ] cluster_id = DynamicModelMultipleChoiceField( queryset=Cluster.objects.all(), required=False, label=_('Cluster') ) virtual_machine_id = DynamicModelMultipleChoiceField( queryset=VirtualMachine.objects.all(), required=False, query_params={ 'cluster_id': '$cluster_id' }, label=_('Virtual machine') ) enabled = forms.NullBooleanField( required=False, widget=StaticSelect( choices=BOOLEAN_WITH_BLANK_CHOICES ) ) mac_address = forms.CharField( required=False, label='MAC address' ) tag = TagFilterField(model)
netbox/virtualization/forms/filtersets.py
from django import forms from django.utils.translation import gettext as _ from dcim.models import DeviceRole, Platform, Region, Site, SiteGroup from extras.forms import CustomFieldModelFilterForm, LocalConfigContextFilterForm from tenancy.forms import TenancyFilterForm, ContactModelFilterForm from utilities.forms import ( DynamicModelMultipleChoiceField, StaticSelect, StaticSelectMultiple, TagFilterField, BOOLEAN_WITH_BLANK_CHOICES, ) from virtualization.choices import * from virtualization.models import * __all__ = ( 'ClusterFilterForm', 'ClusterGroupFilterForm', 'ClusterTypeFilterForm', 'VirtualMachineFilterForm', 'VMInterfaceFilterForm', ) class ClusterTypeFilterForm(CustomFieldModelFilterForm): model = ClusterType tag = TagFilterField(model) class ClusterGroupFilterForm(ContactModelFilterForm, CustomFieldModelFilterForm): model = ClusterGroup tag = TagFilterField(model) class ClusterFilterForm(TenancyFilterForm, ContactModelFilterForm, CustomFieldModelFilterForm): model = Cluster field_groups = [ ['q', 'tag'], ['group_id', 'type_id'], ['region_id', 'site_group_id', 'site_id'], ['tenant_group_id', 'tenant_id'], ['contact', 'contact_role'], ] type_id = DynamicModelMultipleChoiceField( queryset=ClusterType.objects.all(), required=False, label=_('Type') ) region_id = DynamicModelMultipleChoiceField( queryset=Region.objects.all(), required=False, label=_('Region') ) site_group_id = DynamicModelMultipleChoiceField( queryset=SiteGroup.objects.all(), required=False, label=_('Site group') ) site_id = DynamicModelMultipleChoiceField( queryset=Site.objects.all(), required=False, null_option='None', query_params={ 'region_id': '$region_id', 'site_group_id': '$site_group_id', }, label=_('Site') ) group_id = DynamicModelMultipleChoiceField( queryset=ClusterGroup.objects.all(), required=False, null_option='None', label=_('Group') ) tag = TagFilterField(model) class VirtualMachineFilterForm(LocalConfigContextFilterForm, TenancyFilterForm, ContactModelFilterForm, CustomFieldModelFilterForm): model = VirtualMachine field_groups = [ ['q', 'tag'], ['cluster_group_id', 'cluster_type_id', 'cluster_id'], ['region_id', 'site_group_id', 'site_id'], ['status', 'role_id', 'platform_id', 'mac_address', 'has_primary_ip', 'local_context_data'], ['tenant_group_id', 'tenant_id'], ['contact', 'contact_role'], ] cluster_group_id = DynamicModelMultipleChoiceField( queryset=ClusterGroup.objects.all(), required=False, null_option='None', label=_('Cluster group') ) cluster_type_id = DynamicModelMultipleChoiceField( queryset=ClusterType.objects.all(), required=False, null_option='None', label=_('Cluster type') ) cluster_id = DynamicModelMultipleChoiceField( queryset=Cluster.objects.all(), required=False, label=_('Cluster') ) region_id = DynamicModelMultipleChoiceField( queryset=Region.objects.all(), required=False, label=_('Region') ) site_group_id = DynamicModelMultipleChoiceField( queryset=SiteGroup.objects.all(), required=False, label=_('Site group') ) site_id = DynamicModelMultipleChoiceField( queryset=Site.objects.all(), required=False, null_option='None', query_params={ 'region_id': '$region_id', 'group_id': '$site_group_id', }, label=_('Site') ) role_id = DynamicModelMultipleChoiceField( queryset=DeviceRole.objects.all(), required=False, null_option='None', query_params={ 'vm_role': "True" }, label=_('Role') ) status = forms.MultipleChoiceField( choices=VirtualMachineStatusChoices, required=False, widget=StaticSelectMultiple() ) platform_id = DynamicModelMultipleChoiceField( queryset=Platform.objects.all(), required=False, null_option='None', label=_('Platform') ) mac_address = forms.CharField( required=False, label='MAC address' ) has_primary_ip = forms.NullBooleanField( required=False, label='Has a primary IP', widget=StaticSelect( choices=BOOLEAN_WITH_BLANK_CHOICES ) ) tag = TagFilterField(model) class VMInterfaceFilterForm(CustomFieldModelFilterForm): model = VMInterface field_groups = [ ['q', 'tag'], ['cluster_id', 'virtual_machine_id'], ['enabled', 'mac_address'], ] cluster_id = DynamicModelMultipleChoiceField( queryset=Cluster.objects.all(), required=False, label=_('Cluster') ) virtual_machine_id = DynamicModelMultipleChoiceField( queryset=VirtualMachine.objects.all(), required=False, query_params={ 'cluster_id': '$cluster_id' }, label=_('Virtual machine') ) enabled = forms.NullBooleanField( required=False, widget=StaticSelect( choices=BOOLEAN_WITH_BLANK_CHOICES ) ) mac_address = forms.CharField( required=False, label='MAC address' ) tag = TagFilterField(model)
0.538741
0.066721
import multiprocessing import threading import Queue from uuid import uuid4 import numpy as np import SharedArray import data def load_shared(args): i, array_name, fname, kwargs = args array = SharedArray.attach(array_name) array[i] = data.load_augment(fname, **kwargs) class BatchIterator(object): def __init__(self, batch_size): self.batch_size = batch_size def __call__(self, X, y=None, transform=None, color_vec=None): self.tf = transform self.color_vec = color_vec self.X, self.y = X, y return self def __iter__(self): n_samples = self.X.shape[0] bs = self.batch_size for i in range((n_samples + bs - 1) // bs): sl = slice(i * bs, (i + 1) * bs) Xb = self.X[sl] if self.y is not None: yb = self.y[sl] else: yb = None yield self.transform(Xb, yb) def transform(self, Xb, yb): return Xb, yb def __getstate__(self): state = dict(self.__dict__) for attr in ('X', 'y',): if attr in state: del state[attr] return state class QueueIterator(BatchIterator): """BatchIterator with seperate thread to do the image reading.""" def __iter__(self): queue = Queue.Queue(maxsize=20) end_marker = object() def producer(): for Xb, yb in super(QueueIterator, self).__iter__(): queue.put((np.array(Xb), np.array(yb))) queue.put(end_marker) thread = threading.Thread(target=producer) thread.daemon = True thread.start() item = queue.get() while item is not end_marker: yield item queue.task_done() item = queue.get() class SharedIterator(QueueIterator): def __init__(self, config, deterministic=False, *args, **kwargs): self.config = config self.deterministic = deterministic self.pool = multiprocessing.Pool() super(SharedIterator, self).__init__(*args, **kwargs) def transform(self, Xb, yb): shared_array_name = str(uuid4()) try: shared_array = SharedArray.create( shared_array_name, [len(Xb), 3, self.config.get('w'), self.config.get('h')], dtype=np.float32) fnames, labels = super(SharedIterator, self).transform(Xb, yb) args = [] for i, fname in enumerate(fnames): kwargs = {k: self.config.get(k) for k in ['w', 'h']} if not self.deterministic: kwargs.update({k: self.config.get(k) for k in ['aug_params', 'sigma']}) kwargs['transform'] = getattr(self, 'tf', None) kwargs['color_vec'] = getattr(self, 'color_vec', None) args.append((i, shared_array_name, fname, kwargs)) self.pool.map(load_shared, args) Xb = np.array(shared_array, dtype=np.float32) finally: SharedArray.delete(shared_array_name) if labels is not None: labels = labels[:, np.newaxis] return Xb, labels class ResampleIterator(SharedIterator): def __init__(self, config, *args, **kwargs): self.config = config self.count = 0 super(ResampleIterator, self).__init__(config, *args, **kwargs) def __call__(self, X, y=None, transform=None, color_vec=None): if y is not None: alpha = self.config.cnf['balance_ratio'] ** self.count class_weights = self.config.cnf['balance_weights'] * alpha \ + self.config.cnf['final_balance_weights'] * (1 - alpha) self.count += 1 indices = data.balance_per_class_indices(y, weights=class_weights) X = X[indices] y = y[indices] return super(ResampleIterator, self).__call__(X, y, transform=transform, color_vec=color_vec)
iterator.py
import multiprocessing import threading import Queue from uuid import uuid4 import numpy as np import SharedArray import data def load_shared(args): i, array_name, fname, kwargs = args array = SharedArray.attach(array_name) array[i] = data.load_augment(fname, **kwargs) class BatchIterator(object): def __init__(self, batch_size): self.batch_size = batch_size def __call__(self, X, y=None, transform=None, color_vec=None): self.tf = transform self.color_vec = color_vec self.X, self.y = X, y return self def __iter__(self): n_samples = self.X.shape[0] bs = self.batch_size for i in range((n_samples + bs - 1) // bs): sl = slice(i * bs, (i + 1) * bs) Xb = self.X[sl] if self.y is not None: yb = self.y[sl] else: yb = None yield self.transform(Xb, yb) def transform(self, Xb, yb): return Xb, yb def __getstate__(self): state = dict(self.__dict__) for attr in ('X', 'y',): if attr in state: del state[attr] return state class QueueIterator(BatchIterator): """BatchIterator with seperate thread to do the image reading.""" def __iter__(self): queue = Queue.Queue(maxsize=20) end_marker = object() def producer(): for Xb, yb in super(QueueIterator, self).__iter__(): queue.put((np.array(Xb), np.array(yb))) queue.put(end_marker) thread = threading.Thread(target=producer) thread.daemon = True thread.start() item = queue.get() while item is not end_marker: yield item queue.task_done() item = queue.get() class SharedIterator(QueueIterator): def __init__(self, config, deterministic=False, *args, **kwargs): self.config = config self.deterministic = deterministic self.pool = multiprocessing.Pool() super(SharedIterator, self).__init__(*args, **kwargs) def transform(self, Xb, yb): shared_array_name = str(uuid4()) try: shared_array = SharedArray.create( shared_array_name, [len(Xb), 3, self.config.get('w'), self.config.get('h')], dtype=np.float32) fnames, labels = super(SharedIterator, self).transform(Xb, yb) args = [] for i, fname in enumerate(fnames): kwargs = {k: self.config.get(k) for k in ['w', 'h']} if not self.deterministic: kwargs.update({k: self.config.get(k) for k in ['aug_params', 'sigma']}) kwargs['transform'] = getattr(self, 'tf', None) kwargs['color_vec'] = getattr(self, 'color_vec', None) args.append((i, shared_array_name, fname, kwargs)) self.pool.map(load_shared, args) Xb = np.array(shared_array, dtype=np.float32) finally: SharedArray.delete(shared_array_name) if labels is not None: labels = labels[:, np.newaxis] return Xb, labels class ResampleIterator(SharedIterator): def __init__(self, config, *args, **kwargs): self.config = config self.count = 0 super(ResampleIterator, self).__init__(config, *args, **kwargs) def __call__(self, X, y=None, transform=None, color_vec=None): if y is not None: alpha = self.config.cnf['balance_ratio'] ** self.count class_weights = self.config.cnf['balance_weights'] * alpha \ + self.config.cnf['final_balance_weights'] * (1 - alpha) self.count += 1 indices = data.balance_per_class_indices(y, weights=class_weights) X = X[indices] y = y[indices] return super(ResampleIterator, self).__call__(X, y, transform=transform, color_vec=color_vec)
0.633977
0.223939
from typing import Tuple, List import numpy as np from torch.utils.data import Dataset from pathlib import Path from . import ModelCallback from ...models.base import DetectionModel from ...utils import image_utils, draw_bounding_boxes_with_name_tag class GenerateDetectionImageCallback(ModelCallback): def __init__(self, model: DetectionModel, img_size: Tuple[int, int], dataset: Dataset, out_dir: str, label_names: List[str], per_epoch: int = 10, pred_color=(0, 0, 255), teacher_color=(0, 255, 0), apply_all_images=False): """ :param model: :param img_size: (H, W) :param dataset: :param out_dir: :param per_epoch: :param pred_color: :param teacher_color: """ self._model = model self._dataset = dataset self._pred_color = pred_color self._teacher_color = teacher_color self._per_epoch = per_epoch self._out_dir = out_dir self._img_size = img_size self._label_names = label_names self._apply_all_images = apply_all_images if not Path(self._out_dir).exists(): Path(self._out_dir).mkdir() def __call__(self, epoch: int): if (epoch + 1) % self._per_epoch != 0: return if self._apply_all_images: for i, (img_tensor, teacher_bboxes) in enumerate(self._dataset): _, result_img = self._model.calc_detection_image(img_tensor, label_names=self._label_names) result_img = self._draw_teacher_bboxes(result_img, teacher_bboxes=teacher_bboxes) image_utils.cv_to_pil(result_img).save(f"{self._out_dir}/data{i}_image{epoch + 1}.png") return data_len = len(self._dataset) random_image_index = np.random.randint(0, data_len) image, teacher_bboxes = self._dataset[random_image_index] result_img = self._model.calc_detection_image(image, label_names=self._label_names)[1] result_img = self._draw_teacher_bboxes(result_img, teacher_bboxes=teacher_bboxes) image_utils.cv_to_pil(result_img).save(f"{self._out_dir}/result_{epoch + 1}.png") def _draw_teacher_bboxes(self, image: np.ndarray, teacher_bboxes: List[Tuple[float, float, float, float, int]]): """ :param image: :param teacher_bboxes: List of [x_min, y_min, x_max, y_max, label] :return: """ if teacher_bboxes is None or len(teacher_bboxes) == 0: return image for bbox in teacher_bboxes: image = draw_bounding_boxes_with_name_tag(image, [bbox], color=self._teacher_color, text=None) return image
deepext/trainer/callbacks/object_detection.py
from typing import Tuple, List import numpy as np from torch.utils.data import Dataset from pathlib import Path from . import ModelCallback from ...models.base import DetectionModel from ...utils import image_utils, draw_bounding_boxes_with_name_tag class GenerateDetectionImageCallback(ModelCallback): def __init__(self, model: DetectionModel, img_size: Tuple[int, int], dataset: Dataset, out_dir: str, label_names: List[str], per_epoch: int = 10, pred_color=(0, 0, 255), teacher_color=(0, 255, 0), apply_all_images=False): """ :param model: :param img_size: (H, W) :param dataset: :param out_dir: :param per_epoch: :param pred_color: :param teacher_color: """ self._model = model self._dataset = dataset self._pred_color = pred_color self._teacher_color = teacher_color self._per_epoch = per_epoch self._out_dir = out_dir self._img_size = img_size self._label_names = label_names self._apply_all_images = apply_all_images if not Path(self._out_dir).exists(): Path(self._out_dir).mkdir() def __call__(self, epoch: int): if (epoch + 1) % self._per_epoch != 0: return if self._apply_all_images: for i, (img_tensor, teacher_bboxes) in enumerate(self._dataset): _, result_img = self._model.calc_detection_image(img_tensor, label_names=self._label_names) result_img = self._draw_teacher_bboxes(result_img, teacher_bboxes=teacher_bboxes) image_utils.cv_to_pil(result_img).save(f"{self._out_dir}/data{i}_image{epoch + 1}.png") return data_len = len(self._dataset) random_image_index = np.random.randint(0, data_len) image, teacher_bboxes = self._dataset[random_image_index] result_img = self._model.calc_detection_image(image, label_names=self._label_names)[1] result_img = self._draw_teacher_bboxes(result_img, teacher_bboxes=teacher_bboxes) image_utils.cv_to_pil(result_img).save(f"{self._out_dir}/result_{epoch + 1}.png") def _draw_teacher_bboxes(self, image: np.ndarray, teacher_bboxes: List[Tuple[float, float, float, float, int]]): """ :param image: :param teacher_bboxes: List of [x_min, y_min, x_max, y_max, label] :return: """ if teacher_bboxes is None or len(teacher_bboxes) == 0: return image for bbox in teacher_bboxes: image = draw_bounding_boxes_with_name_tag(image, [bbox], color=self._teacher_color, text=None) return image
0.875348
0.422564
import asyncio import pytest from dask_gateway_server.workqueue import WorkQueue, Backoff, WorkQueueClosed from dask_gateway_server.utils import cancel_task def test_backoff(): backoff = Backoff(base_delay=0.5, max_delay=5) assert backoff.failures("foo") == 0 assert backoff.backoff("foo") == 0.5 assert backoff.failures("foo") == 1 assert backoff.backoff("foo") == 1.0 assert backoff.failures("foo") == 2 assert backoff.backoff("foo") == 2.0 backoff.reset("foo") assert backoff.failures("foo") == 0 assert backoff.backoff("foo") == 0.5 # No-op on unknown key backoff.reset("bar") @pytest.mark.asyncio async def test_workqueue_deduplicates(): q = WorkQueue() q.put("foo") q.put("bar") q.put("foo") assert await q.get() == "foo" assert await q.get() == "bar" assert q.is_empty() @pytest.mark.asyncio async def test_workqueue_no_concurrent_execution(): q = WorkQueue() q.put("foo") assert await q.get() == "foo" assert q.is_empty() q.put("foo") assert not q.is_empty() assert not q._queue assert "foo" in q._dirty # Cannot concurrently process "foo", even though it's requeued f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # But after marking done, can continue processing q.task_done("foo") assert q._queue res = await f assert res == "foo" @pytest.mark.asyncio async def test_workqueue_cancellable(): q = WorkQueue() # No items, blocks f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # Cancel the get task, waiter cleaned up await cancel_task(f) assert not q._waiting # No items, blocks f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # Cancel after a put, item still available q.put("foo") await cancel_task(f) assert await q.get() == "foo" @pytest.mark.asyncio async def test_workqueue_put_after(): q = WorkQueue() # Fine if already enqueued q.put("foo") q.put_after("foo", 0.001) assert len(q._queue) == 1 assert q._timers assert await q.get() == "foo" # Cannot concurrently process "foo", even though it's scheduled f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.005) assert not done # But after marking done, can continue processing q.task_done("foo") assert q._queue res = await f assert res == "foo" @pytest.mark.asyncio async def test_workqueue_put_after_reschedules(): q = WorkQueue() q.put_after("foo", 0.1) _, when = q._timers["foo"] # Scheduling after is no-op q.put_after("foo", 0.5) assert len(q._queue) == 0 assert len(q._timers) == 1 assert q._timers["foo"][1] == when # Scheduling before reschedules q.put_after("foo", 0.005) assert len(q._queue) == 0 assert len(q._timers) == 1 assert q._timers["foo"][1] < when assert await q.get() == "foo" q.task_done("foo") # Scheduling at 0 avoids timer creation q.put_after("foo", 0) assert not q._timers assert q._queue assert await q.get() == "foo" @pytest.mark.asyncio async def test_workqueue_put_backoff(): q = WorkQueue() q.put_backoff("foo") assert q.failures("foo") == 1 assert q.failures("bar") == 0 assert await q.get() == "foo" q.task_done("foo") assert q.failures("foo") == 1 q.reset_backoff("foo") assert q.failures("foo") == 0 @pytest.mark.asyncio async def test_workqueue_close(): q = WorkQueue() q.put("foo") q.close() with pytest.raises(WorkQueueClosed): await q.get() assert q.closed q = WorkQueue() fs = [asyncio.ensure_future(q.get()) for _ in range(3)] done, pending = await asyncio.wait(fs, timeout=0.001) assert not done q.close() for f in fs: with pytest.raises(WorkQueueClosed): await f
tests/test_workqueue.py
import asyncio import pytest from dask_gateway_server.workqueue import WorkQueue, Backoff, WorkQueueClosed from dask_gateway_server.utils import cancel_task def test_backoff(): backoff = Backoff(base_delay=0.5, max_delay=5) assert backoff.failures("foo") == 0 assert backoff.backoff("foo") == 0.5 assert backoff.failures("foo") == 1 assert backoff.backoff("foo") == 1.0 assert backoff.failures("foo") == 2 assert backoff.backoff("foo") == 2.0 backoff.reset("foo") assert backoff.failures("foo") == 0 assert backoff.backoff("foo") == 0.5 # No-op on unknown key backoff.reset("bar") @pytest.mark.asyncio async def test_workqueue_deduplicates(): q = WorkQueue() q.put("foo") q.put("bar") q.put("foo") assert await q.get() == "foo" assert await q.get() == "bar" assert q.is_empty() @pytest.mark.asyncio async def test_workqueue_no_concurrent_execution(): q = WorkQueue() q.put("foo") assert await q.get() == "foo" assert q.is_empty() q.put("foo") assert not q.is_empty() assert not q._queue assert "foo" in q._dirty # Cannot concurrently process "foo", even though it's requeued f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # But after marking done, can continue processing q.task_done("foo") assert q._queue res = await f assert res == "foo" @pytest.mark.asyncio async def test_workqueue_cancellable(): q = WorkQueue() # No items, blocks f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # Cancel the get task, waiter cleaned up await cancel_task(f) assert not q._waiting # No items, blocks f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.001) assert not done # Cancel after a put, item still available q.put("foo") await cancel_task(f) assert await q.get() == "foo" @pytest.mark.asyncio async def test_workqueue_put_after(): q = WorkQueue() # Fine if already enqueued q.put("foo") q.put_after("foo", 0.001) assert len(q._queue) == 1 assert q._timers assert await q.get() == "foo" # Cannot concurrently process "foo", even though it's scheduled f = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait([f], timeout=0.005) assert not done # But after marking done, can continue processing q.task_done("foo") assert q._queue res = await f assert res == "foo" @pytest.mark.asyncio async def test_workqueue_put_after_reschedules(): q = WorkQueue() q.put_after("foo", 0.1) _, when = q._timers["foo"] # Scheduling after is no-op q.put_after("foo", 0.5) assert len(q._queue) == 0 assert len(q._timers) == 1 assert q._timers["foo"][1] == when # Scheduling before reschedules q.put_after("foo", 0.005) assert len(q._queue) == 0 assert len(q._timers) == 1 assert q._timers["foo"][1] < when assert await q.get() == "foo" q.task_done("foo") # Scheduling at 0 avoids timer creation q.put_after("foo", 0) assert not q._timers assert q._queue assert await q.get() == "foo" @pytest.mark.asyncio async def test_workqueue_put_backoff(): q = WorkQueue() q.put_backoff("foo") assert q.failures("foo") == 1 assert q.failures("bar") == 0 assert await q.get() == "foo" q.task_done("foo") assert q.failures("foo") == 1 q.reset_backoff("foo") assert q.failures("foo") == 0 @pytest.mark.asyncio async def test_workqueue_close(): q = WorkQueue() q.put("foo") q.close() with pytest.raises(WorkQueueClosed): await q.get() assert q.closed q = WorkQueue() fs = [asyncio.ensure_future(q.get()) for _ in range(3)] done, pending = await asyncio.wait(fs, timeout=0.001) assert not done q.close() for f in fs: with pytest.raises(WorkQueueClosed): await f
0.64579
0.576959
import glfw from OpenGL.GL import * from OpenGL.GL.shaders import compileProgram, compileShader import numpy as np vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec3 a_color; out vec3 v_color; void main() { gl_Position = vec4(a_position, 1.0); v_color = a_color; } """ fragment_src = """ # version 330 in vec3 v_color; out vec4 out_color; void main() { out_color = vec4(v_color, 1.0); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") # creating the window window = glfw.create_window(1280, 720, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 400, 200) # make the context current glfw.make_context_current(window) # okay so the vertices position and the colour values are all here # - the first three values in each row are the position of the vertices # - the second three values in each row are the colour of that vertex # - each value is 4 bits! vertices = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5, 0.0, 1.0, 1.0, 1.0, ] vertices = np.array(vertices, dtype=np.float32) # creating the shader program shader = compileProgram( compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER), ) # create buffer, bind buffer and send data to buffer VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) # this is for position (location = 0) glEnableVertexAttribArray(0) # so here the 24 dictates how many bits it jumps from one reading of the position to the next # - in this case it is 24 bc theres 6 values per row, so 6*4 = 24 and each of the position values are the first three vals of each row # - the ctypes = 0 specifies which index of each row (every 24 bits) it starts on, it is zero bc first three are position # - the one above is offset!!!!!!!!! glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) # this is for colour (location = 1) glEnableVertexAttribArray(1) # the same thing goes here but the ctypes = 12 means it starts reading from the 4th value in each row (12/4 = 3, next one is 4) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) # draws the actual thing :D glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
py_src/Test(ing)/Chris_test.py
import glfw from OpenGL.GL import * from OpenGL.GL.shaders import compileProgram, compileShader import numpy as np vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec3 a_color; out vec3 v_color; void main() { gl_Position = vec4(a_position, 1.0); v_color = a_color; } """ fragment_src = """ # version 330 in vec3 v_color; out vec4 out_color; void main() { out_color = vec4(v_color, 1.0); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") # creating the window window = glfw.create_window(1280, 720, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 400, 200) # make the context current glfw.make_context_current(window) # okay so the vertices position and the colour values are all here # - the first three values in each row are the position of the vertices # - the second three values in each row are the colour of that vertex # - each value is 4 bits! vertices = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5, 0.0, 1.0, 1.0, 1.0, ] vertices = np.array(vertices, dtype=np.float32) # creating the shader program shader = compileProgram( compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER), ) # create buffer, bind buffer and send data to buffer VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) # this is for position (location = 0) glEnableVertexAttribArray(0) # so here the 24 dictates how many bits it jumps from one reading of the position to the next # - in this case it is 24 bc theres 6 values per row, so 6*4 = 24 and each of the position values are the first three vals of each row # - the ctypes = 0 specifies which index of each row (every 24 bits) it starts on, it is zero bc first three are position # - the one above is offset!!!!!!!!! glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) # this is for colour (location = 1) glEnableVertexAttribArray(1) # the same thing goes here but the ctypes = 12 means it starts reading from the 4th value in each row (12/4 = 3, next one is 4) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) # draws the actual thing :D glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
0.405213
0.271481
# Standard library modules. import collections import importlib import os # External dependencies. from humanfriendly import concatenate, format, parse_path, pluralize from pkg_resources import iter_entry_points from property_manager import lazy_property, mutable_property from sqlalchemy import func from update_dotdee import ConfigLoader from verboselogs import VerboseLogger # Modules included in our package. from chat_archive.backends import ChatArchiveBackend from chat_archive.database import SchemaManager from chat_archive.models import Account, Base, Contact, Conversation, EmailAddress, Message from chat_archive.utils import get_full_name DEFAULT_ACCOUNT_NAME = "default" """The name of the default account (a string).""" # Semi-standard package versioning. __version__ = "4.0.3" # Initialize a logger for this module. logger = VerboseLogger(__name__) class ChatArchive(SchemaManager): """Python API for the `chat-archive` program.""" @property def alembic_directory(self): """ The pathname of the directory containing Alembic migration scripts (a string). The value of this property is computed at runtime based on the value of ``__file__`` inside of the ``chat_archive/__init__.py`` module. """ return os.path.join(os.path.dirname(__file__), "alembic") @lazy_property def backends(self): """ A dictionary of available backends (names and dotted paths). >>> from chat_archive import ChatArchive >>> archive = ChatArchive() >>> print(archive.backends) {'gtalk': 'chat_archive.backends.gtalk', 'hangouts': 'chat_archive.backends.hangouts', 'slack': 'chat_archive.backends.slack', 'telegram': 'chat_archive.backends.telegram'} """ return dict((ep.name, ep.module_name) for ep in iter_entry_points("chat_archive.backends")) @lazy_property def config(self): """A dictionary with general user defined configuration options.""" if "chat-archive" in self.config_loader.section_names: return self.config_loader.get_options("chat-archive") return {} @lazy_property def config_loader(self): r""" A :class:`~update_dotdee.ConfigLoader` object that provides access to the configuration. .. [[[cog .. from update_dotdee import inject_documentation .. inject_documentation(program_name='chat-archive') .. ]]] Configuration files are text files in the subset of `ini syntax`_ supported by Python's configparser_ module. They can be located in the following places: ========= ========================== =============================== Directory Main configuration file Modular configuration files ========= ========================== =============================== /etc /etc/chat-archive.ini /etc/chat-archive.d/\*.ini ~ ~/.chat-archive.ini ~/.chat-archive.d/\*.ini ~/.config ~/.config/chat-archive.ini ~/.config/chat-archive.d/\*.ini ========= ========================== =============================== The available configuration files are loaded in the order given above, so that user specific configuration files override system wide configuration files. .. _configparser: https://docs.python.org/3/library/configparser.html .. _ini syntax: https://en.wikipedia.org/wiki/INI_file .. [[[end]]] """ config = ConfigLoader(program_name="chat-archive") if os.name == "nt": updir = os.environ.get("USERPROFILE") if updir: config.base_directories += (updir,) return config @property def declarative_base(self): """The base class for declarative models defined using SQLAlchemy_.""" return Base @mutable_property(cached=True) def data_directory(self): """ The pathname of the directory where data files are stored (a string). The environment variable ``$CHAT_ARCHIVE_DIRECTORY`` can be used to set the value of this property. When the environment variable isn't set the default value ``~/.local/share/chat-archive`` is used (where ``~`` is expanded to the profile directory of the current user). """ return parse_path(os.environ.get("CHAT_ARCHIVE_DIRECTORY", "~/.local/share/chat-archive")) @mutable_property def database_file(self): """ The absolute pathname of the SQLite_ database file (a string). This defaults to ``~/.local/share/chat-archive/database.sqlite3`` (with ``~`` expanded to the home directory of the current user) based on :attr:`data_directory`. .. _SQLite: https://sqlite.org/ """ return os.path.join(self.data_directory, "database.sqlite3") @mutable_property def force(self): """ Retry synchronization of conversations where errors were previously encountered (a boolean, defaults to :data:`False`). """ return False @lazy_property def import_stats(self): """Statistics about objects imported by backends (a :class:`BackendStats` object).""" return BackendStats() @property def num_contacts(self): """The total number of chat contacts in the local archive (a number).""" return self.session.query(func.count(Contact.id)).scalar() @property def num_conversations(self): """The total number of chat conversations in the local archive (a number).""" return self.session.query(func.count(Conversation.id)).scalar() @property def num_html_messages(self): """The total number of chat messages with HTML formatting in the local archive (a number).""" return self.session.query(func.count(Message.id)).filter(Message.html != None).scalar() @property def num_messages(self): """The total number of chat messages in the local archive (a number).""" return self.session.query(func.count(Message.id)).scalar() @lazy_property def operator_name(self): """ The full name of the person using the `chat-archive` program (a string or :data:`None`). The value of :attr:`operator_name` is used to address the operator of the `chat-archive` program in first person instead of third person. You can change the value in the configuration file: .. code-block:: ini [chat-archive] operator-name = ... The default value in case none has been specified in the configuration file is taken from ``/etc/passwd`` using :func:`.get_full_name()`. """ value = self.config.get("my-name") if not value: value = get_full_name() return value def commit_changes(self): """Show import statistics when committing database changes to disk.""" # Show import statistics just before every commit, to give the # operator something nice to look at while they're waiting 😇. self.import_stats.show() # Commit database changes to disk (and possibly save profile data). return super(ChatArchive, self).commit_changes() def get_accounts_for_backend(self, backend_name): """Select the configured and/or previously synchronized account names for the given backend.""" from_config = set(self.get_accounts_from_config(backend_name)) from_database = set(self.get_accounts_from_database(backend_name)) return sorted(from_config | from_database) def get_accounts_from_database(self, backend_name): """Get the names of the accounts that are already in the database for the given backend.""" return [a.name for a in self.session.query(Account).filter(Account.backend == backend_name)] def get_accounts_from_config(self, backend_name): """Get the names of the accounts configured for the given backend in the configuration file.""" for section_name in self.config_loader.section_names: configured_backend, configured_account = self.parse_account_expression(section_name) if backend_name == configured_backend: yield configured_account or DEFAULT_ACCOUNT_NAME def get_backend_name(self, backend_name): """Get a human friendly name for the given backend.""" module = self.load_backend_module(backend_name) return getattr(module, "FRIENDLY_NAME", backend_name) def get_backends_and_accounts(self, *backends): """Select backends and accounts to synchronize.""" if backends: for expression in backends: backend_name, account_name = self.parse_account_expression(expression) if backend_name and account_name: # Synchronize the given (backend, account) pair. yield backend_name, account_name else: # Synchronize all accounts for the given backend. for account_name in self.get_accounts_for_backend(backend_name): yield backend_name, account_name else: # Synchronize all accounts for all backends. for backend_name in sorted(self.backends): for account_name in self.get_accounts_for_backend(backend_name): yield backend_name, account_name def initialize_backend(self, backend_name, account_name): """ Load a chat archive backend module. :param backend_name: The name of the backend (one of the strings 'gtalk', 'hangouts', 'slack' or 'telegram'). :param account_name: The name of the account (a string). :returns: A :class:`~chat_archive.backends.ChatArchiveBackend` object. :raises: :exc:`Exception` when the backend doesn't define a subclass of :class:`~chat_archive.backends.ChatArchiveBackend`. """ module = self.load_backend_module(backend_name) for value in module.__dict__.values(): if isinstance(value, type) and issubclass(value, ChatArchiveBackend) and value is not ChatArchiveBackend: return value( account_name=account_name, archive=self, backend_name=backend_name, stats=self.import_stats ) msg = "Failed to locate backend class! (%s)" raise Exception(msg % backend_name) def is_operator(self, contact): """Check whether the full name of the given contact matches :attr:`operator_name`.""" return self.operator_name and contact.full_name == self.operator_name def load_backend_module(self, backend_name): """ Load a chat archive backend module. :param backend_name: The name of the backend (one of the strings 'gtalk', 'hangouts', 'slack' or 'telegram'). :returns: The loaded module. """ dotted_path = self.backends[backend_name] logger.verbose("Importing %s backend module: %s", backend_name, dotted_path) return importlib.import_module(dotted_path) def parse_account_expression(self, value): """ Parse a ``backend:account`` expression. :param value: The ``backend:account`` expression (a string). :returns: A tuple with two values: 1. The name of a backend (a string). 2. The name of an account (a string, possibly empty). """ backend_name, _, account_name = value.partition(":") return backend_name, account_name def search_messages(self, keywords): """Search the chat messages in the local archive for the given keyword(s).""" query = ( self.session.query(Message) .join(Conversation) .join(Account) .outerjoin((Contact, Contact.id == Message.sender_id)) .outerjoin((EmailAddress, Contact.email_addresses)) ) for kw in keywords: search_term = format(u"%{kw}%", kw=kw) query = query.filter( Account.backend.like(search_term) | Account.name.like(search_term) | Conversation.name.like(search_term) | Contact.full_name.like(search_term) | EmailAddress.value.like(search_term) | Message.timestamp.like(search_term) | Message.text.like(search_term) ) return query.order_by(Message.timestamp) def synchronize(self, *backends): """ Download new chat messages. :param backends: Any positional arguments limit the synchronization to backends whose name matches one of the strings provided as positional arguments. If the name of a backend contains a colon the name is split into two: 1. The backend name. 2. An account name. This way one backend can synchronize multiple named accounts into the same local database without causing confusion during synchronization about which conversations, contacts and messages belong to which account. """ # Synchronize the selected (backend, account) pairs. for backend_name, account_name in self.get_backends_and_accounts(*backends): # Provide backends their own import statistics without losing # aggregate statistics collected about all backends together. with self.import_stats: logger.info( "Synchronizing %s messages in %r account ..", self.get_backend_name(backend_name), account_name ) self.initialize_backend(backend_name, account_name).synchronize() # Commit any outstanding database changes. self.commit_changes() class BackendStats(object): """Statistics about chat message synchronization backends.""" def __init__(self): """Initialize a :class:`BackendStats` object.""" object.__setattr__(self, "stack", [collections.defaultdict(int)]) def __enter__(self): """Alias for :attr:`push()`.""" self.push() def __exit__(self, exc_type=None, exc_value=None, traceback=None): """Alias for :attr:`pop()`.""" self.pop() def __getattr__(self, name): """Get the value of a counter from the current scope.""" return self.scope[name] def __setattr__(self, name, value): """Set the value of a counter in the current scope.""" self.scope[name] = value def pop(self): """Remove the inner scope and merge its counters into the outer scope.""" counters = self.stack.pop(-1) for name, value in counters.items(): self.scope[name] += value def push(self): """Create a new inner scope with all counters reset to zero.""" self.stack.append(collections.defaultdict(int)) def show(self): """Show statistics about imported conversations, messages, contacts, etc.""" additions = [] if self.conversations_added > 0: additions.append(pluralize(self.conversations_added, "conversation")) if self.messages_added > 0: additions.append(pluralize(self.messages_added, "message")) if self.contacts_added > 0: additions.append(pluralize(self.contacts_added, "contact")) if self.email_addresses_added > 0: additions.append(pluralize(self.contacts_added, "email address", "email addresses")) if self.telephone_numbers_added > 0: additions.append(pluralize(self.telephone_numbers_added, "telephone number")) if additions: logger.info("Imported %s.", concatenate(additions)) @property def scope(self): """The current scope (a :class:`collections.defaultdict` object).""" return self.stack[-1]
chat_archive/__init__.py
# Standard library modules. import collections import importlib import os # External dependencies. from humanfriendly import concatenate, format, parse_path, pluralize from pkg_resources import iter_entry_points from property_manager import lazy_property, mutable_property from sqlalchemy import func from update_dotdee import ConfigLoader from verboselogs import VerboseLogger # Modules included in our package. from chat_archive.backends import ChatArchiveBackend from chat_archive.database import SchemaManager from chat_archive.models import Account, Base, Contact, Conversation, EmailAddress, Message from chat_archive.utils import get_full_name DEFAULT_ACCOUNT_NAME = "default" """The name of the default account (a string).""" # Semi-standard package versioning. __version__ = "4.0.3" # Initialize a logger for this module. logger = VerboseLogger(__name__) class ChatArchive(SchemaManager): """Python API for the `chat-archive` program.""" @property def alembic_directory(self): """ The pathname of the directory containing Alembic migration scripts (a string). The value of this property is computed at runtime based on the value of ``__file__`` inside of the ``chat_archive/__init__.py`` module. """ return os.path.join(os.path.dirname(__file__), "alembic") @lazy_property def backends(self): """ A dictionary of available backends (names and dotted paths). >>> from chat_archive import ChatArchive >>> archive = ChatArchive() >>> print(archive.backends) {'gtalk': 'chat_archive.backends.gtalk', 'hangouts': 'chat_archive.backends.hangouts', 'slack': 'chat_archive.backends.slack', 'telegram': 'chat_archive.backends.telegram'} """ return dict((ep.name, ep.module_name) for ep in iter_entry_points("chat_archive.backends")) @lazy_property def config(self): """A dictionary with general user defined configuration options.""" if "chat-archive" in self.config_loader.section_names: return self.config_loader.get_options("chat-archive") return {} @lazy_property def config_loader(self): r""" A :class:`~update_dotdee.ConfigLoader` object that provides access to the configuration. .. [[[cog .. from update_dotdee import inject_documentation .. inject_documentation(program_name='chat-archive') .. ]]] Configuration files are text files in the subset of `ini syntax`_ supported by Python's configparser_ module. They can be located in the following places: ========= ========================== =============================== Directory Main configuration file Modular configuration files ========= ========================== =============================== /etc /etc/chat-archive.ini /etc/chat-archive.d/\*.ini ~ ~/.chat-archive.ini ~/.chat-archive.d/\*.ini ~/.config ~/.config/chat-archive.ini ~/.config/chat-archive.d/\*.ini ========= ========================== =============================== The available configuration files are loaded in the order given above, so that user specific configuration files override system wide configuration files. .. _configparser: https://docs.python.org/3/library/configparser.html .. _ini syntax: https://en.wikipedia.org/wiki/INI_file .. [[[end]]] """ config = ConfigLoader(program_name="chat-archive") if os.name == "nt": updir = os.environ.get("USERPROFILE") if updir: config.base_directories += (updir,) return config @property def declarative_base(self): """The base class for declarative models defined using SQLAlchemy_.""" return Base @mutable_property(cached=True) def data_directory(self): """ The pathname of the directory where data files are stored (a string). The environment variable ``$CHAT_ARCHIVE_DIRECTORY`` can be used to set the value of this property. When the environment variable isn't set the default value ``~/.local/share/chat-archive`` is used (where ``~`` is expanded to the profile directory of the current user). """ return parse_path(os.environ.get("CHAT_ARCHIVE_DIRECTORY", "~/.local/share/chat-archive")) @mutable_property def database_file(self): """ The absolute pathname of the SQLite_ database file (a string). This defaults to ``~/.local/share/chat-archive/database.sqlite3`` (with ``~`` expanded to the home directory of the current user) based on :attr:`data_directory`. .. _SQLite: https://sqlite.org/ """ return os.path.join(self.data_directory, "database.sqlite3") @mutable_property def force(self): """ Retry synchronization of conversations where errors were previously encountered (a boolean, defaults to :data:`False`). """ return False @lazy_property def import_stats(self): """Statistics about objects imported by backends (a :class:`BackendStats` object).""" return BackendStats() @property def num_contacts(self): """The total number of chat contacts in the local archive (a number).""" return self.session.query(func.count(Contact.id)).scalar() @property def num_conversations(self): """The total number of chat conversations in the local archive (a number).""" return self.session.query(func.count(Conversation.id)).scalar() @property def num_html_messages(self): """The total number of chat messages with HTML formatting in the local archive (a number).""" return self.session.query(func.count(Message.id)).filter(Message.html != None).scalar() @property def num_messages(self): """The total number of chat messages in the local archive (a number).""" return self.session.query(func.count(Message.id)).scalar() @lazy_property def operator_name(self): """ The full name of the person using the `chat-archive` program (a string or :data:`None`). The value of :attr:`operator_name` is used to address the operator of the `chat-archive` program in first person instead of third person. You can change the value in the configuration file: .. code-block:: ini [chat-archive] operator-name = ... The default value in case none has been specified in the configuration file is taken from ``/etc/passwd`` using :func:`.get_full_name()`. """ value = self.config.get("my-name") if not value: value = get_full_name() return value def commit_changes(self): """Show import statistics when committing database changes to disk.""" # Show import statistics just before every commit, to give the # operator something nice to look at while they're waiting 😇. self.import_stats.show() # Commit database changes to disk (and possibly save profile data). return super(ChatArchive, self).commit_changes() def get_accounts_for_backend(self, backend_name): """Select the configured and/or previously synchronized account names for the given backend.""" from_config = set(self.get_accounts_from_config(backend_name)) from_database = set(self.get_accounts_from_database(backend_name)) return sorted(from_config | from_database) def get_accounts_from_database(self, backend_name): """Get the names of the accounts that are already in the database for the given backend.""" return [a.name for a in self.session.query(Account).filter(Account.backend == backend_name)] def get_accounts_from_config(self, backend_name): """Get the names of the accounts configured for the given backend in the configuration file.""" for section_name in self.config_loader.section_names: configured_backend, configured_account = self.parse_account_expression(section_name) if backend_name == configured_backend: yield configured_account or DEFAULT_ACCOUNT_NAME def get_backend_name(self, backend_name): """Get a human friendly name for the given backend.""" module = self.load_backend_module(backend_name) return getattr(module, "FRIENDLY_NAME", backend_name) def get_backends_and_accounts(self, *backends): """Select backends and accounts to synchronize.""" if backends: for expression in backends: backend_name, account_name = self.parse_account_expression(expression) if backend_name and account_name: # Synchronize the given (backend, account) pair. yield backend_name, account_name else: # Synchronize all accounts for the given backend. for account_name in self.get_accounts_for_backend(backend_name): yield backend_name, account_name else: # Synchronize all accounts for all backends. for backend_name in sorted(self.backends): for account_name in self.get_accounts_for_backend(backend_name): yield backend_name, account_name def initialize_backend(self, backend_name, account_name): """ Load a chat archive backend module. :param backend_name: The name of the backend (one of the strings 'gtalk', 'hangouts', 'slack' or 'telegram'). :param account_name: The name of the account (a string). :returns: A :class:`~chat_archive.backends.ChatArchiveBackend` object. :raises: :exc:`Exception` when the backend doesn't define a subclass of :class:`~chat_archive.backends.ChatArchiveBackend`. """ module = self.load_backend_module(backend_name) for value in module.__dict__.values(): if isinstance(value, type) and issubclass(value, ChatArchiveBackend) and value is not ChatArchiveBackend: return value( account_name=account_name, archive=self, backend_name=backend_name, stats=self.import_stats ) msg = "Failed to locate backend class! (%s)" raise Exception(msg % backend_name) def is_operator(self, contact): """Check whether the full name of the given contact matches :attr:`operator_name`.""" return self.operator_name and contact.full_name == self.operator_name def load_backend_module(self, backend_name): """ Load a chat archive backend module. :param backend_name: The name of the backend (one of the strings 'gtalk', 'hangouts', 'slack' or 'telegram'). :returns: The loaded module. """ dotted_path = self.backends[backend_name] logger.verbose("Importing %s backend module: %s", backend_name, dotted_path) return importlib.import_module(dotted_path) def parse_account_expression(self, value): """ Parse a ``backend:account`` expression. :param value: The ``backend:account`` expression (a string). :returns: A tuple with two values: 1. The name of a backend (a string). 2. The name of an account (a string, possibly empty). """ backend_name, _, account_name = value.partition(":") return backend_name, account_name def search_messages(self, keywords): """Search the chat messages in the local archive for the given keyword(s).""" query = ( self.session.query(Message) .join(Conversation) .join(Account) .outerjoin((Contact, Contact.id == Message.sender_id)) .outerjoin((EmailAddress, Contact.email_addresses)) ) for kw in keywords: search_term = format(u"%{kw}%", kw=kw) query = query.filter( Account.backend.like(search_term) | Account.name.like(search_term) | Conversation.name.like(search_term) | Contact.full_name.like(search_term) | EmailAddress.value.like(search_term) | Message.timestamp.like(search_term) | Message.text.like(search_term) ) return query.order_by(Message.timestamp) def synchronize(self, *backends): """ Download new chat messages. :param backends: Any positional arguments limit the synchronization to backends whose name matches one of the strings provided as positional arguments. If the name of a backend contains a colon the name is split into two: 1. The backend name. 2. An account name. This way one backend can synchronize multiple named accounts into the same local database without causing confusion during synchronization about which conversations, contacts and messages belong to which account. """ # Synchronize the selected (backend, account) pairs. for backend_name, account_name in self.get_backends_and_accounts(*backends): # Provide backends their own import statistics without losing # aggregate statistics collected about all backends together. with self.import_stats: logger.info( "Synchronizing %s messages in %r account ..", self.get_backend_name(backend_name), account_name ) self.initialize_backend(backend_name, account_name).synchronize() # Commit any outstanding database changes. self.commit_changes() class BackendStats(object): """Statistics about chat message synchronization backends.""" def __init__(self): """Initialize a :class:`BackendStats` object.""" object.__setattr__(self, "stack", [collections.defaultdict(int)]) def __enter__(self): """Alias for :attr:`push()`.""" self.push() def __exit__(self, exc_type=None, exc_value=None, traceback=None): """Alias for :attr:`pop()`.""" self.pop() def __getattr__(self, name): """Get the value of a counter from the current scope.""" return self.scope[name] def __setattr__(self, name, value): """Set the value of a counter in the current scope.""" self.scope[name] = value def pop(self): """Remove the inner scope and merge its counters into the outer scope.""" counters = self.stack.pop(-1) for name, value in counters.items(): self.scope[name] += value def push(self): """Create a new inner scope with all counters reset to zero.""" self.stack.append(collections.defaultdict(int)) def show(self): """Show statistics about imported conversations, messages, contacts, etc.""" additions = [] if self.conversations_added > 0: additions.append(pluralize(self.conversations_added, "conversation")) if self.messages_added > 0: additions.append(pluralize(self.messages_added, "message")) if self.contacts_added > 0: additions.append(pluralize(self.contacts_added, "contact")) if self.email_addresses_added > 0: additions.append(pluralize(self.contacts_added, "email address", "email addresses")) if self.telephone_numbers_added > 0: additions.append(pluralize(self.telephone_numbers_added, "telephone number")) if additions: logger.info("Imported %s.", concatenate(additions)) @property def scope(self): """The current scope (a :class:`collections.defaultdict` object).""" return self.stack[-1]
0.792143
0.185504
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 from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='acquisition_task.proto', package='ts_mon.proto', serialized_pb=_b('\n\x16\x61\x63quisition_task.proto\x12\x0cts_mon.proto\"\xd3\x01\n\x04Task\x12\x19\n\x11proxy_environment\x18\x05 \x01(\t\x12\x18\n\x10\x61\x63quisition_name\x18\n \x01(\t\x12\x14\n\x0cservice_name\x18\x14 \x01(\t\x12\x10\n\x08job_name\x18\x1e \x01(\t\x12\x13\n\x0b\x64\x61ta_center\x18( \x01(\t\x12\x11\n\thost_name\x18\x32 \x01(\t\x12\x10\n\x08task_num\x18< \x01(\x05\x12\x12\n\nproxy_zone\x18\x46 \x01(\t\" \n\x06TypeId\x12\x16\n\x0fMESSAGE_TYPE_ID\x10\xd5\x9d\x9e\x10') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _TASK_TYPEID = _descriptor.EnumDescriptor( name='TypeId', full_name='ts_mon.proto.Task.TypeId', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='MESSAGE_TYPE_ID', index=0, number=34049749, options=None, type=None), ], containing_type=None, options=None, serialized_start=220, serialized_end=252, ) _sym_db.RegisterEnumDescriptor(_TASK_TYPEID) _TASK = _descriptor.Descriptor( name='Task', full_name='ts_mon.proto.Task', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proxy_environment', full_name='ts_mon.proto.Task.proxy_environment', index=0, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='acquisition_name', full_name='ts_mon.proto.Task.acquisition_name', index=1, number=10, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='service_name', full_name='ts_mon.proto.Task.service_name', index=2, number=20, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='job_name', full_name='ts_mon.proto.Task.job_name', index=3, number=30, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data_center', full_name='ts_mon.proto.Task.data_center', index=4, number=40, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='host_name', full_name='ts_mon.proto.Task.host_name', index=5, number=50, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='task_num', full_name='ts_mon.proto.Task.task_num', index=6, number=60, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='proxy_zone', full_name='ts_mon.proto.Task.proxy_zone', index=7, number=70, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TASK_TYPEID, ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=41, serialized_end=252, ) _TASK_TYPEID.containing_type = _TASK DESCRIPTOR.message_types_by_name['Task'] = _TASK Task = _reflection.GeneratedProtocolMessageType('Task', (_message.Message,), dict( DESCRIPTOR = _TASK, __module__ = 'acquisition_task_pb2' # @@protoc_insertion_point(class_scope:ts_mon.proto.Task) )) _sym_db.RegisterMessage(Task) # @@protoc_insertion_point(module_scope)
third_party/gae_ts_mon/gae_ts_mon/protos/acquisition_task_pb2.py
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 from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='acquisition_task.proto', package='ts_mon.proto', serialized_pb=_b('\n\x16\x61\x63quisition_task.proto\x12\x0cts_mon.proto\"\xd3\x01\n\x04Task\x12\x19\n\x11proxy_environment\x18\x05 \x01(\t\x12\x18\n\x10\x61\x63quisition_name\x18\n \x01(\t\x12\x14\n\x0cservice_name\x18\x14 \x01(\t\x12\x10\n\x08job_name\x18\x1e \x01(\t\x12\x13\n\x0b\x64\x61ta_center\x18( \x01(\t\x12\x11\n\thost_name\x18\x32 \x01(\t\x12\x10\n\x08task_num\x18< \x01(\x05\x12\x12\n\nproxy_zone\x18\x46 \x01(\t\" \n\x06TypeId\x12\x16\n\x0fMESSAGE_TYPE_ID\x10\xd5\x9d\x9e\x10') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _TASK_TYPEID = _descriptor.EnumDescriptor( name='TypeId', full_name='ts_mon.proto.Task.TypeId', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='MESSAGE_TYPE_ID', index=0, number=34049749, options=None, type=None), ], containing_type=None, options=None, serialized_start=220, serialized_end=252, ) _sym_db.RegisterEnumDescriptor(_TASK_TYPEID) _TASK = _descriptor.Descriptor( name='Task', full_name='ts_mon.proto.Task', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proxy_environment', full_name='ts_mon.proto.Task.proxy_environment', index=0, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='acquisition_name', full_name='ts_mon.proto.Task.acquisition_name', index=1, number=10, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='service_name', full_name='ts_mon.proto.Task.service_name', index=2, number=20, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='job_name', full_name='ts_mon.proto.Task.job_name', index=3, number=30, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data_center', full_name='ts_mon.proto.Task.data_center', index=4, number=40, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='host_name', full_name='ts_mon.proto.Task.host_name', index=5, number=50, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='task_num', full_name='ts_mon.proto.Task.task_num', index=6, number=60, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='proxy_zone', full_name='ts_mon.proto.Task.proxy_zone', index=7, number=70, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ _TASK_TYPEID, ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=41, serialized_end=252, ) _TASK_TYPEID.containing_type = _TASK DESCRIPTOR.message_types_by_name['Task'] = _TASK Task = _reflection.GeneratedProtocolMessageType('Task', (_message.Message,), dict( DESCRIPTOR = _TASK, __module__ = 'acquisition_task_pb2' # @@protoc_insertion_point(class_scope:ts_mon.proto.Task) )) _sym_db.RegisterMessage(Task) # @@protoc_insertion_point(module_scope)
0.202601
0.112527
from grr.lib import flags from grr.lib import rdfvalue from grr.lib.rdfvalues import flows as rdf_flows from grr.server.grr_response_server import data_store from grr.server.grr_response_server.hunts import results as hunts_results from grr.test_lib import aff4_test_lib from grr.test_lib import test_lib class ResultTest(aff4_test_lib.AFF4ObjectTest): def testEmptyQueue(self): # Create and empty HuntResultCollection. collection_urn = rdfvalue.RDFURN("aff4:/testEmptyQueue/collection") hunts_results.HuntResultCollection(collection_urn) # The queue starts empty, and returns no notifications. results = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(None, results[0]) self.assertEqual([], results[1]) def testNotificationsContainTimestamps(self): collection_urn = rdfvalue.RDFURN( "aff4:/testNotificationsContainTimestamps/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) # If we claim results, we should get all 5. results = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn, results[0]) self.assertEqual(5, len(results[1])) # Read all the results, using the contained (ts, suffix) pairs. values_read = [] collection = hunts_results.HuntResultCollection(collection_urn) for message in collection.MultiResolve( [r.value.ResultRecord() for r in results[1]]): values_read.append(message.request_id) self.assertEqual(sorted(values_read), range(5)) def testNotificationClaimsTimeout(self): collection_urn = rdfvalue.RDFURN( "aff4:/testNotificationClaimsTimeout/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(5, len(results_1[1])) # Check that we have a claim - that another read returns nothing. results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(0, len(results_2[1])) # Push time forward past the default claim timeout, then we should be able # to re-read (and re-claim). with test_lib.FakeTime(rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("45m")): results_3 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(results_3, results_1) def testDelete(self): collection_urn = rdfvalue.RDFURN("aff4:/testDelete/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(5, len(results_1[1])) hunts_results.HuntResultQueue.DeleteNotifications( results_1[1], token=self.token) # Push time forward past the default claim timeout, then we should still # read nothing. with test_lib.FakeTime(rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("45m")): results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(0, len(results_2[1])) def testNotificationsSplitByCollection(self): # Create two HuntResultCollections. collection_urn_1 = rdfvalue.RDFURN( "aff4:/testNotificationsSplitByCollection/collection_1") collection_urn_2 = rdfvalue.RDFURN( "aff4:/testNotificationsSplitByCollection/collection_2") # Add 100 records to each collection, in an interleaved manner. with data_store.DB.GetMutationPool() as pool: for i in range(100): hunts_results.HuntResultCollection.StaticAdd( collection_urn_1, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) hunts_results.HuntResultCollection.StaticAdd( collection_urn_2, rdf_flows.GrrMessage(request_id=100 + i), mutation_pool=pool) # The first result was added to collection 1, so this should return # all 100 results for collection 1. results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn_1, results_1[0]) self.assertEqual(100, len(results_1[1])) # The first call claimed all the notifications for collection 1. These are # claimed, so another call should skip them and give all notifications for # collection 2. results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn_2, results_2[0]) self.assertEqual(100, len(results_2[1])) values_read = [] collection_2 = hunts_results.HuntResultCollection(collection_urn_2) for message in collection_2.MultiResolve( [r.value.ResultRecord() for r in results_2[1]]): values_read.append(message.request_id) self.assertEqual(sorted(values_read), range(100, 200)) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
grr/server/grr_response_server/hunts/results_test.py
from grr.lib import flags from grr.lib import rdfvalue from grr.lib.rdfvalues import flows as rdf_flows from grr.server.grr_response_server import data_store from grr.server.grr_response_server.hunts import results as hunts_results from grr.test_lib import aff4_test_lib from grr.test_lib import test_lib class ResultTest(aff4_test_lib.AFF4ObjectTest): def testEmptyQueue(self): # Create and empty HuntResultCollection. collection_urn = rdfvalue.RDFURN("aff4:/testEmptyQueue/collection") hunts_results.HuntResultCollection(collection_urn) # The queue starts empty, and returns no notifications. results = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(None, results[0]) self.assertEqual([], results[1]) def testNotificationsContainTimestamps(self): collection_urn = rdfvalue.RDFURN( "aff4:/testNotificationsContainTimestamps/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) # If we claim results, we should get all 5. results = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn, results[0]) self.assertEqual(5, len(results[1])) # Read all the results, using the contained (ts, suffix) pairs. values_read = [] collection = hunts_results.HuntResultCollection(collection_urn) for message in collection.MultiResolve( [r.value.ResultRecord() for r in results[1]]): values_read.append(message.request_id) self.assertEqual(sorted(values_read), range(5)) def testNotificationClaimsTimeout(self): collection_urn = rdfvalue.RDFURN( "aff4:/testNotificationClaimsTimeout/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(5, len(results_1[1])) # Check that we have a claim - that another read returns nothing. results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(0, len(results_2[1])) # Push time forward past the default claim timeout, then we should be able # to re-read (and re-claim). with test_lib.FakeTime(rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("45m")): results_3 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(results_3, results_1) def testDelete(self): collection_urn = rdfvalue.RDFURN("aff4:/testDelete/collection") with data_store.DB.GetMutationPool() as pool: for i in range(5): hunts_results.HuntResultCollection.StaticAdd( collection_urn, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(5, len(results_1[1])) hunts_results.HuntResultQueue.DeleteNotifications( results_1[1], token=self.token) # Push time forward past the default claim timeout, then we should still # read nothing. with test_lib.FakeTime(rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("45m")): results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(0, len(results_2[1])) def testNotificationsSplitByCollection(self): # Create two HuntResultCollections. collection_urn_1 = rdfvalue.RDFURN( "aff4:/testNotificationsSplitByCollection/collection_1") collection_urn_2 = rdfvalue.RDFURN( "aff4:/testNotificationsSplitByCollection/collection_2") # Add 100 records to each collection, in an interleaved manner. with data_store.DB.GetMutationPool() as pool: for i in range(100): hunts_results.HuntResultCollection.StaticAdd( collection_urn_1, rdf_flows.GrrMessage(request_id=i), mutation_pool=pool) hunts_results.HuntResultCollection.StaticAdd( collection_urn_2, rdf_flows.GrrMessage(request_id=100 + i), mutation_pool=pool) # The first result was added to collection 1, so this should return # all 100 results for collection 1. results_1 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn_1, results_1[0]) self.assertEqual(100, len(results_1[1])) # The first call claimed all the notifications for collection 1. These are # claimed, so another call should skip them and give all notifications for # collection 2. results_2 = hunts_results.HuntResultQueue.ClaimNotificationsForCollection( token=self.token) self.assertEqual(collection_urn_2, results_2[0]) self.assertEqual(100, len(results_2[1])) values_read = [] collection_2 = hunts_results.HuntResultCollection(collection_urn_2) for message in collection_2.MultiResolve( [r.value.ResultRecord() for r in results_2[1]]): values_read.append(message.request_id) self.assertEqual(sorted(values_read), range(100, 200)) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
0.563858
0.33516
import os import random from imutils import paths import numpy as np import pandas as pd import skimage as sk import skimage.transform from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import img_to_array, load_img from tensorflow.keras.utils import to_categorical import config def import_minimias_dataset(data_dir: str, label_encoder) -> (np.ndarray, np.ndarray): """ Import the dataset by pre-processing the images and encoding the labels. :param data_dir: Directory to the mini-MIAS images. :param label_encoder: The label encoder. :return: Two NumPy arrays, one for the processed images and one for the encoded labels. """ # Initialise variables. images = list() labels = list() # Loop over the image paths and update the data and labels lists with the pre-processed images & labels. for image_path in list(paths.list_images(data_dir)): images.append(preprocess_image(image_path)) labels.append(image_path.split(os.path.sep)[-2]) # Extract label from path. # Convert the data and labels lists to NumPy arrays. images = np.array(images, dtype="float32") # Convert images to a batch. labels = np.array(labels) # Encode labels. labels = encode_labels(labels, label_encoder) return images, labels def import_cbisddsm_training_dataset(label_encoder): """ Import the dataset getting the image paths (downloaded on BigTMP) and encoding the labels. :param label_encoder: The label encoder. :return: Two arrays, one for the image paths and one for the encoded labels. """ df = pd.read_csv("./test_mamo1/data/CBIS-DDSM/training.csv") list_IDs = df['img_path'].values labels = encode_labels(df['label'].values, label_encoder) return list_IDs, labels def preprocess_image(image_path: str) -> np.ndarray: """ Pre-processing steps: * Load the input image in grayscale mode (1 channel), * resize it to 224x224 pixels for the VGG19 CNN model, * transform it to an array format, * normalise the pixel intensities. :param image_path: The path to the image to preprocess. :return: The pre-processed image in NumPy array format. """ image = load_img(image_path, color_mode="grayscale", target_size=(config.VGG_IMG_SIZE['HEIGHT'], config.VGG_IMG_SIZE["WIDTH"])) image = img_to_array(image) image /= 255.0 return image def encode_labels(labels_list: np.ndarray, label_encoder) -> np.ndarray: """ Encode labels using one-hot encoding. :param label_encoder: The label encoder. :param labels_list: The list of labels in NumPy array format. :return: The encoded list of labels in NumPy array format. """ labels = label_encoder.fit_transform(labels_list) if label_encoder.classes_.size == 2: return labels else: return to_categorical(labels) def dataset_stratified_split(split: float, dataset: np.ndarray, labels: np.ndarray) -> \ (np.ndarray, np.ndarray, np.ndarray, np.ndarray): """ Partition the data into training and testing splits. Stratify the split to keep the same class distribution in both sets and shuffle the order to avoid having imbalanced splits. :param split: Dataset split (e.g. if 0.2 is passed, then the dataset is split in 80%/20%). :param dataset: The dataset of pre-processed images. :param labels: The list of labels. :return: the training and testing sets split in input (X) and label (Y). """ train_X, test_X, train_Y, test_Y = train_test_split(dataset, labels, test_size=split, stratify=labels, random_state=config.RANDOM_SEED, shuffle=True) return train_X, test_X, train_Y, test_Y def random_rotation(image_array: np.ndarray): """ Randomly rotate the image :param image_array: input image :return: randomly rotated image """ random_degree = random.uniform(-20, 20) return sk.transform.rotate(image_array, random_degree) def random_noise(image_array: np.ndarray): """ Add random noise to image :param image_array: input image :return: image with added random noise """ return sk.util.random_noise(image_array) def horizontal_flip(image_array: np.ndarray): """ Flip image :param image_array: input image :return: horizantally flipped image """ return image_array[:, ::-1] def generate_image_transforms(images, labels): """ oversample data by tranforming existing images :param images: input images :param labels: input labels :return: updated list of images and labels with extra transformed images and labels """ images_with_transforms = images labels_with_transforms = labels available_transforms = {'rotate': random_rotation, 'noise': random_noise, 'horizontal_flip': horizontal_flip} class_balance = get_class_balances(labels) max_count = max(class_balance) to_add = [max_count - i for i in class_balance] for i in range(len(to_add)): if int(to_add[i]) == 0: continue label = np.zeros(len(to_add)) label[i] = 1 indices = [j for j, x in enumerate(labels) if np.array_equal(x, label)] indiv_class_images = [images[j] for j in indices] for k in range(int(to_add[i])): a = create_individual_transform(indiv_class_images[k % len(indiv_class_images)], available_transforms) transformed_image = create_individual_transform(indiv_class_images[k % len(indiv_class_images)], available_transforms) transformed_image = transformed_image.reshape(1, config.VGG_IMG_SIZE['HEIGHT'], config.VGG_IMG_SIZE['WIDTH'], 1) images_with_transforms = np.append(images_with_transforms, transformed_image, axis=0) transformed_label = label.reshape(1, len(label)) labels_with_transforms = np.append(labels_with_transforms, transformed_label, axis=0) return images_with_transforms, labels_with_transforms def create_individual_transform(image: np.array, transforms: dict): """ Create transformation of an individual image :param image: input image :param transforms: the possible transforms to do on the image :return: transformed image """ num_transformations_to_apply = random.randint(1, len(transforms)) num_transforms = 0 transformed_image = None while num_transforms <= num_transformations_to_apply: key = random.choice(list(transforms)) transformed_image = transforms[key](image) num_transforms += 1 return transformed_image def get_class_balances(y_vals): """ Count occurrences of each class. :param y_vals: labels :return: array count of each class """ num_classes = len(y_vals[0]) counts = np.zeros(num_classes) for y_val in y_vals: for i in range(num_classes): counts[i] += y_val[i] return (counts.tolist())
src/data_operations/data_preprocessing.py
import os import random from imutils import paths import numpy as np import pandas as pd import skimage as sk import skimage.transform from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import img_to_array, load_img from tensorflow.keras.utils import to_categorical import config def import_minimias_dataset(data_dir: str, label_encoder) -> (np.ndarray, np.ndarray): """ Import the dataset by pre-processing the images and encoding the labels. :param data_dir: Directory to the mini-MIAS images. :param label_encoder: The label encoder. :return: Two NumPy arrays, one for the processed images and one for the encoded labels. """ # Initialise variables. images = list() labels = list() # Loop over the image paths and update the data and labels lists with the pre-processed images & labels. for image_path in list(paths.list_images(data_dir)): images.append(preprocess_image(image_path)) labels.append(image_path.split(os.path.sep)[-2]) # Extract label from path. # Convert the data and labels lists to NumPy arrays. images = np.array(images, dtype="float32") # Convert images to a batch. labels = np.array(labels) # Encode labels. labels = encode_labels(labels, label_encoder) return images, labels def import_cbisddsm_training_dataset(label_encoder): """ Import the dataset getting the image paths (downloaded on BigTMP) and encoding the labels. :param label_encoder: The label encoder. :return: Two arrays, one for the image paths and one for the encoded labels. """ df = pd.read_csv("./test_mamo1/data/CBIS-DDSM/training.csv") list_IDs = df['img_path'].values labels = encode_labels(df['label'].values, label_encoder) return list_IDs, labels def preprocess_image(image_path: str) -> np.ndarray: """ Pre-processing steps: * Load the input image in grayscale mode (1 channel), * resize it to 224x224 pixels for the VGG19 CNN model, * transform it to an array format, * normalise the pixel intensities. :param image_path: The path to the image to preprocess. :return: The pre-processed image in NumPy array format. """ image = load_img(image_path, color_mode="grayscale", target_size=(config.VGG_IMG_SIZE['HEIGHT'], config.VGG_IMG_SIZE["WIDTH"])) image = img_to_array(image) image /= 255.0 return image def encode_labels(labels_list: np.ndarray, label_encoder) -> np.ndarray: """ Encode labels using one-hot encoding. :param label_encoder: The label encoder. :param labels_list: The list of labels in NumPy array format. :return: The encoded list of labels in NumPy array format. """ labels = label_encoder.fit_transform(labels_list) if label_encoder.classes_.size == 2: return labels else: return to_categorical(labels) def dataset_stratified_split(split: float, dataset: np.ndarray, labels: np.ndarray) -> \ (np.ndarray, np.ndarray, np.ndarray, np.ndarray): """ Partition the data into training and testing splits. Stratify the split to keep the same class distribution in both sets and shuffle the order to avoid having imbalanced splits. :param split: Dataset split (e.g. if 0.2 is passed, then the dataset is split in 80%/20%). :param dataset: The dataset of pre-processed images. :param labels: The list of labels. :return: the training and testing sets split in input (X) and label (Y). """ train_X, test_X, train_Y, test_Y = train_test_split(dataset, labels, test_size=split, stratify=labels, random_state=config.RANDOM_SEED, shuffle=True) return train_X, test_X, train_Y, test_Y def random_rotation(image_array: np.ndarray): """ Randomly rotate the image :param image_array: input image :return: randomly rotated image """ random_degree = random.uniform(-20, 20) return sk.transform.rotate(image_array, random_degree) def random_noise(image_array: np.ndarray): """ Add random noise to image :param image_array: input image :return: image with added random noise """ return sk.util.random_noise(image_array) def horizontal_flip(image_array: np.ndarray): """ Flip image :param image_array: input image :return: horizantally flipped image """ return image_array[:, ::-1] def generate_image_transforms(images, labels): """ oversample data by tranforming existing images :param images: input images :param labels: input labels :return: updated list of images and labels with extra transformed images and labels """ images_with_transforms = images labels_with_transforms = labels available_transforms = {'rotate': random_rotation, 'noise': random_noise, 'horizontal_flip': horizontal_flip} class_balance = get_class_balances(labels) max_count = max(class_balance) to_add = [max_count - i for i in class_balance] for i in range(len(to_add)): if int(to_add[i]) == 0: continue label = np.zeros(len(to_add)) label[i] = 1 indices = [j for j, x in enumerate(labels) if np.array_equal(x, label)] indiv_class_images = [images[j] for j in indices] for k in range(int(to_add[i])): a = create_individual_transform(indiv_class_images[k % len(indiv_class_images)], available_transforms) transformed_image = create_individual_transform(indiv_class_images[k % len(indiv_class_images)], available_transforms) transformed_image = transformed_image.reshape(1, config.VGG_IMG_SIZE['HEIGHT'], config.VGG_IMG_SIZE['WIDTH'], 1) images_with_transforms = np.append(images_with_transforms, transformed_image, axis=0) transformed_label = label.reshape(1, len(label)) labels_with_transforms = np.append(labels_with_transforms, transformed_label, axis=0) return images_with_transforms, labels_with_transforms def create_individual_transform(image: np.array, transforms: dict): """ Create transformation of an individual image :param image: input image :param transforms: the possible transforms to do on the image :return: transformed image """ num_transformations_to_apply = random.randint(1, len(transforms)) num_transforms = 0 transformed_image = None while num_transforms <= num_transformations_to_apply: key = random.choice(list(transforms)) transformed_image = transforms[key](image) num_transforms += 1 return transformed_image def get_class_balances(y_vals): """ Count occurrences of each class. :param y_vals: labels :return: array count of each class """ num_classes = len(y_vals[0]) counts = np.zeros(num_classes) for y_val in y_vals: for i in range(num_classes): counts[i] += y_val[i] return (counts.tolist())
0.788909
0.663914
from __future__ import annotations import logging from datetime import datetime, timedelta from time import gmtime, strftime from typing import Any, Dict, Optional, Sequence, Tuple, Union from wyze_sdk.errors import WyzeRequestError from wyze_sdk.models import datetime_to_epoch from wyze_sdk.models.devices import DeviceProp from wyze_sdk.models.events import EventAlarmType from wyze_sdk.signature import RequestVerifier from .base import BaseServiceClient, WyzeResponse class ApiServiceClient(BaseServiceClient): """ Wyze api client is the wrapper on the requests to https://api.wyzecam.com """ SC = "a626948714654991afd3c0dbd7cdb901" WYZE_API_URL = "https://api.wyzecam.com/" WYZE_APP_NAME = "com.hualai" def __init__( self, token: Optional[str] = None, base_url: Optional[str] = WYZE_API_URL, app_name: str = WYZE_APP_NAME, sc: str = SC, ): super().__init__(token=token, base_url=base_url, app_name=app_name, request_verifier=RequestVerifier(signing_secret=None)) self.app_ver = self.app_name + '___' + self.app_version self.sc = sc def _get_headers( self, *, request_specific_headers: Optional[dict] ) -> Dict[str, str]: return super()._get_headers(headers=None, has_json=True, request_specific_headers=request_specific_headers) def api_call( self, api_method: str, *, http_verb: str = "POST", json: dict = {}, headers: dict = None, ) -> WyzeResponse: json['access_token'] = self.token json['app_name'] = self.app_name json['app_ver'] = self.app_ver json['app_version'] = self.app_version json['phone_id'] = self.phone_id json['phone_system_type'] = str(self.phone_type) json['sc'] = self.sc json['ts'] = self.request_verifier.clock.nonce() headers = self._get_headers( request_specific_headers={ 'Connection': 'keep-alive', } ) return super().api_call(api_method, http_verb=http_verb, data=None, params=None, json=json, headers=headers, auth=None) def refresh_token(self, *, refresh_token: str, **kwargs) -> WyzeResponse: SV_REFRESH_TOKEN = '<PASSWORD>' kwargs.update({"refresh_token": refresh_token, "sv": SV_REFRESH_TOKEN}) return self.api_call('/app/user/refresh_token', json=kwargs) def set_device_property(self, *, mac: str, model: str, pid: str, value: Any, **kwargs) -> WyzeResponse: SV_SET_DEVICE_PROPERTY = '44b6d5640c4d4978baba65c8ab9a6d6e' kwargs.update({"device_mac": mac, "device_model": model, "pid": pid, "pvalue": str(value), "sv": SV_SET_DEVICE_PROPERTY}) return self.api_call('/app/v2/device/set_property', json=kwargs) def get_device_list_property_list(self, *, device_ids: Sequence[str], target_pids: Sequence[str], **kwargs) -> WyzeResponse: SV_GET_DEVICE_LIST_PROPERTY_LIST = 'be9e90755d3445d0a4a583c8314972b6' kwargs.update({"device_list": device_ids, "target_pid_list": target_pids, "sv": SV_GET_DEVICE_LIST_PROPERTY_LIST}) return self.api_call('/app/v2/device_list/get_property_list', json=kwargs) def get_device_property_list(self, *, mac: str, model: str, target_pids: Sequence[str] = [], **kwargs) -> WyzeResponse: SV_GET_DEVICE_PROPERTY_LIST = '1df2807c63254e16a06213323fe8dec8' kwargs.update({"device_mac": mac, "device_model": model, "sv": SV_GET_DEVICE_PROPERTY_LIST}) if target_pids is not None: kwargs.update({"target_pid_list": target_pids}) return self.api_call('/app/v2/device/get_property_list', json=kwargs) def get_v1_device_info(self, *, mac: str, **kwargs) -> WyzeResponse: SV_GET_DEVICE_INFO = '90fea740c4c045f9a3084c17cee71d46' kwargs.update({"device_mac": mac, "sv": SV_GET_DEVICE_INFO}) return self.api_call('/app/device/get_device_info', json=kwargs) def get_user_info(self, **kwargs) -> WyzeResponse: SV_GET_USER_INFO = '6e054e04b7144c90af3b1281b6533492' kwargs.update({"sv": SV_GET_USER_INFO}) return self.api_call('/app/user/get_user_info', json=kwargs) def logout(self, **kwargs) -> WyzeResponse: SV_LOGOUT = '759245b61abd49128585e95f30e61add' kwargs.update({"sv": SV_LOGOUT}) return self.api_call('/app/user/logout', json=kwargs) def get_device_info(self, *, mac: str, model: str, **kwargs) -> WyzeResponse: SV_GET_DEVICE_INFO = '81d1abc794ba45a39fdd21233d621e84' kwargs.update({"device_mac": mac, "device_model": model, "sv": SV_GET_DEVICE_INFO}) return self.api_call('/app/v2/device/get_device_Info', json=kwargs) def get_object_list(self, **kwargs) -> WyzeResponse: SV_GET_DEVICE_LIST = 'c417b62d72ee44bf933054bdca183e77' kwargs.update({"sv": SV_GET_DEVICE_LIST}) return self.api_call( '/app/v2/home_page/get_object_list', json=kwargs) def get_device_timer(self, *, mac: str, action_type: int, **kwargs) -> WyzeResponse: """ "data": { "action_value": "1", "delay_time": 10800, "plan_execute_ts": 1618169169544 }, """ SV_GET_DEVICE_TIMER = 'ddd49252f61944dc9c46d1a770a5980f' kwargs.update({"device_mac": mac, "action_type": action_type, "sv": SV_GET_DEVICE_TIMER}) return self.api_call('/app/v2/device/timer/get', json=kwargs) def set_device_timer(self, *, mac: str, delay_time: int, action_value: int, **kwargs) -> WyzeResponse: """ action_value: 0=off, 1=on See: com.HLApi.CloudAPI.CloudProtocol.deviceTimerSet """ SV_SET_DEVICE_TIMER = 'b4810ce03e7747669fdc4644e554fd23' kwargs.update({ "device_mac": mac, "action_type": 1, "action_value": action_value, "delay_time": delay_time, "plan_execute_ts": datetime_to_epoch(datetime.now() + timedelta(seconds=delay_time)), "sv": SV_SET_DEVICE_TIMER }) return self.api_call('/app/v2/device/timer/set', json=kwargs) def get_device_group_timer(self, *, id: int, action_type: int, **kwargs) -> WyzeResponse: """ "data": { "action_value": "1", "delay_time": 10800, "plan_execute_ts": 1618169169544 }, """ SV_GET_DEVICE_GROUP_TIMER = 'bf55bbf1db0e4fa18cc7a13022de33a3' kwargs.update({"group_id": str(id), "action_type": action_type, "sv": SV_GET_DEVICE_GROUP_TIMER}) return self.api_call('/app/v2/device_group/timer/get', json=kwargs) def cancel_device_timer(self, *, mac: str, action_type: int, **kwargs) -> WyzeResponse: SV_CANCEL_DEVICE_TIMER = '3f97925c690740f4aff91da765087db5' kwargs.update({"device_mac": mac, "action_type": action_type, "sv": SV_CANCEL_DEVICE_TIMER}) return self.api_call('/app/v2/device/timer/cancel', json=kwargs) def get_smoke_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.SMOKE, begin=begin, end=end, limit=limit, order_by=order_by) def get_sound_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.SOUND, begin=begin, end=end, limit=limit, order_by=order_by) def get_co_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.CO, begin=begin, end=end, limit=limit, order_by=order_by) def get_motion_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.MOTION, begin=begin, end=end, limit=limit, order_by=order_by) def get_event_list(self, *, device_ids: Sequence[str] = [], event_values: Union[EventAlarmType, Sequence[EventAlarmType]] = [], event_tags: Sequence[str] = [], event_type: str = "1", begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: int = 20, order_by: int = 2, **kwargs) -> WyzeResponse: SV_GET_EVENT_LIST = 'bdcb412e230049c0be0916e75022d3f3' if limit < 1 or limit > 20: raise WyzeRequestError(f"limit {limit} must be between 1 and 20") if order_by not in [1, 2]: raise WyzeRequestError(f"order_by {order_by} must be one of {[1, 2]}") if begin is None: begin = datetime.now() - timedelta(days=1) if end is None: end = datetime.now() if isinstance(event_values, (list, Tuple)): kwargs.update({ "event_value_list": [code for alarm_type in event_values for code in alarm_type.codes] }) else: kwargs.update({"event_value_list": [code for code in event_values.codes]}) kwargs.update({ "device_mac_list": device_ids, 'begin_time': datetime_to_epoch(begin), "event_tag_list": event_tags, "event_type": event_type, 'end_time': datetime_to_epoch(end), 'order_by': order_by, 'count': limit, "sv": SV_GET_EVENT_LIST, }) return self.api_call('/app/v2/device/get_event_list', json=kwargs) def set_read_state_list(self, *, events: dict[str, Sequence[str]], read_state: bool = True, **kwargs) -> WyzeResponse: SV_SET_READ_STATE_LIST = '1e9a7d77786f4751b490277dc3cfa7b5' kwargs.update({ "event_list": [{ "device_mac": mac, "event_id_list": [event.id for event in events], "event_type": 1 } for mac, events in events], "read_state": 1 if read_state else 0, "sv": SV_SET_READ_STATE_LIST, }) return self.api_call('/app/v2/device_event/set_read_state_list', json=kwargs) def run_action(self, *, mac: str, action_key: str, action_params: Optional[dict] = {}, custom_string: Optional[str] = None, provider_key: str, **kwargs) -> WyzeResponse: SV_RUN_ACTION = '011a6b42d80a4f32b4cc24bb721c9c96' kwargs.update({ "instance_id": mac, "action_key": action_key, "provider_key": provider_key, "sv": SV_RUN_ACTION }) kwargs.update({"action_params": action_params}) if custom_string is not None: kwargs.update({"custom_string": custom_string}) return self.api_call('/app/v2/auto/run_action', json=kwargs) def run_action_list(self, *, actions: Union[dict[str, dict[str, DeviceProp]], Sequence[dict[str, dict[str, DeviceProp]]]], custom_string: Optional[str] = None, **kwargs) -> WyzeResponse: SV_RUN_ACTION_LIST = '5e02224ae0c64d328154737602d28833' kwargs.update({ "action_list": [], "sv": SV_RUN_ACTION_LIST }) if not isinstance(actions, (list, Tuple)): actions = [actions] for action in actions: kwargs["action_list"].append({ "action_key": action["key"], "action_params": { "list": [ { "mac": action["device_mac"], "plist": [ { "pid": action["prop"].definition.pid, "pvalue": str(action["prop"].api_value), } ] } ] }, "instance_id": action["device_mac"], "provider_key": action["provider_key"], }) if custom_string is not None: kwargs.update({"custom_string": custom_string}) return self.api_call('/app/v2/auto/run_action_list', json=kwargs) class AwayModeGenerator(object): cursor_time = None remain_time = None _logger = logging.getLogger(__name__) @property def value(self) -> Sequence[str]: _values = [] local_am_start = datetime(1970, 1, 1, 6, 0, 0) local_am_end = datetime(1970, 1, 1, 9, 0, 0) local_pm_start = datetime(1970, 1, 1, 18, 0, 0) local_pm_end = datetime(1970, 1, 1, 23, 0, 0) self._calculate_away_mode(_values, local_am_start, local_am_end) self._remove_unreasonable_data(_values, local_am_end) self._calculate_away_mode(_values, local_pm_start, local_pm_end) self._remove_unreasonable_data(_values, local_pm_end) value = [] i2 = 1 for _value in _values: value.append(f"{strftime('%H%M', gmtime(_value))}{i2}") i2 ^= 1 # adds the on/off bit print(f"value returning={value}") return value def _calculate_away_mode(self, arrayList: list, local_start: datetime, local_end: datetime) -> Sequence[str]: """ See: com.hualai.wlpp1.u2.b """ gmt_start_time = local_start.timestamp() gmt_end_time = local_end.timestamp() self.remain_time = gmt_end_time - gmt_start_time self.cursor_time = gmt_start_time z = False while (True): if z: arrayList.append(self._randomize(3600, 60, gmt_end_time)) z = not z elif (self.remain_time <= 900): return arrayList else: arrayList.append(self._randomize(3600, 60, gmt_end_time)) z = not z def _remove_unreasonable_data(self, arrayList: list[float], local_end: datetime): if arrayList is not None and len(arrayList) >= 2: last_data = arrayList[len(arrayList) - 1] + self._local_timezone_in_seconds self._logger.debug(f"remove_unreasonable_data last_data={last_data} local_end={local_end}") if last_data > local_end.timestamp(): self._logger.debug(f"remove_unreasonable_data item {arrayList[len(arrayList) + -1]}") del arrayList[len(arrayList) + -1] del arrayList[len(arrayList) + -1] @property def _local_timezone_in_seconds(self) -> int: return (datetime.now() - datetime.utcnow()).total_seconds() def _randomize(self, seconds_per_hour: float, seconds_per_minute: float, end_time: float) -> int: import random self._logger.debug(f"_randomize remain_time={self.remain_time}") self._logger.debug(f"_randomize cursor_time={self.cursor_time}") minutes_remaining = 60.0 if self.remain_time - seconds_per_hour >= 0 else (self.remain_time % seconds_per_hour) / seconds_per_minute self._logger.debug(f"_randomize minutes_remaining={minutes_remaining}") random = self.cursor_time + ( ((random.random() * (minutes_remaining - 5)) + 5.0) * seconds_per_minute ) self.cursor_time = random self.remain_time = end_time - (random + seconds_per_minute) return self.cursor_time
wyze_sdk/service/api_service.py
from __future__ import annotations import logging from datetime import datetime, timedelta from time import gmtime, strftime from typing import Any, Dict, Optional, Sequence, Tuple, Union from wyze_sdk.errors import WyzeRequestError from wyze_sdk.models import datetime_to_epoch from wyze_sdk.models.devices import DeviceProp from wyze_sdk.models.events import EventAlarmType from wyze_sdk.signature import RequestVerifier from .base import BaseServiceClient, WyzeResponse class ApiServiceClient(BaseServiceClient): """ Wyze api client is the wrapper on the requests to https://api.wyzecam.com """ SC = "a626948714654991afd3c0dbd7cdb901" WYZE_API_URL = "https://api.wyzecam.com/" WYZE_APP_NAME = "com.hualai" def __init__( self, token: Optional[str] = None, base_url: Optional[str] = WYZE_API_URL, app_name: str = WYZE_APP_NAME, sc: str = SC, ): super().__init__(token=token, base_url=base_url, app_name=app_name, request_verifier=RequestVerifier(signing_secret=None)) self.app_ver = self.app_name + '___' + self.app_version self.sc = sc def _get_headers( self, *, request_specific_headers: Optional[dict] ) -> Dict[str, str]: return super()._get_headers(headers=None, has_json=True, request_specific_headers=request_specific_headers) def api_call( self, api_method: str, *, http_verb: str = "POST", json: dict = {}, headers: dict = None, ) -> WyzeResponse: json['access_token'] = self.token json['app_name'] = self.app_name json['app_ver'] = self.app_ver json['app_version'] = self.app_version json['phone_id'] = self.phone_id json['phone_system_type'] = str(self.phone_type) json['sc'] = self.sc json['ts'] = self.request_verifier.clock.nonce() headers = self._get_headers( request_specific_headers={ 'Connection': 'keep-alive', } ) return super().api_call(api_method, http_verb=http_verb, data=None, params=None, json=json, headers=headers, auth=None) def refresh_token(self, *, refresh_token: str, **kwargs) -> WyzeResponse: SV_REFRESH_TOKEN = '<PASSWORD>' kwargs.update({"refresh_token": refresh_token, "sv": SV_REFRESH_TOKEN}) return self.api_call('/app/user/refresh_token', json=kwargs) def set_device_property(self, *, mac: str, model: str, pid: str, value: Any, **kwargs) -> WyzeResponse: SV_SET_DEVICE_PROPERTY = '44b6d5640c4d4978baba65c8ab9a6d6e' kwargs.update({"device_mac": mac, "device_model": model, "pid": pid, "pvalue": str(value), "sv": SV_SET_DEVICE_PROPERTY}) return self.api_call('/app/v2/device/set_property', json=kwargs) def get_device_list_property_list(self, *, device_ids: Sequence[str], target_pids: Sequence[str], **kwargs) -> WyzeResponse: SV_GET_DEVICE_LIST_PROPERTY_LIST = 'be9e90755d3445d0a4a583c8314972b6' kwargs.update({"device_list": device_ids, "target_pid_list": target_pids, "sv": SV_GET_DEVICE_LIST_PROPERTY_LIST}) return self.api_call('/app/v2/device_list/get_property_list', json=kwargs) def get_device_property_list(self, *, mac: str, model: str, target_pids: Sequence[str] = [], **kwargs) -> WyzeResponse: SV_GET_DEVICE_PROPERTY_LIST = '1df2807c63254e16a06213323fe8dec8' kwargs.update({"device_mac": mac, "device_model": model, "sv": SV_GET_DEVICE_PROPERTY_LIST}) if target_pids is not None: kwargs.update({"target_pid_list": target_pids}) return self.api_call('/app/v2/device/get_property_list', json=kwargs) def get_v1_device_info(self, *, mac: str, **kwargs) -> WyzeResponse: SV_GET_DEVICE_INFO = '90fea740c4c045f9a3084c17cee71d46' kwargs.update({"device_mac": mac, "sv": SV_GET_DEVICE_INFO}) return self.api_call('/app/device/get_device_info', json=kwargs) def get_user_info(self, **kwargs) -> WyzeResponse: SV_GET_USER_INFO = '6e054e04b7144c90af3b1281b6533492' kwargs.update({"sv": SV_GET_USER_INFO}) return self.api_call('/app/user/get_user_info', json=kwargs) def logout(self, **kwargs) -> WyzeResponse: SV_LOGOUT = '759245b61abd49128585e95f30e61add' kwargs.update({"sv": SV_LOGOUT}) return self.api_call('/app/user/logout', json=kwargs) def get_device_info(self, *, mac: str, model: str, **kwargs) -> WyzeResponse: SV_GET_DEVICE_INFO = '81d1abc794ba45a39fdd21233d621e84' kwargs.update({"device_mac": mac, "device_model": model, "sv": SV_GET_DEVICE_INFO}) return self.api_call('/app/v2/device/get_device_Info', json=kwargs) def get_object_list(self, **kwargs) -> WyzeResponse: SV_GET_DEVICE_LIST = 'c417b62d72ee44bf933054bdca183e77' kwargs.update({"sv": SV_GET_DEVICE_LIST}) return self.api_call( '/app/v2/home_page/get_object_list', json=kwargs) def get_device_timer(self, *, mac: str, action_type: int, **kwargs) -> WyzeResponse: """ "data": { "action_value": "1", "delay_time": 10800, "plan_execute_ts": 1618169169544 }, """ SV_GET_DEVICE_TIMER = 'ddd49252f61944dc9c46d1a770a5980f' kwargs.update({"device_mac": mac, "action_type": action_type, "sv": SV_GET_DEVICE_TIMER}) return self.api_call('/app/v2/device/timer/get', json=kwargs) def set_device_timer(self, *, mac: str, delay_time: int, action_value: int, **kwargs) -> WyzeResponse: """ action_value: 0=off, 1=on See: com.HLApi.CloudAPI.CloudProtocol.deviceTimerSet """ SV_SET_DEVICE_TIMER = 'b4810ce03e7747669fdc4644e554fd23' kwargs.update({ "device_mac": mac, "action_type": 1, "action_value": action_value, "delay_time": delay_time, "plan_execute_ts": datetime_to_epoch(datetime.now() + timedelta(seconds=delay_time)), "sv": SV_SET_DEVICE_TIMER }) return self.api_call('/app/v2/device/timer/set', json=kwargs) def get_device_group_timer(self, *, id: int, action_type: int, **kwargs) -> WyzeResponse: """ "data": { "action_value": "1", "delay_time": 10800, "plan_execute_ts": 1618169169544 }, """ SV_GET_DEVICE_GROUP_TIMER = 'bf55bbf1db0e4fa18cc7a13022de33a3' kwargs.update({"group_id": str(id), "action_type": action_type, "sv": SV_GET_DEVICE_GROUP_TIMER}) return self.api_call('/app/v2/device_group/timer/get', json=kwargs) def cancel_device_timer(self, *, mac: str, action_type: int, **kwargs) -> WyzeResponse: SV_CANCEL_DEVICE_TIMER = '3f97925c690740f4aff91da765087db5' kwargs.update({"device_mac": mac, "action_type": action_type, "sv": SV_CANCEL_DEVICE_TIMER}) return self.api_call('/app/v2/device/timer/cancel', json=kwargs) def get_smoke_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.SMOKE, begin=begin, end=end, limit=limit, order_by=order_by) def get_sound_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.SOUND, begin=begin, end=end, limit=limit, order_by=order_by) def get_co_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.CO, begin=begin, end=end, limit=limit, order_by=order_by) def get_motion_event_list(self, *, device_ids: Sequence[str] = [], begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: Optional[int] = 20, order_by: Optional[int] = 2, **kwargs) -> WyzeResponse: return self.get_event_list(device_ids=device_ids, event_values=EventAlarmType.MOTION, begin=begin, end=end, limit=limit, order_by=order_by) def get_event_list(self, *, device_ids: Sequence[str] = [], event_values: Union[EventAlarmType, Sequence[EventAlarmType]] = [], event_tags: Sequence[str] = [], event_type: str = "1", begin: Optional[datetime] = None, end: Optional[datetime] = None, limit: int = 20, order_by: int = 2, **kwargs) -> WyzeResponse: SV_GET_EVENT_LIST = 'bdcb412e230049c0be0916e75022d3f3' if limit < 1 or limit > 20: raise WyzeRequestError(f"limit {limit} must be between 1 and 20") if order_by not in [1, 2]: raise WyzeRequestError(f"order_by {order_by} must be one of {[1, 2]}") if begin is None: begin = datetime.now() - timedelta(days=1) if end is None: end = datetime.now() if isinstance(event_values, (list, Tuple)): kwargs.update({ "event_value_list": [code for alarm_type in event_values for code in alarm_type.codes] }) else: kwargs.update({"event_value_list": [code for code in event_values.codes]}) kwargs.update({ "device_mac_list": device_ids, 'begin_time': datetime_to_epoch(begin), "event_tag_list": event_tags, "event_type": event_type, 'end_time': datetime_to_epoch(end), 'order_by': order_by, 'count': limit, "sv": SV_GET_EVENT_LIST, }) return self.api_call('/app/v2/device/get_event_list', json=kwargs) def set_read_state_list(self, *, events: dict[str, Sequence[str]], read_state: bool = True, **kwargs) -> WyzeResponse: SV_SET_READ_STATE_LIST = '1e9a7d77786f4751b490277dc3cfa7b5' kwargs.update({ "event_list": [{ "device_mac": mac, "event_id_list": [event.id for event in events], "event_type": 1 } for mac, events in events], "read_state": 1 if read_state else 0, "sv": SV_SET_READ_STATE_LIST, }) return self.api_call('/app/v2/device_event/set_read_state_list', json=kwargs) def run_action(self, *, mac: str, action_key: str, action_params: Optional[dict] = {}, custom_string: Optional[str] = None, provider_key: str, **kwargs) -> WyzeResponse: SV_RUN_ACTION = '011a6b42d80a4f32b4cc24bb721c9c96' kwargs.update({ "instance_id": mac, "action_key": action_key, "provider_key": provider_key, "sv": SV_RUN_ACTION }) kwargs.update({"action_params": action_params}) if custom_string is not None: kwargs.update({"custom_string": custom_string}) return self.api_call('/app/v2/auto/run_action', json=kwargs) def run_action_list(self, *, actions: Union[dict[str, dict[str, DeviceProp]], Sequence[dict[str, dict[str, DeviceProp]]]], custom_string: Optional[str] = None, **kwargs) -> WyzeResponse: SV_RUN_ACTION_LIST = '5e02224ae0c64d328154737602d28833' kwargs.update({ "action_list": [], "sv": SV_RUN_ACTION_LIST }) if not isinstance(actions, (list, Tuple)): actions = [actions] for action in actions: kwargs["action_list"].append({ "action_key": action["key"], "action_params": { "list": [ { "mac": action["device_mac"], "plist": [ { "pid": action["prop"].definition.pid, "pvalue": str(action["prop"].api_value), } ] } ] }, "instance_id": action["device_mac"], "provider_key": action["provider_key"], }) if custom_string is not None: kwargs.update({"custom_string": custom_string}) return self.api_call('/app/v2/auto/run_action_list', json=kwargs) class AwayModeGenerator(object): cursor_time = None remain_time = None _logger = logging.getLogger(__name__) @property def value(self) -> Sequence[str]: _values = [] local_am_start = datetime(1970, 1, 1, 6, 0, 0) local_am_end = datetime(1970, 1, 1, 9, 0, 0) local_pm_start = datetime(1970, 1, 1, 18, 0, 0) local_pm_end = datetime(1970, 1, 1, 23, 0, 0) self._calculate_away_mode(_values, local_am_start, local_am_end) self._remove_unreasonable_data(_values, local_am_end) self._calculate_away_mode(_values, local_pm_start, local_pm_end) self._remove_unreasonable_data(_values, local_pm_end) value = [] i2 = 1 for _value in _values: value.append(f"{strftime('%H%M', gmtime(_value))}{i2}") i2 ^= 1 # adds the on/off bit print(f"value returning={value}") return value def _calculate_away_mode(self, arrayList: list, local_start: datetime, local_end: datetime) -> Sequence[str]: """ See: com.hualai.wlpp1.u2.b """ gmt_start_time = local_start.timestamp() gmt_end_time = local_end.timestamp() self.remain_time = gmt_end_time - gmt_start_time self.cursor_time = gmt_start_time z = False while (True): if z: arrayList.append(self._randomize(3600, 60, gmt_end_time)) z = not z elif (self.remain_time <= 900): return arrayList else: arrayList.append(self._randomize(3600, 60, gmt_end_time)) z = not z def _remove_unreasonable_data(self, arrayList: list[float], local_end: datetime): if arrayList is not None and len(arrayList) >= 2: last_data = arrayList[len(arrayList) - 1] + self._local_timezone_in_seconds self._logger.debug(f"remove_unreasonable_data last_data={last_data} local_end={local_end}") if last_data > local_end.timestamp(): self._logger.debug(f"remove_unreasonable_data item {arrayList[len(arrayList) + -1]}") del arrayList[len(arrayList) + -1] del arrayList[len(arrayList) + -1] @property def _local_timezone_in_seconds(self) -> int: return (datetime.now() - datetime.utcnow()).total_seconds() def _randomize(self, seconds_per_hour: float, seconds_per_minute: float, end_time: float) -> int: import random self._logger.debug(f"_randomize remain_time={self.remain_time}") self._logger.debug(f"_randomize cursor_time={self.cursor_time}") minutes_remaining = 60.0 if self.remain_time - seconds_per_hour >= 0 else (self.remain_time % seconds_per_hour) / seconds_per_minute self._logger.debug(f"_randomize minutes_remaining={minutes_remaining}") random = self.cursor_time + ( ((random.random() * (minutes_remaining - 5)) + 5.0) * seconds_per_minute ) self.cursor_time = random self.remain_time = end_time - (random + seconds_per_minute) return self.cursor_time
0.845911
0.096663
from test_framework.mininode import * from test_framework.test_framework import XazabTestFramework from test_framework.util import * ''' feature_llmq_signing.py Checks LLMQs signing sessions ''' class LLMQSigningTest(XazabTestFramework): def set_test_params(self): self.set_xazab_test_params(6, 5, fast_dip3_enforcement=True) self.set_xazab_llmq_test_params(5, 3) def add_options(self, parser): parser.add_option("--spork21", dest="spork21", default=False, action="store_true", help="Test with spork21 enabled") def run_test(self): self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0) if self.options.spork21: self.nodes[0].spork("SPORK_21_QUORUM_ALL_CONNECTED", 0) self.wait_for_sporks_same() self.mine_quorum() id = "0000000000000000000000000000000000000000000000000000000000000001" msgHash = "0000000000000000000000000000000000000000000000000000000000000002" msgHashConflict = "0000000000000000000000000000000000000000000000000000000000000003" def check_sigs(hasrecsigs, isconflicting1, isconflicting2): for node in self.nodes: if node.quorum("hasrecsig", 100, id, msgHash) != hasrecsigs: return False if node.quorum("isconflicting", 100, id, msgHash) != isconflicting1: return False if node.quorum("isconflicting", 100, id, msgHashConflict) != isconflicting2: return False return True def wait_for_sigs(hasrecsigs, isconflicting1, isconflicting2, timeout): wait_until(lambda: check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout) def assert_sigs_nochange(hasrecsigs, isconflicting1, isconflicting2, timeout): assert(not wait_until(lambda: not check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout, do_assert = False)) # Initial state wait_for_sigs(False, False, False, 1) # Sign 2 shares, should not result in recovered sig for i in range(2): self.mninfo[i].node.quorum("sign", 100, id, msgHash) assert_sigs_nochange(False, False, False, 3) # Sign one more share, should result in recovered sig and conflict for msgHashConflict self.mninfo[2].node.quorum("sign", 100, id, msgHash) wait_for_sigs(True, False, True, 15) recsig_time = self.mocktime # Mine one more quorum, so that we have 2 active ones, nothing should change self.mine_quorum() assert_sigs_nochange(True, False, True, 3) # Mine 2 more quorums, so that the one used for the the recovered sig should become inactive, nothing should change self.mine_quorum() self.mine_quorum() assert_sigs_nochange(True, False, True, 3) # fast forward until 0.5 days before cleanup is expected, recovered sig should still be valid self.bump_mocktime(recsig_time + int(60 * 60 * 24 * 6.5) - self.mocktime) # Cleanup starts every 5 seconds wait_for_sigs(True, False, True, 15) # fast forward 1 day, recovered sig should not be valid anymore self.bump_mocktime(int(60 * 60 * 24 * 1)) # Cleanup starts every 5 seconds wait_for_sigs(False, False, False, 15) for i in range(2): self.mninfo[i].node.quorum("sign", 100, id, msgHashConflict) for i in range(2, 5): self.mninfo[i].node.quorum("sign", 100, id, msgHash) wait_for_sigs(True, False, True, 15) if self.options.spork21: id = "0000000000000000000000000000000000000000000000000000000000000002" # Isolate the node that is responsible for the recovery of a signature and assert that recovery fails q = self.nodes[0].quorum('selectquorum', 100, id) mn = self.get_mninfo(q['recoveryMembers'][0]) mn.node.setnetworkactive(False) wait_until(lambda: mn.node.getconnectioncount() == 0) for i in range(4): self.mninfo[i].node.quorum("sign", 100, id, msgHash) assert_sigs_nochange(False, False, False, 3) # Need to re-connect so that it later gets the recovered sig mn.node.setnetworkactive(True) connect_nodes(mn.node, 0) # Make sure node0 has received qsendrecsigs from the previously isolated node mn.node.ping() wait_until(lambda: all('pingwait' not in peer for peer in mn.node.getpeerinfo())) # Let 2 seconds pass so that the next node is used for recovery, which should succeed self.bump_mocktime(2) wait_for_sigs(True, False, True, 2) if __name__ == '__main__': LLMQSigningTest().main()
test/functional/feature_llmq_signing.py
from test_framework.mininode import * from test_framework.test_framework import XazabTestFramework from test_framework.util import * ''' feature_llmq_signing.py Checks LLMQs signing sessions ''' class LLMQSigningTest(XazabTestFramework): def set_test_params(self): self.set_xazab_test_params(6, 5, fast_dip3_enforcement=True) self.set_xazab_llmq_test_params(5, 3) def add_options(self, parser): parser.add_option("--spork21", dest="spork21", default=False, action="store_true", help="Test with spork21 enabled") def run_test(self): self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0) if self.options.spork21: self.nodes[0].spork("SPORK_21_QUORUM_ALL_CONNECTED", 0) self.wait_for_sporks_same() self.mine_quorum() id = "0000000000000000000000000000000000000000000000000000000000000001" msgHash = "0000000000000000000000000000000000000000000000000000000000000002" msgHashConflict = "0000000000000000000000000000000000000000000000000000000000000003" def check_sigs(hasrecsigs, isconflicting1, isconflicting2): for node in self.nodes: if node.quorum("hasrecsig", 100, id, msgHash) != hasrecsigs: return False if node.quorum("isconflicting", 100, id, msgHash) != isconflicting1: return False if node.quorum("isconflicting", 100, id, msgHashConflict) != isconflicting2: return False return True def wait_for_sigs(hasrecsigs, isconflicting1, isconflicting2, timeout): wait_until(lambda: check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout) def assert_sigs_nochange(hasrecsigs, isconflicting1, isconflicting2, timeout): assert(not wait_until(lambda: not check_sigs(hasrecsigs, isconflicting1, isconflicting2), timeout = timeout, do_assert = False)) # Initial state wait_for_sigs(False, False, False, 1) # Sign 2 shares, should not result in recovered sig for i in range(2): self.mninfo[i].node.quorum("sign", 100, id, msgHash) assert_sigs_nochange(False, False, False, 3) # Sign one more share, should result in recovered sig and conflict for msgHashConflict self.mninfo[2].node.quorum("sign", 100, id, msgHash) wait_for_sigs(True, False, True, 15) recsig_time = self.mocktime # Mine one more quorum, so that we have 2 active ones, nothing should change self.mine_quorum() assert_sigs_nochange(True, False, True, 3) # Mine 2 more quorums, so that the one used for the the recovered sig should become inactive, nothing should change self.mine_quorum() self.mine_quorum() assert_sigs_nochange(True, False, True, 3) # fast forward until 0.5 days before cleanup is expected, recovered sig should still be valid self.bump_mocktime(recsig_time + int(60 * 60 * 24 * 6.5) - self.mocktime) # Cleanup starts every 5 seconds wait_for_sigs(True, False, True, 15) # fast forward 1 day, recovered sig should not be valid anymore self.bump_mocktime(int(60 * 60 * 24 * 1)) # Cleanup starts every 5 seconds wait_for_sigs(False, False, False, 15) for i in range(2): self.mninfo[i].node.quorum("sign", 100, id, msgHashConflict) for i in range(2, 5): self.mninfo[i].node.quorum("sign", 100, id, msgHash) wait_for_sigs(True, False, True, 15) if self.options.spork21: id = "0000000000000000000000000000000000000000000000000000000000000002" # Isolate the node that is responsible for the recovery of a signature and assert that recovery fails q = self.nodes[0].quorum('selectquorum', 100, id) mn = self.get_mninfo(q['recoveryMembers'][0]) mn.node.setnetworkactive(False) wait_until(lambda: mn.node.getconnectioncount() == 0) for i in range(4): self.mninfo[i].node.quorum("sign", 100, id, msgHash) assert_sigs_nochange(False, False, False, 3) # Need to re-connect so that it later gets the recovered sig mn.node.setnetworkactive(True) connect_nodes(mn.node, 0) # Make sure node0 has received qsendrecsigs from the previously isolated node mn.node.ping() wait_until(lambda: all('pingwait' not in peer for peer in mn.node.getpeerinfo())) # Let 2 seconds pass so that the next node is used for recovery, which should succeed self.bump_mocktime(2) wait_for_sigs(True, False, True, 2) if __name__ == '__main__': LLMQSigningTest().main()
0.556159
0.422326
import numpy as np from scipy.special import iv def tapering_window(time,D,mywindow): """ tapering_window returns the window for tapering a WOSA segment. Inputs: - time [1-dim numpy array of floats]: times along the WOSA segment. - D [float]: Temporal length of the WOSA segment. - mywindow [int]: Choice of tapering window: -> 1: Square window -> 2: Triangular window -> 3: sin window -> 4: sin**2 (Hanning) window -> 5: sin**3 window -> 6: sin**4 window -> 7: Hamming window, defined as 0.54-0.46*np.cos(2.0*np.pi*time/D) -> 8: 4-term Blackman-Harris window, with a0=0.35875 and a1=0.48829 and a2=0.14128 and a3=0.01168 -> 9: Kaiser-Bessel window, with parameter alpha=2.5 -> 10: Gaussian window, with standard dev. sigma=D/6.0 The terminology and formulas come from: <NAME>. On the use of windows for harmonic analysis with the discrete fourier transform. Proceedings of the IEEE, 66(1):51-83, January 1978. WARNING: Provide the vector 'time' such that for all k=0,...,time.size-1, we have time[k]>=0 and time[k]<=D Outputs: - tapering_window [1-dim numpy array of floats - size=time.size]: the tapering window. ----------------------------- This is part of WAVEPAL (C) 2016 <NAME>""" T=time.size if mywindow==1: tapering_window=np.ones(T) elif mywindow==2: tapering_window=1.0-np.absolute(time-D/2.0)/(D/2.0) elif mywindow==3: tapering_window=np.sin(np.pi*time/D) elif mywindow==4: tapering_window=(np.sin(np.pi*time/D))**2 elif mywindow==5: tapering_window=(np.sin(np.pi*time/D))**3 elif mywindow==6: tapering_window=(np.sin(np.pi*time/D))**4 elif mywindow==7: tapering_window=0.54-0.46*np.cos(2.0*np.pi*time/D) elif mywindow==8: a0=0.35875 a1=0.48829 a2=0.14128 a3=0.01168 tapering_window=a0-a1*np.cos(2.0*np.pi*time/D)+a2*np.cos(4.0*np.pi*time/D)-a3*np.cos(6.0*np.pi*time/D) elif mywindow==9: alpha=2.5 tapering_window=iv(0,np.pi*alpha*np.sqrt(1.0-((time-D/2.0)/(D/2.0))**2)) elif mywindow==10: sig=D/6.0 tapering_window=np.exp(-(time-D/2.0)**2/2.0/sig**2) else: print "Error: The window number you entered is not valid. Check input variable 'mywindow'." return return tapering_window
wavepal/tapering_window.py
import numpy as np from scipy.special import iv def tapering_window(time,D,mywindow): """ tapering_window returns the window for tapering a WOSA segment. Inputs: - time [1-dim numpy array of floats]: times along the WOSA segment. - D [float]: Temporal length of the WOSA segment. - mywindow [int]: Choice of tapering window: -> 1: Square window -> 2: Triangular window -> 3: sin window -> 4: sin**2 (Hanning) window -> 5: sin**3 window -> 6: sin**4 window -> 7: Hamming window, defined as 0.54-0.46*np.cos(2.0*np.pi*time/D) -> 8: 4-term Blackman-Harris window, with a0=0.35875 and a1=0.48829 and a2=0.14128 and a3=0.01168 -> 9: Kaiser-Bessel window, with parameter alpha=2.5 -> 10: Gaussian window, with standard dev. sigma=D/6.0 The terminology and formulas come from: <NAME>. On the use of windows for harmonic analysis with the discrete fourier transform. Proceedings of the IEEE, 66(1):51-83, January 1978. WARNING: Provide the vector 'time' such that for all k=0,...,time.size-1, we have time[k]>=0 and time[k]<=D Outputs: - tapering_window [1-dim numpy array of floats - size=time.size]: the tapering window. ----------------------------- This is part of WAVEPAL (C) 2016 <NAME>""" T=time.size if mywindow==1: tapering_window=np.ones(T) elif mywindow==2: tapering_window=1.0-np.absolute(time-D/2.0)/(D/2.0) elif mywindow==3: tapering_window=np.sin(np.pi*time/D) elif mywindow==4: tapering_window=(np.sin(np.pi*time/D))**2 elif mywindow==5: tapering_window=(np.sin(np.pi*time/D))**3 elif mywindow==6: tapering_window=(np.sin(np.pi*time/D))**4 elif mywindow==7: tapering_window=0.54-0.46*np.cos(2.0*np.pi*time/D) elif mywindow==8: a0=0.35875 a1=0.48829 a2=0.14128 a3=0.01168 tapering_window=a0-a1*np.cos(2.0*np.pi*time/D)+a2*np.cos(4.0*np.pi*time/D)-a3*np.cos(6.0*np.pi*time/D) elif mywindow==9: alpha=2.5 tapering_window=iv(0,np.pi*alpha*np.sqrt(1.0-((time-D/2.0)/(D/2.0))**2)) elif mywindow==10: sig=D/6.0 tapering_window=np.exp(-(time-D/2.0)**2/2.0/sig**2) else: print "Error: The window number you entered is not valid. Check input variable 'mywindow'." return return tapering_window
0.300746
0.595434
import pywikibot from datetime import datetime import re site = pywikibot.Site('wikidata', 'wikidata') # remove requests from Wikidata:Requests_for_permissions/Bot def removeRequests(requests): page = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot') text = page.get() for request in requests: text = re.sub(r'{{Wikidata:Requests[\s_]for[\s_]permissions/Bot/'+re.escape(request['name'])+'}}\n?', '', text) comment = 'archiving '+str(len(requests))+' requests' if len(requests) != 1 else 'archiving 1 request' page.put(text, comment=comment, minorEdit=False) # load new archive page def loadNewArchivePage(archive): page = pywikibot.Page(site, 'Wikidata:Requests for permissions/RfBot/'+archive) if not page.exists(): newarchive = ("""{{archive|category=Archived requests for permissions}} = Successful requests = = Unsuccessful requests = """) page.put(newarchive, comment='Bot: Creating new monthly archive.', minorEdit=False) return page.get().replace('_', ' ') # add requests to archive def updateArchive(requests): archives = {} for request in requests: if request['archive'] not in archives: archives[request['archive']] = {'text': loadNewArchivePage(request['archive']), 'count': 0} newText = '' for line in archives[request['archive']]['text'].split('\n'): newText += line+'\n' if (re.match('=\s*successful requests\s*=', line.lower()) and request['status'] == 'success') or (re.match('=\s*unsuccessful requests\s*=', line.lower()) and request['status'] != 'success'): newText += '* [[Wikidata:Requests for permissions/Bot/' + request['name'].replace('_', ' ') + ']]\n' archives[request['archive']]['count'] += 1 archives[request['archive']]['text'] = newText.strip() for archive in archives: page = pywikibot.Page(site, 'Wikidata:Requests for permissions/RfBot/' + archive) comment = 'archiving '+str(archives[archive]['count'])+' requests' if archives[archive]['count'] != 1 else 'archiving 1 request' page.put(archives[archive]['text'], comment=comment, minorEdit=False) def main(): toArchive = [] page = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot') fo = page.get().split('</noinclude>') requests = re.findall('{{Wikidata:Requests[\s_]for[\s_]permissions/Bot/(.*)}}', fo[1]) for request in requests: page2 = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot/' + request) if page2.isRedirectPage(): page2 = page2.getRedirectTarget() if '{{discussion top' in page2.get().lower(): if '{{approved}}' in page2.get().lower(): status = 'success' else: status = 'notdone' history = page2.getVersionHistory() date = '{0:%B} {0:%Y}'.format(history[0].timestamp) data = { 'name': request, 'archive': date, 'status': status } toArchive.append(data) if len(toArchive) > 0: updateArchive(toArchive) removeRequests(toArchive) if __name__ == "__main__": main()
requestsForBotflagArchive.py
import pywikibot from datetime import datetime import re site = pywikibot.Site('wikidata', 'wikidata') # remove requests from Wikidata:Requests_for_permissions/Bot def removeRequests(requests): page = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot') text = page.get() for request in requests: text = re.sub(r'{{Wikidata:Requests[\s_]for[\s_]permissions/Bot/'+re.escape(request['name'])+'}}\n?', '', text) comment = 'archiving '+str(len(requests))+' requests' if len(requests) != 1 else 'archiving 1 request' page.put(text, comment=comment, minorEdit=False) # load new archive page def loadNewArchivePage(archive): page = pywikibot.Page(site, 'Wikidata:Requests for permissions/RfBot/'+archive) if not page.exists(): newarchive = ("""{{archive|category=Archived requests for permissions}} = Successful requests = = Unsuccessful requests = """) page.put(newarchive, comment='Bot: Creating new monthly archive.', minorEdit=False) return page.get().replace('_', ' ') # add requests to archive def updateArchive(requests): archives = {} for request in requests: if request['archive'] not in archives: archives[request['archive']] = {'text': loadNewArchivePage(request['archive']), 'count': 0} newText = '' for line in archives[request['archive']]['text'].split('\n'): newText += line+'\n' if (re.match('=\s*successful requests\s*=', line.lower()) and request['status'] == 'success') or (re.match('=\s*unsuccessful requests\s*=', line.lower()) and request['status'] != 'success'): newText += '* [[Wikidata:Requests for permissions/Bot/' + request['name'].replace('_', ' ') + ']]\n' archives[request['archive']]['count'] += 1 archives[request['archive']]['text'] = newText.strip() for archive in archives: page = pywikibot.Page(site, 'Wikidata:Requests for permissions/RfBot/' + archive) comment = 'archiving '+str(archives[archive]['count'])+' requests' if archives[archive]['count'] != 1 else 'archiving 1 request' page.put(archives[archive]['text'], comment=comment, minorEdit=False) def main(): toArchive = [] page = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot') fo = page.get().split('</noinclude>') requests = re.findall('{{Wikidata:Requests[\s_]for[\s_]permissions/Bot/(.*)}}', fo[1]) for request in requests: page2 = pywikibot.Page(site, 'Wikidata:Requests for permissions/Bot/' + request) if page2.isRedirectPage(): page2 = page2.getRedirectTarget() if '{{discussion top' in page2.get().lower(): if '{{approved}}' in page2.get().lower(): status = 'success' else: status = 'notdone' history = page2.getVersionHistory() date = '{0:%B} {0:%Y}'.format(history[0].timestamp) data = { 'name': request, 'archive': date, 'status': status } toArchive.append(data) if len(toArchive) > 0: updateArchive(toArchive) removeRequests(toArchive) if __name__ == "__main__": main()
0.215433
0.079353
from __future__ import absolute_import, unicode_literals import json import tornado.web import logging import ldap from .dtos import TrackDTO, DTOEncoder from .base_request_handler import BaseRequestHandler from .database_connection import DBConnection logger = logging.getLogger(__package__) class LoginRequestHandler(BaseRequestHandler): def post(self): data = json.loads(self.request.body.decode('utf-8')) # exposes passwords! #logger.debug('Got JSON data: {0}'.format(data)) user_full_name = data['user_id'] password = data['password'] ldap_dn = self.config['mopidy_bamp']['ldap_schema'].replace('#USER_NAME#', user_full_name) logger.debug('ldap dn:' + ldap_dn) try: # talk to ldap server, see if user is authed ldap_connection = ldap.initialize(self.config['mopidy_bamp']['ldap_uri']) ldap_connection.simple_bind_s(who=ldap_dn, cred=password) user_id = ldap_connection.whoami_s().replace('u:CORP\\', '') logger.debug('User validated! ' + user_id) except ldap.LDAPError, e: logger.debug('ldap error: ' + str(e)) raise tornado.web.HTTPError(status_code=403, log_message='invalid creds') # set our cookie to show that we've logged in self.set_secure_cookie(self.SECURE_COOKIE_USER_FIELD, user_id) # does this user have a record in the db? new_user = False user_dto = None with DBConnection() as db_connection: new_user = db_connection.user_table.exists(user_id) == False if new_user: # add row to db if they are new - make their alias their user id db_connection.user_table.add(user_id, user_id) user_dto = db_connection.user_table.get(user_id) response = {'status': 'ok', 'new_user': new_user, 'user': user_dto} self.write(json.dumps(response, cls=DTOEncoder)) class LogoutRequestHandler(BaseRequestHandler): def get(self): # clear our cookie to log us out self.clear_cookie(self.SECURE_COOKIE_USER_FIELD) response = {'status': 'ok'} self.write(response)
mopidy_bamp/mopidy_bamp/login_request_handler.py
from __future__ import absolute_import, unicode_literals import json import tornado.web import logging import ldap from .dtos import TrackDTO, DTOEncoder from .base_request_handler import BaseRequestHandler from .database_connection import DBConnection logger = logging.getLogger(__package__) class LoginRequestHandler(BaseRequestHandler): def post(self): data = json.loads(self.request.body.decode('utf-8')) # exposes passwords! #logger.debug('Got JSON data: {0}'.format(data)) user_full_name = data['user_id'] password = data['password'] ldap_dn = self.config['mopidy_bamp']['ldap_schema'].replace('#USER_NAME#', user_full_name) logger.debug('ldap dn:' + ldap_dn) try: # talk to ldap server, see if user is authed ldap_connection = ldap.initialize(self.config['mopidy_bamp']['ldap_uri']) ldap_connection.simple_bind_s(who=ldap_dn, cred=password) user_id = ldap_connection.whoami_s().replace('u:CORP\\', '') logger.debug('User validated! ' + user_id) except ldap.LDAPError, e: logger.debug('ldap error: ' + str(e)) raise tornado.web.HTTPError(status_code=403, log_message='invalid creds') # set our cookie to show that we've logged in self.set_secure_cookie(self.SECURE_COOKIE_USER_FIELD, user_id) # does this user have a record in the db? new_user = False user_dto = None with DBConnection() as db_connection: new_user = db_connection.user_table.exists(user_id) == False if new_user: # add row to db if they are new - make their alias their user id db_connection.user_table.add(user_id, user_id) user_dto = db_connection.user_table.get(user_id) response = {'status': 'ok', 'new_user': new_user, 'user': user_dto} self.write(json.dumps(response, cls=DTOEncoder)) class LogoutRequestHandler(BaseRequestHandler): def get(self): # clear our cookie to log us out self.clear_cookie(self.SECURE_COOKIE_USER_FIELD) response = {'status': 'ok'} self.write(response)
0.371821
0.056288
import matplotlib.pyplot as plt import numpy as np from ..utils.validation import validate_float, validate_int class PoissonProcess(object): """Simulate a sample path of a Poisson process. A Poisson process (with rate parameter λ) is continuous time stochastic process (N(t) : t ≥ 0) such that 1) N(0) = 0, 2) N(s + t) - N(s) has the Poisson distribution with mean λt, 3) For all times 0 ≤ t_0 < t1 < ... < tn, the random variables N(t_0), N(t_1) - N(t_0), ..., N(t_n) - N(t_{n-1}) are independent. Intuitively, N(s + t) - N(s) counts the number of "events" (or "arrivals", or "hits") occurring in the interval from s to s + t, as long as these events occur independently in disjoint intervals and the times (or distances) between events have the memoryless property. Poisson process arise naturally in many contexts. For example, recombination counts along segments of a genome can be modelled as a Poisson process. Properties ---------- rate : float The average number of arrivals/hits/counts in an interval of length 1. random_state : numpy.random.RandomState The random number generator. """ rate: float = None random_state: np.random.RandomState = None # The number of the last arrival computed _count: int = 0 # The last arrival time computed _time: float = 0.0 # The expanding array of arrival times _times: np.ndarray = None def __init__(self, rate=1.0, random_state=None): """Initialize a Poisson process by specifying the rate. Parameters ---------- rate : float, optional A positive number, representing the average number of arrivals/hits/counts in an interval of length 1. random_state : int or numpy.random.RandomState object, optional A valid initializer for a numpy.random.RandomState object. """ # Validate the rate self.rate = validate_float(rate, "rate", positive=True) # Seed the RNG if isinstance(random_state, np.random.RandomState): self.random_state = random_state else: self.random_state = np.random.RandomState(random_state) # Initialize the expanding times array self._times = np.zeros(shape=(1,), dtype=np.float_) def __next__(self): """Generate the next arrival of the Poisson process.""" # Wait time until the next arrival wait = self.random_state.exponential(scale=(1 / self.rate), size=1) # Get the next arrival time and increment the arival count self._time = self._time + np.asscalar(wait) self._count += 1 # Append the current time to the _times array, enlarging it if necessary if self._count >= len(self._times): self._times = np.resize(self._times, (2 * len(self._times),)) self._times[self._count - 1] = self._time return self._time def __iter__(self): """Return self to adhere to the iterator protocol.""" return self def times(self, n=None) -> np.ndarray: """Get the first n arrival times of the Poisson process. Parameters ---------- n : int, optional Specify how many times to return. If not specified, all the currently generated times are returned. Returns ------- One-dimensional NumPy array of Poisson process arrival times. """ # Validate parameters if n is None: n = self._count else: n = validate_int(n, "n", minimum=1) # Generated more arrival times if needed while self._count < n: next(self) return self._times[:n] def plot(self, end, ax=None, **kwargs): """Plot one sample path of the Poisson process on the interval [0, end]. Parameters ---------- end : positive float The final time. ax : matplotlib.axes.Axes, optional The axes on which to draw the plot kwargs : dict Keyword arguments to pass to ax.step(). Returns ------- The matplotlib.axes.Axes object on which the plot was drawn. """ # Validate parameters end = validate_float(end, "end", positive=True) # Get the axes to draw on if necessary if ax is None: ax = plt.gca() # Generated more arrival times if needed while self._time <= end: next(self) # Get the count of the first time exceeding the end time n = np.asscalar(np.argmax(self._times > end)) + 1 times = np.concatenate(([0.0], self.times(n))) counts = np.arange(n + 1) ax.step(times, counts, where="post", **kwargs) ax.set(xlim=(0, end)) ax.set(ylim=(0, None)) return ax
stattools/simulation/poisson.py
import matplotlib.pyplot as plt import numpy as np from ..utils.validation import validate_float, validate_int class PoissonProcess(object): """Simulate a sample path of a Poisson process. A Poisson process (with rate parameter λ) is continuous time stochastic process (N(t) : t ≥ 0) such that 1) N(0) = 0, 2) N(s + t) - N(s) has the Poisson distribution with mean λt, 3) For all times 0 ≤ t_0 < t1 < ... < tn, the random variables N(t_0), N(t_1) - N(t_0), ..., N(t_n) - N(t_{n-1}) are independent. Intuitively, N(s + t) - N(s) counts the number of "events" (or "arrivals", or "hits") occurring in the interval from s to s + t, as long as these events occur independently in disjoint intervals and the times (or distances) between events have the memoryless property. Poisson process arise naturally in many contexts. For example, recombination counts along segments of a genome can be modelled as a Poisson process. Properties ---------- rate : float The average number of arrivals/hits/counts in an interval of length 1. random_state : numpy.random.RandomState The random number generator. """ rate: float = None random_state: np.random.RandomState = None # The number of the last arrival computed _count: int = 0 # The last arrival time computed _time: float = 0.0 # The expanding array of arrival times _times: np.ndarray = None def __init__(self, rate=1.0, random_state=None): """Initialize a Poisson process by specifying the rate. Parameters ---------- rate : float, optional A positive number, representing the average number of arrivals/hits/counts in an interval of length 1. random_state : int or numpy.random.RandomState object, optional A valid initializer for a numpy.random.RandomState object. """ # Validate the rate self.rate = validate_float(rate, "rate", positive=True) # Seed the RNG if isinstance(random_state, np.random.RandomState): self.random_state = random_state else: self.random_state = np.random.RandomState(random_state) # Initialize the expanding times array self._times = np.zeros(shape=(1,), dtype=np.float_) def __next__(self): """Generate the next arrival of the Poisson process.""" # Wait time until the next arrival wait = self.random_state.exponential(scale=(1 / self.rate), size=1) # Get the next arrival time and increment the arival count self._time = self._time + np.asscalar(wait) self._count += 1 # Append the current time to the _times array, enlarging it if necessary if self._count >= len(self._times): self._times = np.resize(self._times, (2 * len(self._times),)) self._times[self._count - 1] = self._time return self._time def __iter__(self): """Return self to adhere to the iterator protocol.""" return self def times(self, n=None) -> np.ndarray: """Get the first n arrival times of the Poisson process. Parameters ---------- n : int, optional Specify how many times to return. If not specified, all the currently generated times are returned. Returns ------- One-dimensional NumPy array of Poisson process arrival times. """ # Validate parameters if n is None: n = self._count else: n = validate_int(n, "n", minimum=1) # Generated more arrival times if needed while self._count < n: next(self) return self._times[:n] def plot(self, end, ax=None, **kwargs): """Plot one sample path of the Poisson process on the interval [0, end]. Parameters ---------- end : positive float The final time. ax : matplotlib.axes.Axes, optional The axes on which to draw the plot kwargs : dict Keyword arguments to pass to ax.step(). Returns ------- The matplotlib.axes.Axes object on which the plot was drawn. """ # Validate parameters end = validate_float(end, "end", positive=True) # Get the axes to draw on if necessary if ax is None: ax = plt.gca() # Generated more arrival times if needed while self._time <= end: next(self) # Get the count of the first time exceeding the end time n = np.asscalar(np.argmax(self._times > end)) + 1 times = np.concatenate(([0.0], self.times(n))) counts = np.arange(n + 1) ax.step(times, counts, where="post", **kwargs) ax.set(xlim=(0, end)) ax.set(ylim=(0, None)) return ax
0.929216
0.82925
from __future__ import unicode_literals RAW_URL = 'https://raw.githubusercontent.com/Kozea/tinycss/single-regex-tokenizer/tinycss/tokenizer2.py' import re import sys import functools import operator import regex from . import token_data MACROS = {} def macro(name, value): MACROS[name] = '(?:%s)' % value.format(**MACROS) macro('nl', r'\n|\r\n|\r|\f') macro('w', r'[ \t\r\n\f]*') macro('nonascii', '[^\0-\237]') macro('escape', r''' \\[0-9a-f]{{1,6}} (?: \r\n | [ \n\r\t\f] )? | \\[^\n\r\f0-9a-f] ''') macro('nmstart', r'[_a-z]|{nonascii}|{escape}') macro('nmchar', r'[_a-z0-9-]|{nonascii}|{escape}') macro('name', r'{nmchar}+') macro('ident', r'[-]?{nmstart}{nmchar}*') macro('string', r''' " (?: [^\n\r\f\\"]|\\{nl}|{escape} )* " | ' (?: [^\n\r\f\\']|\\{nl}|{escape} )* ' ''') macro('badstring', r''' " (?: [^\n\r\f\\"]|\\{nl}|{escape} )* \\? | ' (?: [^\n\r\f\\']|\\{nl}|{escape} )* \\? ''') TOKENS_RE = regex.compile(r''' (?P<S> [ \t\r\n\f]+ ) | (?P<URI> url\({w} (?P<uri_content> {string} | (?: [!#$%&*-\[\]-~] | {nonascii} | {escape} )* ) {w}\) ) | (?P<BAD_URI> url\({w} (?: [!#$%&*-~] | {nonascii} | {escape} )* {w} | url\({w}{string}{w} | url\({w}{badstring} ) | (?P<FUNCTION> {ident}\( ) | (?P<UNICODE_RANGE> u\+ [0-9a-f?]{{1,6}} (-[0-9a-f]{{1,6}})? ) | (?P<IDENT> {ident} ) | (?P<ATKEYWORD> @{ident} ) | (?P<HASH> \#{name} ) | (?P<numbers> (?: (?P<fractional> [+-]?[0-9]*\.[0-9]+ ) | (?P<integer> [+-]?[0-9]+ ) ) (?P<unit> % | {ident} ) ? ) | (?P<STRING> {string} ) | (?P<BAD_STRING> {badstring} ) | (?P<COMMENT> /\* [^*]* \*+ (?: [^/*] [^*]* \*+ )* / ) | (?P<BAD_COMMENT> (?: /\* [^*]* \*+ (?: [^/*] [^*]* \*+ )* ) | (?: /\* [^*]* (?: \*+ [^/*] [^*]* )* ) ) | (?P<CDO> <!-- ) | (?P<CDC> --> ) '''.format(**MACROS), regex.VERBOSE | regex.IGNORECASE| regex.V1) try: unichr except NameError: # Python 3 unichr = chr unicode = str def _unicode_replace(match, int=int, unichr=unichr, maxunicode=sys.maxunicode): codepoint = int(match.group(1), 16) if codepoint <= maxunicode: return unichr(codepoint) else: return '\N{REPLACEMENT CHARACTER}' # U+FFFD UNICODE_UNESCAPE = functools.partial( regex.compile(r'\\([0-9a-f]{1,6})(?:\r\n|[ \n\r\t\f])?', regex.I).sub, _unicode_replace) NEWLINE_UNESCAPE = functools.partial( regex.compile(r'\\(?:\n|\r\n|\r|\f)').sub, '') SIMPLE_UNESCAPE = functools.partial( regex.compile(r'\\(.)').sub, # Same as r'\1', but faster on CPython operator.methodcaller('group', 1)) NEWLINES_RE = regex.compile(MACROS['nl']) def tokenize_flat(css_source, ignore_comments=True, unicode_unescape=UNICODE_UNESCAPE, newline_unescape=NEWLINE_UNESCAPE, simple_unescape=SIMPLE_UNESCAPE, Token=token_data.Token, len=len, int=int, float=float, list=list, _None=None, ): """ :param css_source: CSS as an unicode string :param ignore_comments: if true (the default) comments will not be included in the return value :return: An iterator of :class:`Token` """ regexp = TOKENS_RE.match find_newlines = NEWLINES_RE.finditer pos = 0 line = 1 column = 1 source_len = len(css_source) tokens = [] append_token = tokens.append while pos < source_len: char = css_source[pos] if char in ':;{}()[]': type_ = char css_value = char value = char unit = _None length = 1 next_pos = pos + 1 else: match = regexp(css_source, pos) if match: groups = match.groupdict() css_value = match.group() length = len(css_value) next_pos = pos + length value = css_value unit = _None if groups['S']: type_ = 'S' elif groups['numbers']: integer = groups['integer'] if integer: value = int(integer) type_ = 'INTEGER' else: value = float(groups['fractional']) type_ = 'NUMBER' unit = groups['unit'] if unit == '%': type_ = 'PERCENTAGE' elif unit: type_ = 'DIMENSION' unit = unicode_unescape(unit) unit = simple_unescape(unit) unit = unit.lower() # normalize elif groups['IDENT']: type_ = 'IDENT' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['ATKEYWORD']: type_ = 'ATKEYWORD' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['HASH']: type_ = 'HASH' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['FUNCTION']: type_ = 'FUNCTION' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['URI']: type_ = 'URI' value = groups['uri_content'] if value and value[0] in '"\'': value = value[1:-1] # Remove quotes value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) elif groups['STRING']: type_ = 'STRING' value = css_value[1:-1] # Remove quotes value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) # BAD_STRING can only be one of: # * Unclosed string at the end of the stylesheet: # Close the string, but this is not an error. # Make it a "good" STRING token. # * Unclosed string at the (unescaped) end of the line: # Close the string, but this is an error. # Leave it as a BAD_STRING, don’t bother parsing it. # See http://www.w3.org/TR/CSS21/syndata.html#parsing-errors elif groups['BAD_STRING']: if next_pos == source_len: type_ = 'STRING' value = css_value[1:] # Remove quote value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) else: type_ = 'BAD_STRING' elif groups['COMMENT']: type_ = 'COMMENT' elif groups['BAD_COMMENT']: type_ = 'BAD_COMMENT' elif groups['BAD_URI']: type_ = 'BAD_URI' elif groups['UNICODE_RANGE']: type_ = 'UNICODE-RANGE' elif groups['CDO']: type_ = 'CDO' else: assert groups['CDC'] type_ = 'CDC' else: # No match. # "Any other character not matched by the above rules, # and neither a single nor a double quote." # ... but quotes at the start of a token are always matched # by STRING or BAD_STRING. So DELIM is any single character. type_ = 'DELIM' css_value = char value = char unit = _None length = 1 next_pos = pos + 1 # A BAD_COMMENT is a comment at EOF. Ignore it too. if not (ignore_comments and type_ in ('COMMENT', 'BAD_COMMENT')): append_token(Token(type_, css_value, value, unit, line, column)) pos = next_pos newlines = list(find_newlines(css_value)) if newlines: line += len(newlines) # Add 1 to have lines start at column 1, not 0 column = length - newlines[-1].end() + 1 else: column += length return tokens
tinycss/tokenizer2.py
from __future__ import unicode_literals RAW_URL = 'https://raw.githubusercontent.com/Kozea/tinycss/single-regex-tokenizer/tinycss/tokenizer2.py' import re import sys import functools import operator import regex from . import token_data MACROS = {} def macro(name, value): MACROS[name] = '(?:%s)' % value.format(**MACROS) macro('nl', r'\n|\r\n|\r|\f') macro('w', r'[ \t\r\n\f]*') macro('nonascii', '[^\0-\237]') macro('escape', r''' \\[0-9a-f]{{1,6}} (?: \r\n | [ \n\r\t\f] )? | \\[^\n\r\f0-9a-f] ''') macro('nmstart', r'[_a-z]|{nonascii}|{escape}') macro('nmchar', r'[_a-z0-9-]|{nonascii}|{escape}') macro('name', r'{nmchar}+') macro('ident', r'[-]?{nmstart}{nmchar}*') macro('string', r''' " (?: [^\n\r\f\\"]|\\{nl}|{escape} )* " | ' (?: [^\n\r\f\\']|\\{nl}|{escape} )* ' ''') macro('badstring', r''' " (?: [^\n\r\f\\"]|\\{nl}|{escape} )* \\? | ' (?: [^\n\r\f\\']|\\{nl}|{escape} )* \\? ''') TOKENS_RE = regex.compile(r''' (?P<S> [ \t\r\n\f]+ ) | (?P<URI> url\({w} (?P<uri_content> {string} | (?: [!#$%&*-\[\]-~] | {nonascii} | {escape} )* ) {w}\) ) | (?P<BAD_URI> url\({w} (?: [!#$%&*-~] | {nonascii} | {escape} )* {w} | url\({w}{string}{w} | url\({w}{badstring} ) | (?P<FUNCTION> {ident}\( ) | (?P<UNICODE_RANGE> u\+ [0-9a-f?]{{1,6}} (-[0-9a-f]{{1,6}})? ) | (?P<IDENT> {ident} ) | (?P<ATKEYWORD> @{ident} ) | (?P<HASH> \#{name} ) | (?P<numbers> (?: (?P<fractional> [+-]?[0-9]*\.[0-9]+ ) | (?P<integer> [+-]?[0-9]+ ) ) (?P<unit> % | {ident} ) ? ) | (?P<STRING> {string} ) | (?P<BAD_STRING> {badstring} ) | (?P<COMMENT> /\* [^*]* \*+ (?: [^/*] [^*]* \*+ )* / ) | (?P<BAD_COMMENT> (?: /\* [^*]* \*+ (?: [^/*] [^*]* \*+ )* ) | (?: /\* [^*]* (?: \*+ [^/*] [^*]* )* ) ) | (?P<CDO> <!-- ) | (?P<CDC> --> ) '''.format(**MACROS), regex.VERBOSE | regex.IGNORECASE| regex.V1) try: unichr except NameError: # Python 3 unichr = chr unicode = str def _unicode_replace(match, int=int, unichr=unichr, maxunicode=sys.maxunicode): codepoint = int(match.group(1), 16) if codepoint <= maxunicode: return unichr(codepoint) else: return '\N{REPLACEMENT CHARACTER}' # U+FFFD UNICODE_UNESCAPE = functools.partial( regex.compile(r'\\([0-9a-f]{1,6})(?:\r\n|[ \n\r\t\f])?', regex.I).sub, _unicode_replace) NEWLINE_UNESCAPE = functools.partial( regex.compile(r'\\(?:\n|\r\n|\r|\f)').sub, '') SIMPLE_UNESCAPE = functools.partial( regex.compile(r'\\(.)').sub, # Same as r'\1', but faster on CPython operator.methodcaller('group', 1)) NEWLINES_RE = regex.compile(MACROS['nl']) def tokenize_flat(css_source, ignore_comments=True, unicode_unescape=UNICODE_UNESCAPE, newline_unescape=NEWLINE_UNESCAPE, simple_unescape=SIMPLE_UNESCAPE, Token=token_data.Token, len=len, int=int, float=float, list=list, _None=None, ): """ :param css_source: CSS as an unicode string :param ignore_comments: if true (the default) comments will not be included in the return value :return: An iterator of :class:`Token` """ regexp = TOKENS_RE.match find_newlines = NEWLINES_RE.finditer pos = 0 line = 1 column = 1 source_len = len(css_source) tokens = [] append_token = tokens.append while pos < source_len: char = css_source[pos] if char in ':;{}()[]': type_ = char css_value = char value = char unit = _None length = 1 next_pos = pos + 1 else: match = regexp(css_source, pos) if match: groups = match.groupdict() css_value = match.group() length = len(css_value) next_pos = pos + length value = css_value unit = _None if groups['S']: type_ = 'S' elif groups['numbers']: integer = groups['integer'] if integer: value = int(integer) type_ = 'INTEGER' else: value = float(groups['fractional']) type_ = 'NUMBER' unit = groups['unit'] if unit == '%': type_ = 'PERCENTAGE' elif unit: type_ = 'DIMENSION' unit = unicode_unescape(unit) unit = simple_unescape(unit) unit = unit.lower() # normalize elif groups['IDENT']: type_ = 'IDENT' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['ATKEYWORD']: type_ = 'ATKEYWORD' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['HASH']: type_ = 'HASH' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['FUNCTION']: type_ = 'FUNCTION' value = unicode_unescape(css_value) value = simple_unescape(value) elif groups['URI']: type_ = 'URI' value = groups['uri_content'] if value and value[0] in '"\'': value = value[1:-1] # Remove quotes value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) elif groups['STRING']: type_ = 'STRING' value = css_value[1:-1] # Remove quotes value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) # BAD_STRING can only be one of: # * Unclosed string at the end of the stylesheet: # Close the string, but this is not an error. # Make it a "good" STRING token. # * Unclosed string at the (unescaped) end of the line: # Close the string, but this is an error. # Leave it as a BAD_STRING, don’t bother parsing it. # See http://www.w3.org/TR/CSS21/syndata.html#parsing-errors elif groups['BAD_STRING']: if next_pos == source_len: type_ = 'STRING' value = css_value[1:] # Remove quote value = newline_unescape(value) value = unicode_unescape(value) value = simple_unescape(value) else: type_ = 'BAD_STRING' elif groups['COMMENT']: type_ = 'COMMENT' elif groups['BAD_COMMENT']: type_ = 'BAD_COMMENT' elif groups['BAD_URI']: type_ = 'BAD_URI' elif groups['UNICODE_RANGE']: type_ = 'UNICODE-RANGE' elif groups['CDO']: type_ = 'CDO' else: assert groups['CDC'] type_ = 'CDC' else: # No match. # "Any other character not matched by the above rules, # and neither a single nor a double quote." # ... but quotes at the start of a token are always matched # by STRING or BAD_STRING. So DELIM is any single character. type_ = 'DELIM' css_value = char value = char unit = _None length = 1 next_pos = pos + 1 # A BAD_COMMENT is a comment at EOF. Ignore it too. if not (ignore_comments and type_ in ('COMMENT', 'BAD_COMMENT')): append_token(Token(type_, css_value, value, unit, line, column)) pos = next_pos newlines = list(find_newlines(css_value)) if newlines: line += len(newlines) # Add 1 to have lines start at column 1, not 0 column = length - newlines[-1].end() + 1 else: column += length return tokens
0.39129
0.135318
from mcfunction.versions.mc_1_13.team import team, ParsedTeamCommand from mcfunction.nodes import EntityNode def test_team_add(): parsed = team.parse('team add testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'add' assert parsed.team.value == 'testteam' assert str(parsed) == 'team add testteam' def test_team_add_displayname(): parsed = team.parse('team add testteam {"text":"test successful"}') parsed: ParsedTeamCommand assert parsed.name.object['text'] == 'test successful' assert str(parsed) == 'team add testteam {"text":"test successful"}' def test_team_empty(): parsed = team.parse('team empty testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'empty' assert parsed.team.value == 'testteam' assert str(parsed) == 'team empty testteam' def test_team_join(): parsed = team.parse('team join testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'join' assert parsed.team.value == 'testteam' assert str(parsed) == 'team join testteam' def test_team_join_target(): parsed = team.parse('team join testteam @s') parsed: ParsedTeamCommand assert isinstance(parsed.target, EntityNode) assert str(parsed) == 'team join testteam @s' def test_team_leave(): parsed = team.parse('team leave @s') parsed: ParsedTeamCommand assert parsed.action.value == 'leave' assert isinstance(parsed.target, EntityNode) assert str(parsed) == 'team leave @s' def test_team_list(): parsed = team.parse('team list') parsed: ParsedTeamCommand assert parsed.action.value == 'list' assert str(parsed) == 'team list' def test_team_list_team(): parsed = team.parse('team list testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'list' assert parsed.team.value == 'testteam' assert str(parsed) == 'team list testteam' def test_team_modify(): parsed = team.parse('team modify testteam displayName ' '{"text":"test successful"}') parsed: ParsedTeamCommand assert parsed.action.value == 'modify' assert parsed.team.value == 'testteam' assert parsed.option.value == 'displayName' assert parsed.value.value == '{"text":"test successful"}' assert str(parsed) == 'team modify testteam displayName ' \ '{"text":"test successful"}'
tests/commands/mc-1.13/test_team.py
from mcfunction.versions.mc_1_13.team import team, ParsedTeamCommand from mcfunction.nodes import EntityNode def test_team_add(): parsed = team.parse('team add testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'add' assert parsed.team.value == 'testteam' assert str(parsed) == 'team add testteam' def test_team_add_displayname(): parsed = team.parse('team add testteam {"text":"test successful"}') parsed: ParsedTeamCommand assert parsed.name.object['text'] == 'test successful' assert str(parsed) == 'team add testteam {"text":"test successful"}' def test_team_empty(): parsed = team.parse('team empty testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'empty' assert parsed.team.value == 'testteam' assert str(parsed) == 'team empty testteam' def test_team_join(): parsed = team.parse('team join testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'join' assert parsed.team.value == 'testteam' assert str(parsed) == 'team join testteam' def test_team_join_target(): parsed = team.parse('team join testteam @s') parsed: ParsedTeamCommand assert isinstance(parsed.target, EntityNode) assert str(parsed) == 'team join testteam @s' def test_team_leave(): parsed = team.parse('team leave @s') parsed: ParsedTeamCommand assert parsed.action.value == 'leave' assert isinstance(parsed.target, EntityNode) assert str(parsed) == 'team leave @s' def test_team_list(): parsed = team.parse('team list') parsed: ParsedTeamCommand assert parsed.action.value == 'list' assert str(parsed) == 'team list' def test_team_list_team(): parsed = team.parse('team list testteam') parsed: ParsedTeamCommand assert parsed.action.value == 'list' assert parsed.team.value == 'testteam' assert str(parsed) == 'team list testteam' def test_team_modify(): parsed = team.parse('team modify testteam displayName ' '{"text":"test successful"}') parsed: ParsedTeamCommand assert parsed.action.value == 'modify' assert parsed.team.value == 'testteam' assert parsed.option.value == 'displayName' assert parsed.value.value == '{"text":"test successful"}' assert str(parsed) == 'team modify testteam displayName ' \ '{"text":"test successful"}'
0.724773
0.722576
import discord from discord.ext import commands from discord.ext import pages from discord import Embed import pycordSuperUtils client = commands.Bot(command_prefix="-") embedc = discord.Color.from_rgb(255, 255, 255) @client.event async def on_ready(): print("Page manager is ready.", client.user) # The old buttonpaginator was removed from PSU! Here's a example for the official py-cord paginator @client.slash_command(name="paginator", description="Page manager") async def _paginator(ctx): await ctx.defer() invite = "https://discord.com/api/oauth2/authorize?client_id=828902907084537867&permissions=8&scope=bot%20applications.commands" page1 = Embed( color=embedc, title="**🤖 Help Menu**" ) page1.set_footer(text=ctx.guild.name) page1.set_author(name=ctx.author.display_name) page1.add_field(name="**🌐Features**", value="> Moderation \n> Information\n> Fun\n> Helpful Setups like applications, join2create and much more!", inline=False) page1.add_field(name="**📊 Stats**", value=f"```py\nGuilds: {len(client.guilds)}\nUsers: {len(client.users)}```", inline=False) page1.add_field(name="**🆘 Help & Links**", value=f"**Support Server**\n> [Join here](https://discord.gg/mQkydPS82f)\n**Developer**\n> Areo | 513786050271772673\n**Invite me**\n> [Invite now!]({invite})", inline=False) page2 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**🔨 Moderation Commands**" ) page2.set_footer(text=ctx.guild.name) page3 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**ℹ️ Information Commands**" ) page4 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**🎭 Fun Commands**" ) page5 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**⚙️ Setup Commands**" ) page5.set_footer(text=ctx.guild.name) page5.set_thumbnail(url=client.user.avatar.url) # Note: You can add as much embed as you want paginationList = [page1, page2, page3, page4, page5] # Creating buttons b1 = pages.PaginatorButton("next", label="▶️", style=discord.ButtonStyle.blurple) b2 = pages.PaginatorButton("first", label="⏪", style=discord.ButtonStyle.blurple) b4 = pages.PaginatorButton("last", label="⏩", style=discord.ButtonStyle.blurple) b3 = pages.PaginatorButton("prev", label="◀️", style=discord.ButtonStyle.blurple) button_list = [b1, b2, b3, b4] # initializing the paginator paginator = pages.Paginator(pages=paginationList, show_disabled=True, show_indicator=False, use_default_buttons=False, custom_buttons=button_list) # start paginating await paginator.respond(ctx.interaction, ephemeral=False) client.run("token")
examples/paginator.py
import discord from discord.ext import commands from discord.ext import pages from discord import Embed import pycordSuperUtils client = commands.Bot(command_prefix="-") embedc = discord.Color.from_rgb(255, 255, 255) @client.event async def on_ready(): print("Page manager is ready.", client.user) # The old buttonpaginator was removed from PSU! Here's a example for the official py-cord paginator @client.slash_command(name="paginator", description="Page manager") async def _paginator(ctx): await ctx.defer() invite = "https://discord.com/api/oauth2/authorize?client_id=828902907084537867&permissions=8&scope=bot%20applications.commands" page1 = Embed( color=embedc, title="**🤖 Help Menu**" ) page1.set_footer(text=ctx.guild.name) page1.set_author(name=ctx.author.display_name) page1.add_field(name="**🌐Features**", value="> Moderation \n> Information\n> Fun\n> Helpful Setups like applications, join2create and much more!", inline=False) page1.add_field(name="**📊 Stats**", value=f"```py\nGuilds: {len(client.guilds)}\nUsers: {len(client.users)}```", inline=False) page1.add_field(name="**🆘 Help & Links**", value=f"**Support Server**\n> [Join here](https://discord.gg/mQkydPS82f)\n**Developer**\n> Areo | 513786050271772673\n**Invite me**\n> [Invite now!]({invite})", inline=False) page2 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**🔨 Moderation Commands**" ) page2.set_footer(text=ctx.guild.name) page3 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**ℹ️ Information Commands**" ) page4 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**🎭 Fun Commands**" ) page5 = Embed( color=embedc, title="**🤖 Bot Help Menu**", description=f"**⚙️ Setup Commands**" ) page5.set_footer(text=ctx.guild.name) page5.set_thumbnail(url=client.user.avatar.url) # Note: You can add as much embed as you want paginationList = [page1, page2, page3, page4, page5] # Creating buttons b1 = pages.PaginatorButton("next", label="▶️", style=discord.ButtonStyle.blurple) b2 = pages.PaginatorButton("first", label="⏪", style=discord.ButtonStyle.blurple) b4 = pages.PaginatorButton("last", label="⏩", style=discord.ButtonStyle.blurple) b3 = pages.PaginatorButton("prev", label="◀️", style=discord.ButtonStyle.blurple) button_list = [b1, b2, b3, b4] # initializing the paginator paginator = pages.Paginator(pages=paginationList, show_disabled=True, show_indicator=False, use_default_buttons=False, custom_buttons=button_list) # start paginating await paginator.respond(ctx.interaction, ephemeral=False) client.run("token")
0.413122
0.275739
import atexit import signal import sys import os import time # Infoset imports from infoset.utils import log from infoset.utils import general class Daemon(object): """A generic daemon class. Usage: subclass the daemon class and override the run() method. Modified from http://www.jejik.com/files/examples/daemon3x.py """ def __init__(self, pidfile, lockfile=None): """Method for intializing the class. Args: pidfile: Name of PID file lockfile: Name of lock file Returns: None """ # Initialize key variables self.pidfile = pidfile self.lockfile = lockfile def daemonize(self): """Deamonize class. UNIX double fork mechanism. Args: None Returns: None """ # Create a parent process that will manage the child # when the code using this class is done. try: pid = os.fork() if pid > 0: # Exit first parent sys.exit(0) except OSError as err: log_message = ('Daemon fork #1 failed: %s') % (err) log_message = ('%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1060, log_message) # Decouple from parent environment os.chdir('/') os.setsid() os.umask(0) # Do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as err: log_message = ('Daemon fork #2 failed: %s') % (err) log_message = ('%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1061, log_message) # Redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() f_handle_si = open(os.devnull, 'r') # f_handle_so = open(os.devnull, 'a+') f_handle_so = open(os.devnull, 'a+') f_handle_se = open(os.devnull, 'a+') os.dup2(f_handle_si.fileno(), sys.stdin.fileno()) # os.dup2(f_handle_so.fileno(), sys.stdout.fileno()) os.dup2(f_handle_so.fileno(), sys.stdout.fileno()) os.dup2(f_handle_se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as f_handle: f_handle.write(pid + '\n') def delpid(self): """Delete the PID file. Args: None Returns: None """ # Delete file if os.path.exists(self.pidfile) is True: os.remove(self.pidfile) def dellock(self): """Delete the lock file. Args: None Returns: None """ # Delete file if self.lockfile is not None: if os.path.exists(self.lockfile) is True: os.remove(self.lockfile) def start(self): """Start the daemon. Args: None Returns: """ # Check for a pidfile to see if the daemon already runs try: with open(self.pidfile, 'r') as pf_handle: pid = int(pf_handle.read().strip()) except IOError: pid = None if pid: log_message = ( 'PID file: %s already exists. Daemon already running?' '') % (self.pidfile) log.log2die(1062, log_message) # Start the daemon self.daemonize() # Log success log_message = ('Daemon Started - PID file: %s') % (self.pidfile) log.log2info(1070, log_message) # Run code for daemon self.run() def force(self): """Stop the daemon by deleting the lock file first. Args: None Returns: """ # Delete lock file and stop self.dellock() self.stop() def stop(self): """Stop the daemon. Args: None Returns: """ # Get the pid from the pidfile try: with open(self.pidfile, 'r') as pf_handle: pid = int(pf_handle.read().strip()) except IOError: pid = None if not pid: log_message = ( 'PID file: %s does not exist. Daemon not running?' '') % (self.pidfile) log.log2warning(1063, log_message) # Not an error in a restart return # Try killing the daemon process try: while 1: # Sleep a while time.sleep(0.3) # Process lockfile state when trying to stop if self.lockfile is None: os.kill(pid, signal.SIGTERM) else: if os.path.exists(self.lockfile) is True: continue else: os.kill(pid, signal.SIGTERM) except OSError as err: error = str(err.args) if error.find("No such process") > 0: self.delpid() self.dellock() else: log_message = (str(err.args)) log_message = ( '%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1068, log_message) except: log_message = ( 'Unknown daemon "stop" error for PID file: %s' '') % (self.pidfile) log.log2die(1066, log_message) # Log success self.delpid() self.dellock() log_message = ('Daemon Stopped - PID file: %s') % (self.pidfile) log.log2info(1071, log_message) def restart(self): """Restart the daemon. Args: None Returns: """ # Restart self.stop() self.start() def status(self): """Get daemon status. Args: None Returns: """ # Get status if os.path.exists(self.pidfile) is True: print('Daemon is running') else: print('Daemon is stopped') def run(self): """You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ # Simple comment to pass linter pass class _Directory(object): """A class for creating the names of hidden directories.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.root = ('%s/.status') % (general.root_directory()) def pid(self): """Method for defining the hidden pid directory. Args: None Returns: value: pid directory """ # Return value = ('%s/pid') % self.root return value def lock(self): """Method for defining the hidden lock directory. Args: None Returns: value: lock directory """ # Return value = ('%s/lock') % self.root return value def id_agent(self): """Method for defining the hidden id_agent directory. Args: None Returns: value: id_agent directory """ # Return value = ('%s/id_agent') % self.root return value class _File(object): """A class for creating the names of hidden files.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.directory = _Directory() def pid(self, prefix, create=True): """Method for defining the hidden pid directory. Args: prefix: Prefix of file create: Create file if True Returns: value: pid directory """ # Return if create is True: _mkdir(self.directory.pid()) value = ('%s/%s.pid') % (self.directory.pid(), prefix) return value def lock(self, prefix, create=True): """Method for defining the hidden lock directory. Args: prefix: Prefix of file create: Create file if True Returns: value: lock directory """ # Return if create is True: _mkdir(self.directory.lock()) value = ('%s/%s.lock') % (self.directory.lock(), prefix) return value def id_agent(self, prefix): """Method for defining the hidden id_agent directory. Args: prefix: Prefix of file Returns: value: id_agent directory """ # Return _mkdir(self.directory.id_agent()) value = ('%s/%s.id_agent') % (self.directory.id_agent(), prefix) return value class _Touch(object): """A class for updating modifed times for hidden files.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.filez = _File() def pid(self, prefix): """Method for updating the hidden pid file. Args: prefix: Prefix of file Returns: None """ # Return timestamp = int(time.time()) filename = self.filez.pid(prefix) os.utime(filename, (timestamp, timestamp)) def pid_file(agent_name): """Get the pidfile for an agent. Args: agent_name: Agent name Returns: result: Name of pid file """ # Return f_obj = _File() result = f_obj.pid(agent_name) return result def pid_file_exists(agent_name): """Get the existence state of the pid_file. Args: agent_name: Agent name Returns: result: Name of pid file """ # Initialize key variables exists = False # Return f_obj = _File() result = f_obj.pid(agent_name, create=False) if os.path.isfile(result) is True: exists = True return exists def lock_file(agent_name): """Get the lockfile for an agent. Args: agent_name: Agent name Returns: result: Name of lock file """ # Return f_obj = _File() result = f_obj.lock(agent_name) return result def id_agent_file(agent_name): """Get the id_agentfile for an agent. Args: agent_name: Agent name Returns: result: Name of id_agent file """ # Return f_obj = _File() result = f_obj.id_agent(agent_name) return result def update_pid(agent_name): """Update the PID for agent. Args: agent_name: Agent name Returns: None """ # Update the PID file timestamp (important) update = _Touch() update.pid(agent_name) def _mkdir(directory): """Create a directory if it doesn't already exist. Args: directory: Directory name Returns: None """ # Do work if os.path.exists(directory) is False: os.makedirs(directory, mode=0o755) else: if os.path.isfile(directory) is True: log_message = ( '%s is not a directory.' '') % (directory) log.log2die(1043, log_message)
infoset/utils/daemon.py
import atexit import signal import sys import os import time # Infoset imports from infoset.utils import log from infoset.utils import general class Daemon(object): """A generic daemon class. Usage: subclass the daemon class and override the run() method. Modified from http://www.jejik.com/files/examples/daemon3x.py """ def __init__(self, pidfile, lockfile=None): """Method for intializing the class. Args: pidfile: Name of PID file lockfile: Name of lock file Returns: None """ # Initialize key variables self.pidfile = pidfile self.lockfile = lockfile def daemonize(self): """Deamonize class. UNIX double fork mechanism. Args: None Returns: None """ # Create a parent process that will manage the child # when the code using this class is done. try: pid = os.fork() if pid > 0: # Exit first parent sys.exit(0) except OSError as err: log_message = ('Daemon fork #1 failed: %s') % (err) log_message = ('%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1060, log_message) # Decouple from parent environment os.chdir('/') os.setsid() os.umask(0) # Do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError as err: log_message = ('Daemon fork #2 failed: %s') % (err) log_message = ('%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1061, log_message) # Redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() f_handle_si = open(os.devnull, 'r') # f_handle_so = open(os.devnull, 'a+') f_handle_so = open(os.devnull, 'a+') f_handle_se = open(os.devnull, 'a+') os.dup2(f_handle_si.fileno(), sys.stdin.fileno()) # os.dup2(f_handle_so.fileno(), sys.stdout.fileno()) os.dup2(f_handle_so.fileno(), sys.stdout.fileno()) os.dup2(f_handle_se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) with open(self.pidfile, 'w+') as f_handle: f_handle.write(pid + '\n') def delpid(self): """Delete the PID file. Args: None Returns: None """ # Delete file if os.path.exists(self.pidfile) is True: os.remove(self.pidfile) def dellock(self): """Delete the lock file. Args: None Returns: None """ # Delete file if self.lockfile is not None: if os.path.exists(self.lockfile) is True: os.remove(self.lockfile) def start(self): """Start the daemon. Args: None Returns: """ # Check for a pidfile to see if the daemon already runs try: with open(self.pidfile, 'r') as pf_handle: pid = int(pf_handle.read().strip()) except IOError: pid = None if pid: log_message = ( 'PID file: %s already exists. Daemon already running?' '') % (self.pidfile) log.log2die(1062, log_message) # Start the daemon self.daemonize() # Log success log_message = ('Daemon Started - PID file: %s') % (self.pidfile) log.log2info(1070, log_message) # Run code for daemon self.run() def force(self): """Stop the daemon by deleting the lock file first. Args: None Returns: """ # Delete lock file and stop self.dellock() self.stop() def stop(self): """Stop the daemon. Args: None Returns: """ # Get the pid from the pidfile try: with open(self.pidfile, 'r') as pf_handle: pid = int(pf_handle.read().strip()) except IOError: pid = None if not pid: log_message = ( 'PID file: %s does not exist. Daemon not running?' '') % (self.pidfile) log.log2warning(1063, log_message) # Not an error in a restart return # Try killing the daemon process try: while 1: # Sleep a while time.sleep(0.3) # Process lockfile state when trying to stop if self.lockfile is None: os.kill(pid, signal.SIGTERM) else: if os.path.exists(self.lockfile) is True: continue else: os.kill(pid, signal.SIGTERM) except OSError as err: error = str(err.args) if error.find("No such process") > 0: self.delpid() self.dellock() else: log_message = (str(err.args)) log_message = ( '%s - PID file: %s') % (log_message, self.pidfile) log.log2die(1068, log_message) except: log_message = ( 'Unknown daemon "stop" error for PID file: %s' '') % (self.pidfile) log.log2die(1066, log_message) # Log success self.delpid() self.dellock() log_message = ('Daemon Stopped - PID file: %s') % (self.pidfile) log.log2info(1071, log_message) def restart(self): """Restart the daemon. Args: None Returns: """ # Restart self.stop() self.start() def status(self): """Get daemon status. Args: None Returns: """ # Get status if os.path.exists(self.pidfile) is True: print('Daemon is running') else: print('Daemon is stopped') def run(self): """You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ # Simple comment to pass linter pass class _Directory(object): """A class for creating the names of hidden directories.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.root = ('%s/.status') % (general.root_directory()) def pid(self): """Method for defining the hidden pid directory. Args: None Returns: value: pid directory """ # Return value = ('%s/pid') % self.root return value def lock(self): """Method for defining the hidden lock directory. Args: None Returns: value: lock directory """ # Return value = ('%s/lock') % self.root return value def id_agent(self): """Method for defining the hidden id_agent directory. Args: None Returns: value: id_agent directory """ # Return value = ('%s/id_agent') % self.root return value class _File(object): """A class for creating the names of hidden files.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.directory = _Directory() def pid(self, prefix, create=True): """Method for defining the hidden pid directory. Args: prefix: Prefix of file create: Create file if True Returns: value: pid directory """ # Return if create is True: _mkdir(self.directory.pid()) value = ('%s/%s.pid') % (self.directory.pid(), prefix) return value def lock(self, prefix, create=True): """Method for defining the hidden lock directory. Args: prefix: Prefix of file create: Create file if True Returns: value: lock directory """ # Return if create is True: _mkdir(self.directory.lock()) value = ('%s/%s.lock') % (self.directory.lock(), prefix) return value def id_agent(self, prefix): """Method for defining the hidden id_agent directory. Args: prefix: Prefix of file Returns: value: id_agent directory """ # Return _mkdir(self.directory.id_agent()) value = ('%s/%s.id_agent') % (self.directory.id_agent(), prefix) return value class _Touch(object): """A class for updating modifed times for hidden files.""" def __init__(self): """Method for intializing the class. Args: None Returns: None """ # Initialize key variables self.filez = _File() def pid(self, prefix): """Method for updating the hidden pid file. Args: prefix: Prefix of file Returns: None """ # Return timestamp = int(time.time()) filename = self.filez.pid(prefix) os.utime(filename, (timestamp, timestamp)) def pid_file(agent_name): """Get the pidfile for an agent. Args: agent_name: Agent name Returns: result: Name of pid file """ # Return f_obj = _File() result = f_obj.pid(agent_name) return result def pid_file_exists(agent_name): """Get the existence state of the pid_file. Args: agent_name: Agent name Returns: result: Name of pid file """ # Initialize key variables exists = False # Return f_obj = _File() result = f_obj.pid(agent_name, create=False) if os.path.isfile(result) is True: exists = True return exists def lock_file(agent_name): """Get the lockfile for an agent. Args: agent_name: Agent name Returns: result: Name of lock file """ # Return f_obj = _File() result = f_obj.lock(agent_name) return result def id_agent_file(agent_name): """Get the id_agentfile for an agent. Args: agent_name: Agent name Returns: result: Name of id_agent file """ # Return f_obj = _File() result = f_obj.id_agent(agent_name) return result def update_pid(agent_name): """Update the PID for agent. Args: agent_name: Agent name Returns: None """ # Update the PID file timestamp (important) update = _Touch() update.pid(agent_name) def _mkdir(directory): """Create a directory if it doesn't already exist. Args: directory: Directory name Returns: None """ # Do work if os.path.exists(directory) is False: os.makedirs(directory, mode=0o755) else: if os.path.isfile(directory) is True: log_message = ( '%s is not a directory.' '') % (directory) log.log2die(1043, log_message)
0.494873
0.122786
import imp from generator.tree.builder import build_ast from generator.tree.nodes.trivial.namespace import Namespace from .generators.cpp import CppGenerator from .generators.dot import DotGenerator from .generators.go import GoGenerator from .generators.python import PythonGenerator from .generators.rust import RustGenerator from .generators.flatdata import FlatdataGenerator class Engine: """ Flatdata Generator Engine. Implements code generation from the given flatdata schema. """ _GENERATORS = { "cpp": CppGenerator, "dot": DotGenerator, "go": GoGenerator, "py": PythonGenerator, "rust": RustGenerator, "flatdata" : FlatdataGenerator } @classmethod def available_generators(cls): """ Lists names of available code generators. """ return list(cls._GENERATORS.keys()) def __init__(self, schema): """ Instantiates generator engine for a given schema. :raises FlatdataSyntaxError """ self.schema = schema self.tree = build_ast(schema) def render(self, generator_name): """ Render schema with a given generator :param generator_name: """ generator = self._create_generator(generator_name) if generator is None: raise ValueError( "Generator %s not implemented. Available options: %s" % generator_name, self.available_generators() ) output_content = generator.render(self.tree) return output_content def render_python_module(self, module_name=None, archive_name=None): """ Render python module. :param module_name: Module name to use. If none, root namespace name is used. :param archive_name: Archive name to lookup, if specified, archive type is returned along with the model """ root_namespace = self._find_root_namespace(self.tree) module_code = self.render("py") module = imp.new_module(module_name if module_name is not None else root_namespace.name) #pylint: disable=exec-used exec(module_code, module.__dict__) if archive_name is None: return module name = root_namespace.name + "_" + archive_name archive_type = getattr(module, name) if archive_name else None return module, archive_type @classmethod def _create_generator(cls, name): generator_type = cls._GENERATORS.get(name, None) if generator_type is None: return None return generator_type() @staticmethod def _find_root_namespace(tree): root_children = tree.root.children root_namespaces = [ child for child in root_children if isinstance(child, Namespace) and "builtin" not in child.name ] if not root_namespaces: raise RuntimeError("No root namespace found.") elif len(root_namespaces) > 1: raise RuntimeError("Ambiguous root namespace. Could not find root archive.") return root_namespaces[0]
flatdata-py/generator/engine.py
import imp from generator.tree.builder import build_ast from generator.tree.nodes.trivial.namespace import Namespace from .generators.cpp import CppGenerator from .generators.dot import DotGenerator from .generators.go import GoGenerator from .generators.python import PythonGenerator from .generators.rust import RustGenerator from .generators.flatdata import FlatdataGenerator class Engine: """ Flatdata Generator Engine. Implements code generation from the given flatdata schema. """ _GENERATORS = { "cpp": CppGenerator, "dot": DotGenerator, "go": GoGenerator, "py": PythonGenerator, "rust": RustGenerator, "flatdata" : FlatdataGenerator } @classmethod def available_generators(cls): """ Lists names of available code generators. """ return list(cls._GENERATORS.keys()) def __init__(self, schema): """ Instantiates generator engine for a given schema. :raises FlatdataSyntaxError """ self.schema = schema self.tree = build_ast(schema) def render(self, generator_name): """ Render schema with a given generator :param generator_name: """ generator = self._create_generator(generator_name) if generator is None: raise ValueError( "Generator %s not implemented. Available options: %s" % generator_name, self.available_generators() ) output_content = generator.render(self.tree) return output_content def render_python_module(self, module_name=None, archive_name=None): """ Render python module. :param module_name: Module name to use. If none, root namespace name is used. :param archive_name: Archive name to lookup, if specified, archive type is returned along with the model """ root_namespace = self._find_root_namespace(self.tree) module_code = self.render("py") module = imp.new_module(module_name if module_name is not None else root_namespace.name) #pylint: disable=exec-used exec(module_code, module.__dict__) if archive_name is None: return module name = root_namespace.name + "_" + archive_name archive_type = getattr(module, name) if archive_name else None return module, archive_type @classmethod def _create_generator(cls, name): generator_type = cls._GENERATORS.get(name, None) if generator_type is None: return None return generator_type() @staticmethod def _find_root_namespace(tree): root_children = tree.root.children root_namespaces = [ child for child in root_children if isinstance(child, Namespace) and "builtin" not in child.name ] if not root_namespaces: raise RuntimeError("No root namespace found.") elif len(root_namespaces) > 1: raise RuntimeError("Ambiguous root namespace. Could not find root archive.") return root_namespaces[0]
0.73678
0.297582
import collections import datetime import json import multiprocessing.pool import random import time import traceback import types from django import forms from django.db import models import django.core.mail import django.urls import django.forms.renderers from cached_property import cached_property from constance import config import jinja2 from modules.smartq import api import frontend.forms import users.models # TODO(<NAME>): consider replacing with # https://pypi.python.org/pypi/pysandbox/ class Sandbox: """ A simple sandbox to execute code stored in a database. Allows to run functions in a separate thread with a timeout. Passes all the exceptions over adding TimeoutException to them. """ @classmethod def instance(cls): if not hasattr(cls, '_instance'): cls._instance = cls() return cls._instance def __init__(self): self.pool = multiprocessing.pool.ThreadPool(processes=1) def run(self, function, args=None, kwargs=None, timeout=None): args = args or [] kwargs = kwargs or {} async_result = self.pool.apply_async(function, args, kwargs) return async_result.get(timeout) class Question(models.Model): short_name = models.CharField( max_length=100, unique=True, help_text="Используется в url'ах. Например, build-heap.") template_html = models.TextField( help_text='Jinja2 шаблон для HTML кода вопроса.') template_css = models.TextField( blank=True, default='', help_text='Jinja2 шаблон для CSS кода вопроса.') template_js = models.TextField( blank=True, default='', help_text='Jinja2 шаблон для Javascript кода вопроса.') # TODO(<NAME>): consider adding version control # TODO(<NAME>): add a link to documentation to the help text. As soon # as we have it. code = models.TextField( help_text='Код python модуля, в котором должны быть определены классы ' 'Generator и Checker. В модуле изначально доступен модуль ' 'api. Generator и Checker должны быть отнаследованы от ' 'api.Generator и api.Checker соответственно.') # TODO(<NAME>): cache compiled code in a database created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) _implementation_cache = {} _template_cache = {} def __str__(self): return self.short_name @property def _module_name(self): return self.short_name.replace('-', '_') @property def _implementation(self): name = self._module_name module = self._implementation_cache.get(name) if module is None or module.modified_date < self.modified_date: try: module = types.ModuleType(name=name) module.api = api Sandbox.instance().run( exec, [self.code, module.__dict__], timeout=config.SMARTQ_MODULE_EXECUTION_TIMEOUT) module.modified_date = self.modified_date self._implementation_cache[name] = module except Exception: message = ('{}: smartq: failed running question code\n' ' question = {}\n' '{}\n'.format(datetime.datetime.now(), self, traceback.format_exc())) print(message) django.core.mail.mail_admins( 'smartq: failed running question code', message) # TODO(<NAME>): fail in a more graceful way. It should be # easy for the code using smartq to show some kind of # "Something went wrong" screen to the user. raise return module def _compiled_template(self, kind, template): key = '{}:{}'.format(kind, self.short_name) if key not in self._template_cache: self._template_cache[key] = jinja2.Template(template) return self._template_cache[key] @property def compiled_template_html(self): return self._compiled_template('html', self.template_html) @property def compiled_template_css(self): return self._compiled_template('css', self.template_html) @property def compiled_template_js(self): return self._compiled_template('js', self.template_html) def save(self, *args, **kwargs): # Check that the code actually compiles. It will throw an exception and # prevent saving if not. compile(self.code, self._module_name, 'exec') super().save(*args, **kwargs) def create_instance(self, user, seed=None, klass=None): if seed is None: seed = time.time() if klass is None: klass = GeneratedQuestion if not issubclass(klass, GeneratedQuestion): raise ValueError("Generated question class should be a subclass " "of GeneratedQuestion") # Make it possible to store seed in a database seed = str(seed)[:100] # Standard python random is used because we don't need results to be # consistent across different python version and hardware. All the # generated data is stored in the database along with the original seed, # so we don't need to regenerate it. try: state = random.getstate() random.seed(seed) generator = Sandbox.instance().run( self._implementation.Generator, timeout=config.SMARTQ_GENERATOR_INSTANTIATION_TIMEOUT, ) data = Sandbox.instance().run( generator.generate, timeout=config.SMARTQ_GENERATOR_TIMEOUT, ) except Exception: message = ('{}: smartq: failed while generating quesiton\n' ' question = {}\n' ' user = {}\n' ' seed = {}\n' '{}\n'.format(datetime.datetime.now(), self, user, seed, traceback.format_exc())) print(message) django.core.mail.mail_admins( 'smartq: failed while generating question', message) # TODO(<NAME>): fail in a more graceful way. It should be # easy for the code using smartq to show some kind of # "Something went wrong" screen to the user. raise finally: random.setstate(state) return klass.objects.create( base_question=self, user=user, seed=seed, data_json=json.dumps(data.__dict__)) class GeneratedQuestion(models.Model): base_question = models.ForeignKey(Question, on_delete=models.CASCADE) seed = models.CharField( max_length=100, help_text='По-умолчанию устанавливается в текущее системное время. ' 'Используется только для отладки, так как сгенерированные ' 'для вопроса данные целиком храняться в базе.', ) user = models.ForeignKey( users.models.User, on_delete=models.CASCADE, related_name='+', help_text='Пользователь, которому выдан этот вопрос. Другие ' 'пользователи не смогут на него отвечать.', ) data_json = models.TextField( help_text='Возвращённый генератором объект, сериализованный в JSON' ) answer_json = models.TextField( blank=True, help_text='Последний ответ на вопрос, сериализованный в JSON' ) # TODO(<NAME>): consider using custom ModelManager which does # serialization inside? def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) data_dict = json.loads(self.data_json) if self.data_json else {} self.data = api.GeneratedQuestionData(**data_dict) self._form = None def __str__(self): return '{}({})'.format(self.base_question, self.seed) @cached_property def form_type(self): if self.id is None: return None return _make_form_type( self.id, self._question_div_id, self.data.answer_fields) @property def form(self): if self._form is None: self._form = self.form_type(self.answer) return self._form @form.setter def form(self, value): self._form = value @property def answer(self): return json.loads(self.answer_json) if self.answer_json else None @answer.setter def answer(self, value): self.answer_json = json.dumps(value) def save_answer(self, data): self.answer = { field.html_name: data[field.html_name] for field in self.form if field.html_name in data } self.form = self.form_type(self.answer) self.save() def html(self): rendered_template = (jinja2.Template(self.base_question.template_html) .render(self._template_context)) return '<div id="{}" class="smartq-question">{}</div>'.format( self._question_div_id, rendered_template) def css(self): return (jinja2.Template(self.base_question.template_css) .render(self._template_context)) def js(self): rendered_template = (jinja2.Template(self.base_question.template_js) .render(self._template_context)) return '(function() {{ {} }})();'.format(rendered_template) @property def _template_context(self): return { 'short_name': self.base_question.short_name, 'question_id': self.id, 'question_html_id': self._question_div_id, 'data': self.data, 'form': self.form, } @property def _question_div_id(self): return 'smartq-' + str(self.id) def check_answer(self, data): self.save_answer(data) if not self.form.is_valid(): return api.CheckerResult( status=api.Checker.Status.PRESENTATION_ERROR) answer_dict = collections.OrderedDict( (name, self.form.cleaned_data[name]) for name in self.form.field_order) result = None try: checker = Sandbox.instance().run( self.base_question._implementation.Checker, timeout=config.SMARTQ_CHECKER_INSTANTIATION_TIMEOUT ) result = Sandbox.instance().run( checker.check, args=[self.data, answer_dict], timeout=config.SMARTQ_CHECKER_TIMEOUT ) except Exception: #pylint: disable=broad-except result = api.CheckerResult( status=api.Checker.Status.CHECK_FAILED, message="{}: [id={}, question={}] {}".format( datetime.datetime.now(), self.id, self, traceback.format_exc() ) ) if result.status == api.Checker.Status.CHECK_FAILED: message = ('{}: smartq: CheckFailed\n' ' generated_question_id = {}\n' ' question = {}\n' '{}\n'.format(datetime.datetime.now(), self.id, self, result.message)) print(message) django.core.mail.mail_admins('smartq: CheckFailed', message) return result # TODO(<NAME>): move to a separate module with staff models class StaffGeneratedQuestion(GeneratedQuestion): @classmethod def get_instance(cls, user, base_question): try: instance = cls.objects.get( user=user, base_question=base_question) except cls.DoesNotExist: instance = base_question.create_instance(user, klass=cls) return instance @classmethod def regenerate(cls, user, base_question): cls.objects.filter( user=user, base_question=base_question ).delete() return base_question.create_instance(user, klass=cls) def _make_form_type(generated_question_id, prefix, field_specs): fields = {} field_order = [] for i, spec in enumerate(field_specs): field_name = spec.get('name', 'element_' + str(i)) # Attributes to add to the input tag attrs = { 'data-smartq-id': generated_question_id, 'data-smartq-save-url': django.urls.reverse( 'smartq:save_answer', kwargs={'generated_question_id': generated_question_id} ), } if 'validation_regexp' in spec: attrs['data-smartq-validation-regexp'] = spec['validation_regexp'] if 'validation_regexp_message' in spec: attrs['data-smartq-validation-regexp-message'] = ( spec['validation_regexp_message']) if 'placeholder' in spec: attrs['placeholder'] = spec['placeholder'] required = spec.get('required', True) field = None if spec['type'] == api.AnswerFieldSpec.Type.TEXT: if spec['multiline']: widget = frontend.forms.SistemaTextarea(attrs=attrs) else: widget = frontend.forms.SistemaTextInput(attrs=attrs) field = forms.CharField( required=required, min_length=spec.get('min_length'), max_length=spec.get('max_length'), widget=widget) if spec['type'] == api.AnswerFieldSpec.Type.INTEGER: field = forms.IntegerField( required=required, min_value=spec.get('min_value'), max_value=spec.get('max_value'), widget=frontend.forms.SistemaNumberInput(attrs=attrs)) if field is None: raise ValueError('Unknown field type') fields[field_name] = field field_order.append(field_name) return type('SmartQForm', (forms.BaseForm,), { 'default_renderer': django.forms.renderers.Jinja2, 'base_fields': fields, 'field_order': field_order, 'prefix': prefix, })
src/web/modules/smartq/models.py
import collections import datetime import json import multiprocessing.pool import random import time import traceback import types from django import forms from django.db import models import django.core.mail import django.urls import django.forms.renderers from cached_property import cached_property from constance import config import jinja2 from modules.smartq import api import frontend.forms import users.models # TODO(<NAME>): consider replacing with # https://pypi.python.org/pypi/pysandbox/ class Sandbox: """ A simple sandbox to execute code stored in a database. Allows to run functions in a separate thread with a timeout. Passes all the exceptions over adding TimeoutException to them. """ @classmethod def instance(cls): if not hasattr(cls, '_instance'): cls._instance = cls() return cls._instance def __init__(self): self.pool = multiprocessing.pool.ThreadPool(processes=1) def run(self, function, args=None, kwargs=None, timeout=None): args = args or [] kwargs = kwargs or {} async_result = self.pool.apply_async(function, args, kwargs) return async_result.get(timeout) class Question(models.Model): short_name = models.CharField( max_length=100, unique=True, help_text="Используется в url'ах. Например, build-heap.") template_html = models.TextField( help_text='Jinja2 шаблон для HTML кода вопроса.') template_css = models.TextField( blank=True, default='', help_text='Jinja2 шаблон для CSS кода вопроса.') template_js = models.TextField( blank=True, default='', help_text='Jinja2 шаблон для Javascript кода вопроса.') # TODO(<NAME>): consider adding version control # TODO(<NAME>): add a link to documentation to the help text. As soon # as we have it. code = models.TextField( help_text='Код python модуля, в котором должны быть определены классы ' 'Generator и Checker. В модуле изначально доступен модуль ' 'api. Generator и Checker должны быть отнаследованы от ' 'api.Generator и api.Checker соответственно.') # TODO(<NAME>): cache compiled code in a database created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) _implementation_cache = {} _template_cache = {} def __str__(self): return self.short_name @property def _module_name(self): return self.short_name.replace('-', '_') @property def _implementation(self): name = self._module_name module = self._implementation_cache.get(name) if module is None or module.modified_date < self.modified_date: try: module = types.ModuleType(name=name) module.api = api Sandbox.instance().run( exec, [self.code, module.__dict__], timeout=config.SMARTQ_MODULE_EXECUTION_TIMEOUT) module.modified_date = self.modified_date self._implementation_cache[name] = module except Exception: message = ('{}: smartq: failed running question code\n' ' question = {}\n' '{}\n'.format(datetime.datetime.now(), self, traceback.format_exc())) print(message) django.core.mail.mail_admins( 'smartq: failed running question code', message) # TODO(<NAME>): fail in a more graceful way. It should be # easy for the code using smartq to show some kind of # "Something went wrong" screen to the user. raise return module def _compiled_template(self, kind, template): key = '{}:{}'.format(kind, self.short_name) if key not in self._template_cache: self._template_cache[key] = jinja2.Template(template) return self._template_cache[key] @property def compiled_template_html(self): return self._compiled_template('html', self.template_html) @property def compiled_template_css(self): return self._compiled_template('css', self.template_html) @property def compiled_template_js(self): return self._compiled_template('js', self.template_html) def save(self, *args, **kwargs): # Check that the code actually compiles. It will throw an exception and # prevent saving if not. compile(self.code, self._module_name, 'exec') super().save(*args, **kwargs) def create_instance(self, user, seed=None, klass=None): if seed is None: seed = time.time() if klass is None: klass = GeneratedQuestion if not issubclass(klass, GeneratedQuestion): raise ValueError("Generated question class should be a subclass " "of GeneratedQuestion") # Make it possible to store seed in a database seed = str(seed)[:100] # Standard python random is used because we don't need results to be # consistent across different python version and hardware. All the # generated data is stored in the database along with the original seed, # so we don't need to regenerate it. try: state = random.getstate() random.seed(seed) generator = Sandbox.instance().run( self._implementation.Generator, timeout=config.SMARTQ_GENERATOR_INSTANTIATION_TIMEOUT, ) data = Sandbox.instance().run( generator.generate, timeout=config.SMARTQ_GENERATOR_TIMEOUT, ) except Exception: message = ('{}: smartq: failed while generating quesiton\n' ' question = {}\n' ' user = {}\n' ' seed = {}\n' '{}\n'.format(datetime.datetime.now(), self, user, seed, traceback.format_exc())) print(message) django.core.mail.mail_admins( 'smartq: failed while generating question', message) # TODO(<NAME>): fail in a more graceful way. It should be # easy for the code using smartq to show some kind of # "Something went wrong" screen to the user. raise finally: random.setstate(state) return klass.objects.create( base_question=self, user=user, seed=seed, data_json=json.dumps(data.__dict__)) class GeneratedQuestion(models.Model): base_question = models.ForeignKey(Question, on_delete=models.CASCADE) seed = models.CharField( max_length=100, help_text='По-умолчанию устанавливается в текущее системное время. ' 'Используется только для отладки, так как сгенерированные ' 'для вопроса данные целиком храняться в базе.', ) user = models.ForeignKey( users.models.User, on_delete=models.CASCADE, related_name='+', help_text='Пользователь, которому выдан этот вопрос. Другие ' 'пользователи не смогут на него отвечать.', ) data_json = models.TextField( help_text='Возвращённый генератором объект, сериализованный в JSON' ) answer_json = models.TextField( blank=True, help_text='Последний ответ на вопрос, сериализованный в JSON' ) # TODO(<NAME>): consider using custom ModelManager which does # serialization inside? def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) data_dict = json.loads(self.data_json) if self.data_json else {} self.data = api.GeneratedQuestionData(**data_dict) self._form = None def __str__(self): return '{}({})'.format(self.base_question, self.seed) @cached_property def form_type(self): if self.id is None: return None return _make_form_type( self.id, self._question_div_id, self.data.answer_fields) @property def form(self): if self._form is None: self._form = self.form_type(self.answer) return self._form @form.setter def form(self, value): self._form = value @property def answer(self): return json.loads(self.answer_json) if self.answer_json else None @answer.setter def answer(self, value): self.answer_json = json.dumps(value) def save_answer(self, data): self.answer = { field.html_name: data[field.html_name] for field in self.form if field.html_name in data } self.form = self.form_type(self.answer) self.save() def html(self): rendered_template = (jinja2.Template(self.base_question.template_html) .render(self._template_context)) return '<div id="{}" class="smartq-question">{}</div>'.format( self._question_div_id, rendered_template) def css(self): return (jinja2.Template(self.base_question.template_css) .render(self._template_context)) def js(self): rendered_template = (jinja2.Template(self.base_question.template_js) .render(self._template_context)) return '(function() {{ {} }})();'.format(rendered_template) @property def _template_context(self): return { 'short_name': self.base_question.short_name, 'question_id': self.id, 'question_html_id': self._question_div_id, 'data': self.data, 'form': self.form, } @property def _question_div_id(self): return 'smartq-' + str(self.id) def check_answer(self, data): self.save_answer(data) if not self.form.is_valid(): return api.CheckerResult( status=api.Checker.Status.PRESENTATION_ERROR) answer_dict = collections.OrderedDict( (name, self.form.cleaned_data[name]) for name in self.form.field_order) result = None try: checker = Sandbox.instance().run( self.base_question._implementation.Checker, timeout=config.SMARTQ_CHECKER_INSTANTIATION_TIMEOUT ) result = Sandbox.instance().run( checker.check, args=[self.data, answer_dict], timeout=config.SMARTQ_CHECKER_TIMEOUT ) except Exception: #pylint: disable=broad-except result = api.CheckerResult( status=api.Checker.Status.CHECK_FAILED, message="{}: [id={}, question={}] {}".format( datetime.datetime.now(), self.id, self, traceback.format_exc() ) ) if result.status == api.Checker.Status.CHECK_FAILED: message = ('{}: smartq: CheckFailed\n' ' generated_question_id = {}\n' ' question = {}\n' '{}\n'.format(datetime.datetime.now(), self.id, self, result.message)) print(message) django.core.mail.mail_admins('smartq: CheckFailed', message) return result # TODO(<NAME>): move to a separate module with staff models class StaffGeneratedQuestion(GeneratedQuestion): @classmethod def get_instance(cls, user, base_question): try: instance = cls.objects.get( user=user, base_question=base_question) except cls.DoesNotExist: instance = base_question.create_instance(user, klass=cls) return instance @classmethod def regenerate(cls, user, base_question): cls.objects.filter( user=user, base_question=base_question ).delete() return base_question.create_instance(user, klass=cls) def _make_form_type(generated_question_id, prefix, field_specs): fields = {} field_order = [] for i, spec in enumerate(field_specs): field_name = spec.get('name', 'element_' + str(i)) # Attributes to add to the input tag attrs = { 'data-smartq-id': generated_question_id, 'data-smartq-save-url': django.urls.reverse( 'smartq:save_answer', kwargs={'generated_question_id': generated_question_id} ), } if 'validation_regexp' in spec: attrs['data-smartq-validation-regexp'] = spec['validation_regexp'] if 'validation_regexp_message' in spec: attrs['data-smartq-validation-regexp-message'] = ( spec['validation_regexp_message']) if 'placeholder' in spec: attrs['placeholder'] = spec['placeholder'] required = spec.get('required', True) field = None if spec['type'] == api.AnswerFieldSpec.Type.TEXT: if spec['multiline']: widget = frontend.forms.SistemaTextarea(attrs=attrs) else: widget = frontend.forms.SistemaTextInput(attrs=attrs) field = forms.CharField( required=required, min_length=spec.get('min_length'), max_length=spec.get('max_length'), widget=widget) if spec['type'] == api.AnswerFieldSpec.Type.INTEGER: field = forms.IntegerField( required=required, min_value=spec.get('min_value'), max_value=spec.get('max_value'), widget=frontend.forms.SistemaNumberInput(attrs=attrs)) if field is None: raise ValueError('Unknown field type') fields[field_name] = field field_order.append(field_name) return type('SmartQForm', (forms.BaseForm,), { 'default_renderer': django.forms.renderers.Jinja2, 'base_fields': fields, 'field_order': field_order, 'prefix': prefix, })
0.26923
0.106319
import json import jwt from fastapi import Depends, HTTPException, Path, Query from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND from . import enums from .factory import app auth_schema = HTTPBearer() async def jwt_required( request: Request, token: HTTPAuthorizationCredentials = Depends(auth_schema) ): credentials_exception = HTTPException(HTTP_401_UNAUTHORIZED) try: payload = jwt.decode(token.credentials, app.admin_secret) user_id = payload.get("user_id") if user_id is None: raise credentials_exception except jwt.PyJWTError: raise credentials_exception request.scope["user_id"] = user_id return user_id async def jwt_optional(request: Request): authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if credentials: try: payload = jwt.decode(credentials, app.admin_secret) user_id = payload.get("user_id") request.scope["user_id"] = user_id return user_id except jwt.PyJWTError: pass return class QueryItem(BaseModel): page: int = 1 sort: dict where: dict = {} with_: dict = {} size: int = 10 sort: dict = {} class Config: fields = {"with_": "with"} def get_query(query=Query(...)): query = json.loads(query) return QueryItem.parse_obj(query) def get_model(resource: str = Path(...)): model = app.models.get(resource) return model async def parse_body(request: Request, resource: str = Path(...)): body = await request.json() resource = await app.get_resource(resource, exclude_pk=True, exclude_m2m_field=False) resource_fields = resource.resource_fields.keys() ret = {} for key in resource_fields: v = body.get(key) if v is not None: ret[key] = v return ret, resource_fields async def get_current_user(user_id=Depends(jwt_required)): user = await app.user_model.get_or_none(pk=user_id) if not user: raise HTTPException(HTTP_404_NOT_FOUND) return user class PermissionsChecker: def __init__(self, action: enums.PermissionAction): self.action = action async def __call__(self, resource: str = Path(...), user=Depends(get_current_user)): if not app.permission or user.is_superuser: return if not user.is_active: raise HTTPException(status_code=HTTP_403_FORBIDDEN) has_permission = False await user.fetch_related("roles") for role in user.roles: if await role.permissions.filter(model=resource, action=self.action): has_permission = True break if not has_permission: raise HTTPException(status_code=HTTP_403_FORBIDDEN) read_checker = PermissionsChecker(action=enums.PermissionAction.read) create_checker = PermissionsChecker(action=enums.PermissionAction.create) update_checker = PermissionsChecker(action=enums.PermissionAction.update) delete_checker = PermissionsChecker(action=enums.PermissionAction.delete)
fastapi_admin/depends.py
import json import jwt from fastapi import Depends, HTTPException, Path, Query from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND from . import enums from .factory import app auth_schema = HTTPBearer() async def jwt_required( request: Request, token: HTTPAuthorizationCredentials = Depends(auth_schema) ): credentials_exception = HTTPException(HTTP_401_UNAUTHORIZED) try: payload = jwt.decode(token.credentials, app.admin_secret) user_id = payload.get("user_id") if user_id is None: raise credentials_exception except jwt.PyJWTError: raise credentials_exception request.scope["user_id"] = user_id return user_id async def jwt_optional(request: Request): authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if credentials: try: payload = jwt.decode(credentials, app.admin_secret) user_id = payload.get("user_id") request.scope["user_id"] = user_id return user_id except jwt.PyJWTError: pass return class QueryItem(BaseModel): page: int = 1 sort: dict where: dict = {} with_: dict = {} size: int = 10 sort: dict = {} class Config: fields = {"with_": "with"} def get_query(query=Query(...)): query = json.loads(query) return QueryItem.parse_obj(query) def get_model(resource: str = Path(...)): model = app.models.get(resource) return model async def parse_body(request: Request, resource: str = Path(...)): body = await request.json() resource = await app.get_resource(resource, exclude_pk=True, exclude_m2m_field=False) resource_fields = resource.resource_fields.keys() ret = {} for key in resource_fields: v = body.get(key) if v is not None: ret[key] = v return ret, resource_fields async def get_current_user(user_id=Depends(jwt_required)): user = await app.user_model.get_or_none(pk=user_id) if not user: raise HTTPException(HTTP_404_NOT_FOUND) return user class PermissionsChecker: def __init__(self, action: enums.PermissionAction): self.action = action async def __call__(self, resource: str = Path(...), user=Depends(get_current_user)): if not app.permission or user.is_superuser: return if not user.is_active: raise HTTPException(status_code=HTTP_403_FORBIDDEN) has_permission = False await user.fetch_related("roles") for role in user.roles: if await role.permissions.filter(model=resource, action=self.action): has_permission = True break if not has_permission: raise HTTPException(status_code=HTTP_403_FORBIDDEN) read_checker = PermissionsChecker(action=enums.PermissionAction.read) create_checker = PermissionsChecker(action=enums.PermissionAction.create) update_checker = PermissionsChecker(action=enums.PermissionAction.update) delete_checker = PermissionsChecker(action=enums.PermissionAction.delete)
0.412057
0.066387
import numpy as np import paddle import paddle.nn as nn from ..registry import BACKBONES import sys def get_hop_distance(num_node, edge, max_hop=1): A = np.zeros((num_node, num_node)) for i, j in edge: A[j, i] = 1 A[i, j] = 1 # compute hop steps hop_dis = np.zeros((num_node, num_node)) + np.inf transfer_mat = [np.linalg.matrix_power(A, d) for d in range(max_hop + 1)] arrive_mat = (np.stack(transfer_mat) > 0) for d in range(max_hop, -1, -1): hop_dis[arrive_mat[d]] = d return hop_dis def normalize_digraph(A): Dl = np.sum(A, 0) num_node = A.shape[0] Dn = np.zeros((num_node, num_node)) for i in range(num_node): if Dl[i] > 0: Dn[i, i] = Dl[i] ** (-1) AD = np.dot(A, Dn) return AD class Graph(): def __init__(self, layout='openpose', strategy='uniform', max_hop=1, dilation=1): self.max_hop = max_hop self.dilation = dilation self.get_edge(layout) self.hop_dis = get_hop_distance(self.num_node, self.edge, max_hop=max_hop) self.get_adjacency(strategy) def __str__(self): return self.A def get_edge(self, layout): # edge is a list of [child, parent] paris if layout == 'fsd10': self.num_node = 25 self_link = [(i, i) for i in range(self.num_node)] neighbor_link = [(1, 8), (0, 1), (15, 0), (17, 15), (16, 0), (18, 16), (5, 1), (6, 5), (7, 6), (2, 1), (3, 2), (4, 3), (9, 8), (10, 9), (11, 10), (24, 11), (22, 11), (23, 22), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19)] self.edge = self_link + neighbor_link self.center = 8 elif layout == 'ntu-rgb+d': self.num_node = 25 self_link = [(i, i) for i in range(self.num_node)] neighbor_1base = [(1, 2), (2, 21), (3, 21), (4, 3), (5, 21), (6, 5), (7, 6), (8, 7), (9, 21), (10, 9), (11, 10), (12, 11), (13, 1), (14, 13), (15, 14), (16, 15), (17, 1), (18, 17), (19, 18), (20, 19), (22, 23), (23, 8), (24, 25), (25, 12)] neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base] self.edge = self_link + neighbor_link self.center = 21 - 1 else: raise ValueError("Do Not Exist This Layout.") def get_adjacency(self, strategy): valid_hop = range(0, self.max_hop + 1, self.dilation) adjacency = np.zeros((self.num_node, self.num_node)) for hop in valid_hop: adjacency[self.hop_dis == hop] = 1 normalize_adjacency = normalize_digraph(adjacency) if strategy == 'spatial': A = [] for hop in valid_hop: a_root = np.zeros((self.num_node, self.num_node)) a_close = np.zeros((self.num_node, self.num_node)) a_further = np.zeros((self.num_node, self.num_node)) for i in range(self.num_node): for j in range(self.num_node): if self.hop_dis[j, i] == hop: if self.hop_dis[j, self.center] == self.hop_dis[ i, self.center]: a_root[j, i] = normalize_adjacency[j, i] elif self.hop_dis[j, self.center] > self.hop_dis[ i, self.center]: a_close[j, i] = normalize_adjacency[j, i] else: a_further[j, i] = normalize_adjacency[j, i] if hop == 0: A.append(a_root) else: A.append(a_root + a_close) A.append(a_further) A = np.stack(A) self.A = A else: raise ValueError("Do Not Exist This Strategy") class TCN(nn.Layer): def __init__(self, in_channels, out_channels, kernel_size=9, stride=1, dilation=1): super(TCN, self).__init__() pad = (kernel_size + (kernel_size - 1) * (dilation - 1) - 1) // 2 self.conv = nn.Conv2D( in_channels, out_channels, kernel_size=(kernel_size, 1), padding=(pad, 0), stride=(stride, 1), dilation=(dilation, 1)) self.bn = nn.BatchNorm2D(out_channels) def forward(self, x): x = self.conv(x) x = self.bn(x) return x class Temporal_Block(nn.Layer): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilations=[1, 2], residual=True, residual_kernel_size=1): super().__init__() assert out_channels % (len(dilations) + 2) == 0, '# out channels should be multiples of # branches' # Multiple branches of temporal convolution self.num_branches = len(dilations) + 2 branch_channels = out_channels // self.num_branches if type(kernel_size) == list: assert len(kernel_size) == len(dilations) else: kernel_size = [kernel_size] * len(dilations) # Temporal Convolution branches self.branche1 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), TCN(branch_channels, branch_channels, kernel_size=kernel_size[0], stride=stride, dilation=dilations[0]), ) self.branche2 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), TCN(branch_channels, branch_channels, kernel_size=kernel_size[1], stride=stride, dilation=dilations[1]), ) # Additional Max & 1x1 branch self.branche3 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), nn.MaxPool2D(kernel_size=(3, 1), stride=(stride, 1), padding=(1, 0)), nn.BatchNorm2D(branch_channels) # 为什么还要加bn ) self.branche4 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0, stride=(stride, 1)), nn.BatchNorm2D(branch_channels) ) # Residual connection if not residual: self.res = lambda x: 0 elif (in_channels == out_channels) and (stride == 1): self.res = lambda x: x else: self.res = TCN(in_channels, out_channels, kernel_size=residual_kernel_size, stride=stride) # initialize # self.apply(weights_init)#todo 初始化 def forward(self, x): # Input dim: (N,C,T,V) branch_outs = [] branch_outs.append(self.branche1(x)) branch_outs.append(self.branche2(x)) branch_outs.append(self.branche3(x)) branch_outs.append(self.branche4(x)) out = paddle.concat(branch_outs, axis=1) out += self.res(x) return out class CTRGC(nn.Layer): def __init__(self, in_channels, out_channels, rel_reduction=8, mid_reduction=1): super(CTRGC, self).__init__() self.in_channels = in_channels self.out_channels = out_channels # TODO in_channels if in_channels <= 4 or in_channels == 9: self.rel_channels = 8 # self.mid_channels = 16 else: self.rel_channels = in_channels // rel_reduction # self.mid_channels = in_channels // mid_reduction self.conv1 = nn.Conv2D(self.in_channels, self.rel_channels, kernel_size=1) self.conv2 = nn.Conv2D(self.in_channels, self.rel_channels, kernel_size=1) self.conv3 = nn.Conv2D(self.rel_channels, self.out_channels, kernel_size=1) self.shortcut = nn.Conv2D(self.in_channels, self.out_channels, kernel_size=1) self.tanh = nn.Tanh() def forward(self, x, A=None, alpha=1): x1 = self.conv1(x) x1 = x1.mean(-2) x2 = self.conv2(x).mean(-2) y = self.shortcut(x) x = self.tanh(x1.unsqueeze(-1) - x2.unsqueeze(-2)) x = self.conv3(x) * alpha + (A.unsqueeze(0).unsqueeze(0) if A is not None else 0) # N,C,V,V x = paddle.einsum('ncuv,nctv->nctu', x, y) return x class Spatial_Block(nn.Layer): def __init__(self, in_channels, out_channels, A, coff_embedding=4, adaptive=True, residual=True): super(Spatial_Block, self).__init__() self.adaptive = adaptive self.num_subset = A.shape[0] # three graph self.convs = nn.Sequential( # hardcode instead of num_subset CTRGC(in_channels, out_channels), CTRGC(in_channels, out_channels), CTRGC(in_channels, out_channels) ) graphA = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[0])) graphB = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[1])) graphC = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[2])) self.add_parameter(name='graphA', parameter=graphA) self.add_parameter(name='graphB', parameter=graphB) self.add_parameter(name='graphC', parameter=graphC) alpha = paddle.create_parameter([1], dtype='float32') self.add_parameter(name='alpha', parameter=alpha) # end # one graph # self.conv = CTRGC(in_channels, out_channels) # A = A.sum(axis=0) # graph = paddle.create_parameter([25, 25], dtype='float32', # default_initializer=paddle.nn.initializer.Assign(A)) # self.add_parameter(name='graph', parameter=graph) # self.alpha = 1 # end # todo learn alpha or not self.bn = nn.BatchNorm2D(out_channels) # self.soft = nn.Softmax(-2)#todo unused self.relu = nn.ReLU() if residual: if in_channels != out_channels: self.res = nn.Sequential( nn.Conv2D(in_channels, out_channels, 1), nn.BatchNorm2D(out_channels) ) else: self.res = lambda x: x else: self.res = lambda x: 0 def forward(self, x): # three graph y = self.convs[0](x, self.graphA, self.alpha) y = y + self.convs[1](x, self.graphB, self.alpha) y = y + self.convs[2](x, self.graphC, self.alpha) # end # one graph # y = self.conv(x, self.graph, self.alpha) # end y = self.bn(y) y += self.res(x) y = self.relu(y) return y class ST_Block(nn.Layer): def __init__(self, in_channels, out_channels, A, stride=1, residual=True, adaptive=True, kernel_size=[9, 9], dilations=[1, 2]): super(ST_Block, self).__init__() self.spatial_model = Spatial_Block(in_channels, out_channels, A, adaptive=adaptive) self.temporal_model = Temporal_Block(out_channels, out_channels, kernel_size=kernel_size, stride=stride, dilations=dilations, residual=False) self.relu = nn.ReLU() if not residual: self.res = lambda x: 0 elif (in_channels == out_channels) and (stride == 1): self.res = lambda x: x else: self.res = TCN(in_channels, out_channels, kernel_size=1, stride=stride) # todo def forward(self, x): y = self.relu(self.temporal_model(self.spatial_model(x)) + self.res(x)) return y @BACKBONES.register() class CTRGCN2(nn.Layer): ''' Channel-wise Topology Refinement Graph Convolution Network ''' # todo test code in_channels=2 def __init__(self, in_channels=2, adaptive=True, **kwargs): super(CTRGCN2, self).__init__() self.graph = Graph( layout='fsd10', strategy='spatial', ) A = paddle.to_tensor(self.graph.A, dtype='float32') base_channel = 64 self.ctrgcn = nn.Sequential( ST_Block(in_channels, base_channel, A, residual=False, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel * 2, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 2, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 2, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 4, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 4, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 4, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 8, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 8, base_channel * 8, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 8, base_channel * 8, A, adaptive=adaptive, **kwargs), ) self.pool = nn.AdaptiveAvgPool2D(output_size=(1, 1)) self.dropout = nn.Dropout(0.2) def forward(self, x): # data normalization N, C, T, V, M = x.shape x = x.transpose((0, 4, 1, 2, 3)) # N, M, C, T, V x = x.reshape((N * M, C, T, V)) x = self.ctrgcn(x) # x = self.dropout(x) # x = self.pool(x) # NM,C,T,V --> NM,C,1,1 C = x.shape[1] # x = paddle.reshape(x, (N, M, C, 1, 1)).mean(axis=1) # N,C,1,1 x = paddle.reshape(x, (N, M, C, -1)) x = x.mean(3).mean(1).unsqueeze(-1).unsqueeze(-1) # x = self.dropout(x) return x
paddlevideo/modeling/backbones/ctrgcn2.py
import numpy as np import paddle import paddle.nn as nn from ..registry import BACKBONES import sys def get_hop_distance(num_node, edge, max_hop=1): A = np.zeros((num_node, num_node)) for i, j in edge: A[j, i] = 1 A[i, j] = 1 # compute hop steps hop_dis = np.zeros((num_node, num_node)) + np.inf transfer_mat = [np.linalg.matrix_power(A, d) for d in range(max_hop + 1)] arrive_mat = (np.stack(transfer_mat) > 0) for d in range(max_hop, -1, -1): hop_dis[arrive_mat[d]] = d return hop_dis def normalize_digraph(A): Dl = np.sum(A, 0) num_node = A.shape[0] Dn = np.zeros((num_node, num_node)) for i in range(num_node): if Dl[i] > 0: Dn[i, i] = Dl[i] ** (-1) AD = np.dot(A, Dn) return AD class Graph(): def __init__(self, layout='openpose', strategy='uniform', max_hop=1, dilation=1): self.max_hop = max_hop self.dilation = dilation self.get_edge(layout) self.hop_dis = get_hop_distance(self.num_node, self.edge, max_hop=max_hop) self.get_adjacency(strategy) def __str__(self): return self.A def get_edge(self, layout): # edge is a list of [child, parent] paris if layout == 'fsd10': self.num_node = 25 self_link = [(i, i) for i in range(self.num_node)] neighbor_link = [(1, 8), (0, 1), (15, 0), (17, 15), (16, 0), (18, 16), (5, 1), (6, 5), (7, 6), (2, 1), (3, 2), (4, 3), (9, 8), (10, 9), (11, 10), (24, 11), (22, 11), (23, 22), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19)] self.edge = self_link + neighbor_link self.center = 8 elif layout == 'ntu-rgb+d': self.num_node = 25 self_link = [(i, i) for i in range(self.num_node)] neighbor_1base = [(1, 2), (2, 21), (3, 21), (4, 3), (5, 21), (6, 5), (7, 6), (8, 7), (9, 21), (10, 9), (11, 10), (12, 11), (13, 1), (14, 13), (15, 14), (16, 15), (17, 1), (18, 17), (19, 18), (20, 19), (22, 23), (23, 8), (24, 25), (25, 12)] neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base] self.edge = self_link + neighbor_link self.center = 21 - 1 else: raise ValueError("Do Not Exist This Layout.") def get_adjacency(self, strategy): valid_hop = range(0, self.max_hop + 1, self.dilation) adjacency = np.zeros((self.num_node, self.num_node)) for hop in valid_hop: adjacency[self.hop_dis == hop] = 1 normalize_adjacency = normalize_digraph(adjacency) if strategy == 'spatial': A = [] for hop in valid_hop: a_root = np.zeros((self.num_node, self.num_node)) a_close = np.zeros((self.num_node, self.num_node)) a_further = np.zeros((self.num_node, self.num_node)) for i in range(self.num_node): for j in range(self.num_node): if self.hop_dis[j, i] == hop: if self.hop_dis[j, self.center] == self.hop_dis[ i, self.center]: a_root[j, i] = normalize_adjacency[j, i] elif self.hop_dis[j, self.center] > self.hop_dis[ i, self.center]: a_close[j, i] = normalize_adjacency[j, i] else: a_further[j, i] = normalize_adjacency[j, i] if hop == 0: A.append(a_root) else: A.append(a_root + a_close) A.append(a_further) A = np.stack(A) self.A = A else: raise ValueError("Do Not Exist This Strategy") class TCN(nn.Layer): def __init__(self, in_channels, out_channels, kernel_size=9, stride=1, dilation=1): super(TCN, self).__init__() pad = (kernel_size + (kernel_size - 1) * (dilation - 1) - 1) // 2 self.conv = nn.Conv2D( in_channels, out_channels, kernel_size=(kernel_size, 1), padding=(pad, 0), stride=(stride, 1), dilation=(dilation, 1)) self.bn = nn.BatchNorm2D(out_channels) def forward(self, x): x = self.conv(x) x = self.bn(x) return x class Temporal_Block(nn.Layer): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilations=[1, 2], residual=True, residual_kernel_size=1): super().__init__() assert out_channels % (len(dilations) + 2) == 0, '# out channels should be multiples of # branches' # Multiple branches of temporal convolution self.num_branches = len(dilations) + 2 branch_channels = out_channels // self.num_branches if type(kernel_size) == list: assert len(kernel_size) == len(dilations) else: kernel_size = [kernel_size] * len(dilations) # Temporal Convolution branches self.branche1 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), TCN(branch_channels, branch_channels, kernel_size=kernel_size[0], stride=stride, dilation=dilations[0]), ) self.branche2 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), TCN(branch_channels, branch_channels, kernel_size=kernel_size[1], stride=stride, dilation=dilations[1]), ) # Additional Max & 1x1 branch self.branche3 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0), nn.BatchNorm2D(branch_channels), nn.ReLU(), nn.MaxPool2D(kernel_size=(3, 1), stride=(stride, 1), padding=(1, 0)), nn.BatchNorm2D(branch_channels) # 为什么还要加bn ) self.branche4 = nn.Sequential( nn.Conv2D(in_channels, branch_channels, kernel_size=1, padding=0, stride=(stride, 1)), nn.BatchNorm2D(branch_channels) ) # Residual connection if not residual: self.res = lambda x: 0 elif (in_channels == out_channels) and (stride == 1): self.res = lambda x: x else: self.res = TCN(in_channels, out_channels, kernel_size=residual_kernel_size, stride=stride) # initialize # self.apply(weights_init)#todo 初始化 def forward(self, x): # Input dim: (N,C,T,V) branch_outs = [] branch_outs.append(self.branche1(x)) branch_outs.append(self.branche2(x)) branch_outs.append(self.branche3(x)) branch_outs.append(self.branche4(x)) out = paddle.concat(branch_outs, axis=1) out += self.res(x) return out class CTRGC(nn.Layer): def __init__(self, in_channels, out_channels, rel_reduction=8, mid_reduction=1): super(CTRGC, self).__init__() self.in_channels = in_channels self.out_channels = out_channels # TODO in_channels if in_channels <= 4 or in_channels == 9: self.rel_channels = 8 # self.mid_channels = 16 else: self.rel_channels = in_channels // rel_reduction # self.mid_channels = in_channels // mid_reduction self.conv1 = nn.Conv2D(self.in_channels, self.rel_channels, kernel_size=1) self.conv2 = nn.Conv2D(self.in_channels, self.rel_channels, kernel_size=1) self.conv3 = nn.Conv2D(self.rel_channels, self.out_channels, kernel_size=1) self.shortcut = nn.Conv2D(self.in_channels, self.out_channels, kernel_size=1) self.tanh = nn.Tanh() def forward(self, x, A=None, alpha=1): x1 = self.conv1(x) x1 = x1.mean(-2) x2 = self.conv2(x).mean(-2) y = self.shortcut(x) x = self.tanh(x1.unsqueeze(-1) - x2.unsqueeze(-2)) x = self.conv3(x) * alpha + (A.unsqueeze(0).unsqueeze(0) if A is not None else 0) # N,C,V,V x = paddle.einsum('ncuv,nctv->nctu', x, y) return x class Spatial_Block(nn.Layer): def __init__(self, in_channels, out_channels, A, coff_embedding=4, adaptive=True, residual=True): super(Spatial_Block, self).__init__() self.adaptive = adaptive self.num_subset = A.shape[0] # three graph self.convs = nn.Sequential( # hardcode instead of num_subset CTRGC(in_channels, out_channels), CTRGC(in_channels, out_channels), CTRGC(in_channels, out_channels) ) graphA = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[0])) graphB = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[1])) graphC = paddle.create_parameter([25, 25], dtype='float32', default_initializer=paddle.nn.initializer.Assign(A[2])) self.add_parameter(name='graphA', parameter=graphA) self.add_parameter(name='graphB', parameter=graphB) self.add_parameter(name='graphC', parameter=graphC) alpha = paddle.create_parameter([1], dtype='float32') self.add_parameter(name='alpha', parameter=alpha) # end # one graph # self.conv = CTRGC(in_channels, out_channels) # A = A.sum(axis=0) # graph = paddle.create_parameter([25, 25], dtype='float32', # default_initializer=paddle.nn.initializer.Assign(A)) # self.add_parameter(name='graph', parameter=graph) # self.alpha = 1 # end # todo learn alpha or not self.bn = nn.BatchNorm2D(out_channels) # self.soft = nn.Softmax(-2)#todo unused self.relu = nn.ReLU() if residual: if in_channels != out_channels: self.res = nn.Sequential( nn.Conv2D(in_channels, out_channels, 1), nn.BatchNorm2D(out_channels) ) else: self.res = lambda x: x else: self.res = lambda x: 0 def forward(self, x): # three graph y = self.convs[0](x, self.graphA, self.alpha) y = y + self.convs[1](x, self.graphB, self.alpha) y = y + self.convs[2](x, self.graphC, self.alpha) # end # one graph # y = self.conv(x, self.graph, self.alpha) # end y = self.bn(y) y += self.res(x) y = self.relu(y) return y class ST_Block(nn.Layer): def __init__(self, in_channels, out_channels, A, stride=1, residual=True, adaptive=True, kernel_size=[9, 9], dilations=[1, 2]): super(ST_Block, self).__init__() self.spatial_model = Spatial_Block(in_channels, out_channels, A, adaptive=adaptive) self.temporal_model = Temporal_Block(out_channels, out_channels, kernel_size=kernel_size, stride=stride, dilations=dilations, residual=False) self.relu = nn.ReLU() if not residual: self.res = lambda x: 0 elif (in_channels == out_channels) and (stride == 1): self.res = lambda x: x else: self.res = TCN(in_channels, out_channels, kernel_size=1, stride=stride) # todo def forward(self, x): y = self.relu(self.temporal_model(self.spatial_model(x)) + self.res(x)) return y @BACKBONES.register() class CTRGCN2(nn.Layer): ''' Channel-wise Topology Refinement Graph Convolution Network ''' # todo test code in_channels=2 def __init__(self, in_channels=2, adaptive=True, **kwargs): super(CTRGCN2, self).__init__() self.graph = Graph( layout='fsd10', strategy='spatial', ) A = paddle.to_tensor(self.graph.A, dtype='float32') base_channel = 64 self.ctrgcn = nn.Sequential( ST_Block(in_channels, base_channel, A, residual=False, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel, A, adaptive=adaptive, **kwargs), ST_Block(base_channel, base_channel * 2, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 2, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 2, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 2, base_channel * 4, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 4, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 4, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 4, base_channel * 8, A, stride=2, adaptive=adaptive, **kwargs), ST_Block(base_channel * 8, base_channel * 8, A, adaptive=adaptive, **kwargs), ST_Block(base_channel * 8, base_channel * 8, A, adaptive=adaptive, **kwargs), ) self.pool = nn.AdaptiveAvgPool2D(output_size=(1, 1)) self.dropout = nn.Dropout(0.2) def forward(self, x): # data normalization N, C, T, V, M = x.shape x = x.transpose((0, 4, 1, 2, 3)) # N, M, C, T, V x = x.reshape((N * M, C, T, V)) x = self.ctrgcn(x) # x = self.dropout(x) # x = self.pool(x) # NM,C,T,V --> NM,C,1,1 C = x.shape[1] # x = paddle.reshape(x, (N, M, C, 1, 1)).mean(axis=1) # N,C,1,1 x = paddle.reshape(x, (N, M, C, -1)) x = x.mean(3).mean(1).unsqueeze(-1).unsqueeze(-1) # x = self.dropout(x) return x
0.52683
0.348493
from __future__ import unicode_literals from __future__ import print_function from ...command import SubCommand from ...wsgi import WSGIApplication from ...console import Cell from ...template.moyatemplates import Template from datetime import datetime from fs.path import join import os.path from collections import defaultdict import polib import pytz class Extract(SubCommand): """Extract translatable text from libraries""" help = "extract translatable text" def add_arguments(self, parser): parser.add_argument( dest="libs", default=None, metavar="LIB NAME", nargs="+", help="Extract text from these libs", ) parser.add_argument( "-l", "--location", dest="location", default=None, metavar="PATH", help="location of the Moya server code", ) parser.add_argument( "-i", "--ini", dest="settings", default=None, metavar="SETTINGSPATH", help="path to projects settings file", ) parser.add_argument( "-m", "--merge", dest="merge", action="store_true", help="merge translatable strings with existing .pot file", ) parser.add_argument( "-o", "--overwrite", dest="overwrite", action="store_true", help="overwrite existing .pot file", ) def run(self): args = self.args application = WSGIApplication( self.location, self.get_settings(), disable_autoreload=True, master_settings=self.master_settings, ) archive = application.archive try: libs = [archive.libs[lib_name] for lib_name in args.libs] except KeyError: self.console.error('No lib with name "{}" installed'.format(lib_name)) return -1 table = [] for lib in libs: template_text = set() extract_text = defaultdict(lambda: {"occurrences": []}) if not lib.translations_location: table.append( [ lib.long_name, Cell("translations not enabled", fg="red", bold=True), "", ] ) continue filename = "{}.pot".format(lib.long_name.replace(".", "_")) translations_dir = lib.load_fs.getsyspath(lib.translations_location) def add_text( path, line, text, comment=None, plural=None, attr=None, context=None ): rel_path = os.path.relpath(path, translations_dir) entry = extract_text[(text, plural, attr, context)] if attr is not None and context is not None: context = "attribute '{}'".format(attr) if plural is not None: entry["msgid"] = text entry["msgid_plural"] = plural entry["msgstr_plural"] = {"0": "", "1": ""} else: entry["msgid"] = text if context is not None: entry["msgctxt"] = context entry["occurrences"].append((rel_path, line)) if comment is not None: entry["comment"] = comment with self.console.progress( "extracting {}".format(lib), len(lib.documents) ) as progress: for doc in lib.documents: progress.step() for element in doc.elements.itervalues(): if element._translate_text: text = element._text.strip() if text: add_text( element._location, element.source_line, text, comment=unicode(element), ) for name, attribute in element._tag_attributes.items(): if ( attribute.translate or name in element._translatable_attrs ): text = element._attrs.get(name, "").strip() if text: add_text( element._location, element.source_line, text, attr=name, comment="attribute '{}' of {}".format( name, unicode(element) ), ) if "location" in lib.templates_info: engine = archive.get_template_engine("moya") with lib.load_fs.opendir( lib.templates_info["location"] ) as templates_fs: for path in templates_fs.walk.files(): sys_path = ( templates_fs.getsyspath(path, allow_none=True) or path ) contents = templates_fs.getbytes(path) template = Template(contents, path) template.parse(engine.env) for trans_text in template.translatable_text: line, start, end = trans_text.location text = trans_text.text comment = trans_text.comment plural = trans_text.plural translatable_text = ( path, line, start, text, plural, ) if translatable_text not in template_text: add_text( sys_path, line, text, comment, plural=plural, context=trans_text.context, ) template_text.add(translatable_text) now = pytz.UTC.localize(datetime.utcnow()) po = polib.POFile() for text in extract_text.values(): po.append(polib.POEntry(**text)) po.metadata = { "POT-Creation-Date": now.strftime("%Y-%m-%d %H:%M%z"), "Project-Id-Version": lib.version, "Language": lib.default_language or "en", "MIME-Version": "1.0", "Content-Type": "text/plain; charset=utf-8", "Content-Transfer-Encoding": "8Bit", "Plural-Forms": "nplurals=2; plural=(n != 1);", } if lib.translations_location: lib.load_fs.makedir(lib.translations_location, recreate=True) translations_location = lib.load_fs.getsyspath( lib.translations_location ) translation_path = os.path.join(translations_location, filename) if os.path.exists(translation_path) and not args.overwrite: if not args.merge: self.console.error( 'message file "{}" exists, see --merge or --overwrite options'.format( filename ) ) return -1 existing_po = polib.pofile(translation_path) po.merge(existing_po) po.save(translation_path) else: po.save(translation_path) locale_fs = lib.load_fs.opendir(lib.translations_location) for lang in lib.languages: locale_fs.makedirs("{}/LC_MESSAGES/".format(lang), recreate=True) table.append( [ lib.long_name, Cell( join(lib.translations_location, filename), fg="green", bold=True, ), Cell(len(po), bold=True), ] ) self.console.table(table, header_row=["lib", "file", "no. strings"])
moya/command/sub/extract.py
from __future__ import unicode_literals from __future__ import print_function from ...command import SubCommand from ...wsgi import WSGIApplication from ...console import Cell from ...template.moyatemplates import Template from datetime import datetime from fs.path import join import os.path from collections import defaultdict import polib import pytz class Extract(SubCommand): """Extract translatable text from libraries""" help = "extract translatable text" def add_arguments(self, parser): parser.add_argument( dest="libs", default=None, metavar="LIB NAME", nargs="+", help="Extract text from these libs", ) parser.add_argument( "-l", "--location", dest="location", default=None, metavar="PATH", help="location of the Moya server code", ) parser.add_argument( "-i", "--ini", dest="settings", default=None, metavar="SETTINGSPATH", help="path to projects settings file", ) parser.add_argument( "-m", "--merge", dest="merge", action="store_true", help="merge translatable strings with existing .pot file", ) parser.add_argument( "-o", "--overwrite", dest="overwrite", action="store_true", help="overwrite existing .pot file", ) def run(self): args = self.args application = WSGIApplication( self.location, self.get_settings(), disable_autoreload=True, master_settings=self.master_settings, ) archive = application.archive try: libs = [archive.libs[lib_name] for lib_name in args.libs] except KeyError: self.console.error('No lib with name "{}" installed'.format(lib_name)) return -1 table = [] for lib in libs: template_text = set() extract_text = defaultdict(lambda: {"occurrences": []}) if not lib.translations_location: table.append( [ lib.long_name, Cell("translations not enabled", fg="red", bold=True), "", ] ) continue filename = "{}.pot".format(lib.long_name.replace(".", "_")) translations_dir = lib.load_fs.getsyspath(lib.translations_location) def add_text( path, line, text, comment=None, plural=None, attr=None, context=None ): rel_path = os.path.relpath(path, translations_dir) entry = extract_text[(text, plural, attr, context)] if attr is not None and context is not None: context = "attribute '{}'".format(attr) if plural is not None: entry["msgid"] = text entry["msgid_plural"] = plural entry["msgstr_plural"] = {"0": "", "1": ""} else: entry["msgid"] = text if context is not None: entry["msgctxt"] = context entry["occurrences"].append((rel_path, line)) if comment is not None: entry["comment"] = comment with self.console.progress( "extracting {}".format(lib), len(lib.documents) ) as progress: for doc in lib.documents: progress.step() for element in doc.elements.itervalues(): if element._translate_text: text = element._text.strip() if text: add_text( element._location, element.source_line, text, comment=unicode(element), ) for name, attribute in element._tag_attributes.items(): if ( attribute.translate or name in element._translatable_attrs ): text = element._attrs.get(name, "").strip() if text: add_text( element._location, element.source_line, text, attr=name, comment="attribute '{}' of {}".format( name, unicode(element) ), ) if "location" in lib.templates_info: engine = archive.get_template_engine("moya") with lib.load_fs.opendir( lib.templates_info["location"] ) as templates_fs: for path in templates_fs.walk.files(): sys_path = ( templates_fs.getsyspath(path, allow_none=True) or path ) contents = templates_fs.getbytes(path) template = Template(contents, path) template.parse(engine.env) for trans_text in template.translatable_text: line, start, end = trans_text.location text = trans_text.text comment = trans_text.comment plural = trans_text.plural translatable_text = ( path, line, start, text, plural, ) if translatable_text not in template_text: add_text( sys_path, line, text, comment, plural=plural, context=trans_text.context, ) template_text.add(translatable_text) now = pytz.UTC.localize(datetime.utcnow()) po = polib.POFile() for text in extract_text.values(): po.append(polib.POEntry(**text)) po.metadata = { "POT-Creation-Date": now.strftime("%Y-%m-%d %H:%M%z"), "Project-Id-Version": lib.version, "Language": lib.default_language or "en", "MIME-Version": "1.0", "Content-Type": "text/plain; charset=utf-8", "Content-Transfer-Encoding": "8Bit", "Plural-Forms": "nplurals=2; plural=(n != 1);", } if lib.translations_location: lib.load_fs.makedir(lib.translations_location, recreate=True) translations_location = lib.load_fs.getsyspath( lib.translations_location ) translation_path = os.path.join(translations_location, filename) if os.path.exists(translation_path) and not args.overwrite: if not args.merge: self.console.error( 'message file "{}" exists, see --merge or --overwrite options'.format( filename ) ) return -1 existing_po = polib.pofile(translation_path) po.merge(existing_po) po.save(translation_path) else: po.save(translation_path) locale_fs = lib.load_fs.opendir(lib.translations_location) for lang in lib.languages: locale_fs.makedirs("{}/LC_MESSAGES/".format(lang), recreate=True) table.append( [ lib.long_name, Cell( join(lib.translations_location, filename), fg="green", bold=True, ), Cell(len(po), bold=True), ] ) self.console.table(table, header_row=["lib", "file", "no. strings"])
0.359701
0.080719
import unittest import schrift class SchriftTest(unittest.TestCase): def setUp(self): schrift.app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" self.app = schrift.app.test_client() schrift.db.create_all() self.setUpUsers() def setUpUsers(self): """ Helper function to add the test users to the database. """ self.author = schrift.User("Author", "1235", editor=True) self.author.authors.append(self.author) self.author.blog_title = u"Author s blog title" self.reader = schrift.User("Reader", "1235") self.reader.authors.append(self.author) self.unauthorized = schrift.User("Spam", "1235") schrift.db.session.add(self.author) schrift.db.session.add(self.reader) schrift.db.session.add(self.unauthorized) schrift.db.session.commit() def add_post(self, title, content, summary="", private=False, published=True): """ Helper function to add a new blog post. """ data = dict(title=title, content=content, summary=summary, tags="") if private: data["private"] = "1" if published: data["published"] = "1" return self.app.post("/add", follow_redirects=True, data=data) def login(self, name): """ Helper function to login. """ return self.app.post("/login", follow_redirects=True, data=dict(name=name, password="<PASSWORD>")) def logout(self): """ Helper function to logout. """ return self.app.get("/logout", follow_redirects=True) def test__empty_db(self): """ Start with an empty database. """ response = self.app.get("/") self.assertEqual(response.status_code, 200) def test_login_logout(self): for name in ["Author", "Reader", "Spam"]: response = self.login(name) self.assertTrue("Logged in as " + name in response.data) response = self.logout() self.assertTrue("logged out" in response.data) def test_change_password(self): self.login("Author") response = self.app.post("/changepassword", data=dict(old_password="", password="")) self.assertTrue(u"A new password is required." in response.data) response = self.app.post("/changepassword", follow_redirects=True, data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) self.assertTrue(u"Password changed." in response.data) response = self.app.post("/changepassword", data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) self.assertTrue(u"Sorry, try again." in response.data) # Change password back self.app.post("/changepassword", data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) def test_blog_title(self): # Add 11 blog posts (pagination needed) self.login("Author") for _ in xrange(11): self.add_post(u"blog title test", content=u"Nothing.") # Test itself for url in ["/", "/2", "/atom"]: response = self.app.get(url) self.assertTrue(schrift.BLOG_TITLE in response.data, url) for url in ["/Author", "/Author/2", "/Author/atom"]: response = self.app.get(url) self.assertTrue(self.author.blog_title in response.data, url) def test_edit(self): self.login("Author") title = u"Editing test post" new_title = u"An edited test post" slug = schrift.slugify(title) response = self.add_post(title, content="Spam", summary=u"Old summary.") entry = schrift.db.session.query(schrift.Post).filter_by(slug=slug).first() response = self.app.post("/save", follow_redirects=True, data=dict(id=entry.id, summary=u"New summary", title=new_title, content=u"New Spam", tags="")) self.assertTrue(u"New Spam" in response.data) entry = schrift.db.session.query(schrift.Post).filter_by(slug=slug).first() self.assertEquals(u"New summary", entry.summary) self.assertEquals(new_title, entry.title) def test_private(self): self.login("Author") title = u"Post with a title" content = u"This is the post's content (test_private)." read_url = "/read/" + schrift.slugify(title) response = self.add_post(title, content, private=True) self.assertTrue(content in response.data) self.logout() # Only logged in users can read it response = self.app.get("/") self.assertFalse(content in response.data) response = self.app.get(read_url) self.assertEquals(response.status_code, 302) self.assertTrue(u"Redirecting" in response.data) response = self.app.get("/atom") self.assertFalse(content in response.data) # Reader is allowed to read it self.login("Reader") response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) self.logout() # Spam isn't allowed to read it self.login("Spam") response = self.app.get("/") self.assertFalse(content in response.data) response = self.app.get(read_url) self.assertEquals(response.status_code, 403) response = self.app.get("/atom") self.assertFalse(content in response.data) self.logout() # But spam is allowed to read public posts by Author self.login("Author") title = u"Post with a title (public)" content = u"This is the post's content (test_private)." read_url = "/read/" + schrift.slugify(title) response = self.add_post(title, content, private=False) self.assertTrue(content in response.data) self.logout() self.login("Spam") response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) self.logout() # ... and unidentified users are allowed to read public posts by Author response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) def test_private_prev_next(self): self.login(self.author.name) private_title = u"Private Post" private_read_url = "/read/" + schrift.slugify(private_title) self.add_post(private_title, u"Spam", private=True) title = u"Second Post" read_url = "/read/" + schrift.slugify(title) self.add_post(title, u"Spam", private=False) # Author can see prev link response = self.app.get(read_url) self.assertTrue(private_read_url in response.data) # Reader, too self.login(self.reader.name) response = self.app.get(read_url) self.assertTrue(private_read_url in response.data) # The other reader not self.login(self.unauthorized.name) response = self.app.get(read_url) self.assertFalse(private_read_url in response.data) def test_private_auth_atom(self): self.login("Author") title = u"test_private_auth_atom" self.add_post(title, "Spam", private=True) self.logout() response = self.app.get("/atom?auth", headers=[("Authorization", "Basic QXV0aG9yOjEyMzU=")]) self.assertTrue(title in response.data) def test_unpublished(self): self.login("Author") title = u"Unpublished post" slug = schrift.slugify(title) self.add_post(title, u"Spam", published=False) # Author should see the unpublished post for url in ["/", "/Author", "/read/" + slug]: response = self.app.get(url) self.assertTrue(title in response.data, url) self.logout() # Everyone else not for url in ["/", "/Author", "/atom"]: response = self.app.get(url) self.assertFalse(title in response.data, url) # The post does not exist response = self.app.get("/read/" + slug) self.assertEquals(response.status_code, 404) def test_unpublished_prev_next(self): self.login(self.author.name) unpublished_title = u"Unpublished Post" unpublished_read_url = "/read/" + schrift.slugify(unpublished_title) self.add_post(unpublished_title, u"Spam", published=False) title = u"Second Post" read_url = "/read/" + schrift.slugify(title) self.add_post(title, u"Spam") # Author can see prev link response = self.app.get(read_url) self.assertTrue(unpublished_read_url in response.data) # All others not self.login(self.reader.name) response = self.app.get(read_url) self.assertFalse(unpublished_read_url in response.data) def test_duplicates(self): title = u"Duplicated title" read_url = "/read/" + schrift.slugify(title) self.login("Author") self.add_post(title, u"Spam") self.add_post(title, u"Spam") response = self.add_post(title, u"Spam") self.assertTrue(read_url in response.data) self.assertTrue(read_url + "-2" in response.data) self.assertTrue(read_url + "-3" in response.data) def test_user(self): self.login("Author") title = u"A public post." content = u"This is a public post (test_user)." read_url = "/Author/read/" + schrift.slugify(title) response = self.add_post(title, content) self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) def test_slugify(self): self.assertEqual(schrift.slugify(u"ßpäm"), u"sspaem") self.assertEqual(schrift.slugify(u"slug With spaces"), u"slug-with-spaces") self.assertEqual(schrift.slugify(u"foo@bar"), u"foobar") self.assertEqual(schrift.slugify(u"slug with multiple -- spaces"), u"slug-with-multiple-spaces") self.assertEqual(schrift.slugify(u"42"), u"42") if __name__ == "__main__": unittest.main()
schrift_tests.py
import unittest import schrift class SchriftTest(unittest.TestCase): def setUp(self): schrift.app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" self.app = schrift.app.test_client() schrift.db.create_all() self.setUpUsers() def setUpUsers(self): """ Helper function to add the test users to the database. """ self.author = schrift.User("Author", "1235", editor=True) self.author.authors.append(self.author) self.author.blog_title = u"Author s blog title" self.reader = schrift.User("Reader", "1235") self.reader.authors.append(self.author) self.unauthorized = schrift.User("Spam", "1235") schrift.db.session.add(self.author) schrift.db.session.add(self.reader) schrift.db.session.add(self.unauthorized) schrift.db.session.commit() def add_post(self, title, content, summary="", private=False, published=True): """ Helper function to add a new blog post. """ data = dict(title=title, content=content, summary=summary, tags="") if private: data["private"] = "1" if published: data["published"] = "1" return self.app.post("/add", follow_redirects=True, data=data) def login(self, name): """ Helper function to login. """ return self.app.post("/login", follow_redirects=True, data=dict(name=name, password="<PASSWORD>")) def logout(self): """ Helper function to logout. """ return self.app.get("/logout", follow_redirects=True) def test__empty_db(self): """ Start with an empty database. """ response = self.app.get("/") self.assertEqual(response.status_code, 200) def test_login_logout(self): for name in ["Author", "Reader", "Spam"]: response = self.login(name) self.assertTrue("Logged in as " + name in response.data) response = self.logout() self.assertTrue("logged out" in response.data) def test_change_password(self): self.login("Author") response = self.app.post("/changepassword", data=dict(old_password="", password="")) self.assertTrue(u"A new password is required." in response.data) response = self.app.post("/changepassword", follow_redirects=True, data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) self.assertTrue(u"Password changed." in response.data) response = self.app.post("/changepassword", data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) self.assertTrue(u"Sorry, try again." in response.data) # Change password back self.app.post("/changepassword", data=dict(old_password="<PASSWORD>", password="<PASSWORD>")) def test_blog_title(self): # Add 11 blog posts (pagination needed) self.login("Author") for _ in xrange(11): self.add_post(u"blog title test", content=u"Nothing.") # Test itself for url in ["/", "/2", "/atom"]: response = self.app.get(url) self.assertTrue(schrift.BLOG_TITLE in response.data, url) for url in ["/Author", "/Author/2", "/Author/atom"]: response = self.app.get(url) self.assertTrue(self.author.blog_title in response.data, url) def test_edit(self): self.login("Author") title = u"Editing test post" new_title = u"An edited test post" slug = schrift.slugify(title) response = self.add_post(title, content="Spam", summary=u"Old summary.") entry = schrift.db.session.query(schrift.Post).filter_by(slug=slug).first() response = self.app.post("/save", follow_redirects=True, data=dict(id=entry.id, summary=u"New summary", title=new_title, content=u"New Spam", tags="")) self.assertTrue(u"New Spam" in response.data) entry = schrift.db.session.query(schrift.Post).filter_by(slug=slug).first() self.assertEquals(u"New summary", entry.summary) self.assertEquals(new_title, entry.title) def test_private(self): self.login("Author") title = u"Post with a title" content = u"This is the post's content (test_private)." read_url = "/read/" + schrift.slugify(title) response = self.add_post(title, content, private=True) self.assertTrue(content in response.data) self.logout() # Only logged in users can read it response = self.app.get("/") self.assertFalse(content in response.data) response = self.app.get(read_url) self.assertEquals(response.status_code, 302) self.assertTrue(u"Redirecting" in response.data) response = self.app.get("/atom") self.assertFalse(content in response.data) # Reader is allowed to read it self.login("Reader") response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) self.logout() # Spam isn't allowed to read it self.login("Spam") response = self.app.get("/") self.assertFalse(content in response.data) response = self.app.get(read_url) self.assertEquals(response.status_code, 403) response = self.app.get("/atom") self.assertFalse(content in response.data) self.logout() # But spam is allowed to read public posts by Author self.login("Author") title = u"Post with a title (public)" content = u"This is the post's content (test_private)." read_url = "/read/" + schrift.slugify(title) response = self.add_post(title, content, private=False) self.assertTrue(content in response.data) self.logout() self.login("Spam") response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) self.logout() # ... and unidentified users are allowed to read public posts by Author response = self.app.get("/") self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) response = self.app.get("/atom") self.assertTrue(content in response.data) def test_private_prev_next(self): self.login(self.author.name) private_title = u"Private Post" private_read_url = "/read/" + schrift.slugify(private_title) self.add_post(private_title, u"Spam", private=True) title = u"Second Post" read_url = "/read/" + schrift.slugify(title) self.add_post(title, u"Spam", private=False) # Author can see prev link response = self.app.get(read_url) self.assertTrue(private_read_url in response.data) # Reader, too self.login(self.reader.name) response = self.app.get(read_url) self.assertTrue(private_read_url in response.data) # The other reader not self.login(self.unauthorized.name) response = self.app.get(read_url) self.assertFalse(private_read_url in response.data) def test_private_auth_atom(self): self.login("Author") title = u"test_private_auth_atom" self.add_post(title, "Spam", private=True) self.logout() response = self.app.get("/atom?auth", headers=[("Authorization", "Basic QXV0aG9yOjEyMzU=")]) self.assertTrue(title in response.data) def test_unpublished(self): self.login("Author") title = u"Unpublished post" slug = schrift.slugify(title) self.add_post(title, u"Spam", published=False) # Author should see the unpublished post for url in ["/", "/Author", "/read/" + slug]: response = self.app.get(url) self.assertTrue(title in response.data, url) self.logout() # Everyone else not for url in ["/", "/Author", "/atom"]: response = self.app.get(url) self.assertFalse(title in response.data, url) # The post does not exist response = self.app.get("/read/" + slug) self.assertEquals(response.status_code, 404) def test_unpublished_prev_next(self): self.login(self.author.name) unpublished_title = u"Unpublished Post" unpublished_read_url = "/read/" + schrift.slugify(unpublished_title) self.add_post(unpublished_title, u"Spam", published=False) title = u"Second Post" read_url = "/read/" + schrift.slugify(title) self.add_post(title, u"Spam") # Author can see prev link response = self.app.get(read_url) self.assertTrue(unpublished_read_url in response.data) # All others not self.login(self.reader.name) response = self.app.get(read_url) self.assertFalse(unpublished_read_url in response.data) def test_duplicates(self): title = u"Duplicated title" read_url = "/read/" + schrift.slugify(title) self.login("Author") self.add_post(title, u"Spam") self.add_post(title, u"Spam") response = self.add_post(title, u"Spam") self.assertTrue(read_url in response.data) self.assertTrue(read_url + "-2" in response.data) self.assertTrue(read_url + "-3" in response.data) def test_user(self): self.login("Author") title = u"A public post." content = u"This is a public post (test_user)." read_url = "/Author/read/" + schrift.slugify(title) response = self.add_post(title, content) self.assertTrue(content in response.data) response = self.app.get(read_url) self.assertTrue(content in response.data) def test_slugify(self): self.assertEqual(schrift.slugify(u"ßpäm"), u"sspaem") self.assertEqual(schrift.slugify(u"slug With spaces"), u"slug-with-spaces") self.assertEqual(schrift.slugify(u"foo@bar"), u"foobar") self.assertEqual(schrift.slugify(u"slug with multiple -- spaces"), u"slug-with-multiple-spaces") self.assertEqual(schrift.slugify(u"42"), u"42") if __name__ == "__main__": unittest.main()
0.446012
0.244242
from dataclasses import dataclass, field from typing import Optional from transformers import AutoModelForTokenClassification, AutoConfig from transformers import HfArgumentParser import transformers import torch import logging import os from collections import OrderedDict from tqdm import tqdm os.environ["WANDB_DISABLED"] = "true" @dataclass class ModelArguments: """ Arguments for the models that should be merged and the amounts of training data sets for weighted averaging. """ output_dir: str = field( metadata={"help": "Path where the new model should be saved"} ) baseline_model: str = field( metadata={"help": "Name or path of pre-trained transformer model."} ) amount_of_labels: int = field( metadata={"help": "Number of labels the models were trained on."} ) first_model_path: str = field( metadata={"help": "Path to the first model."} ) amount_first_model: int = field( metadata={"help": "Amount of training data used for training the model."} ) second_model_path: str = field( metadata={"help": "Path to the second model."} ) amount_second_model: int = field( metadata={"help": "Amount of training data used for training the model."} ) further_models: Optional[str] = field( default="", metadata={"help": "Whitespace-separated list containing further models that should be merged for" "federated learning settings."} ) further_amounts: Optional[str] = field( default="", metadata={"help": "Whitespace-separated list consisting of further amounts corresponding to the" "amount of training data the further models were trained on"} ) def average_weights(input_models, coefficients): """average weights of different transformer models based on the amount of training data they were trained on""" weights_averaged = OrderedDict() for i, current_model in tqdm(enumerate(input_models), leave=False): current_weights = current_model.state_dict() for key in current_weights.keys(): if i == 0: weights_averaged[key] = coefficients[i] * current_weights[key] else: weights_averaged[key] += coefficients[i] * current_weights[key] return weights_averaged def update_a_model(base_model, weights): """update a base model with new weights""" base_model.load_state_dict(weights) return base_model if __name__ == '__main__': transformers.logging.set_verbosity_error() logger = logging.getLogger(__name__) # parse arguments parser = HfArgumentParser(ModelArguments) args = parser.parse_args() # baseline_model = "bert-base-cased" models_to_merge = [] training_data_amounts_temp = [] config = AutoConfig.from_pretrained( pretrained_model_name_or_path=args.baseline_model, num_labels=args.amount_of_labels ) # load models # baseline baseline_model = AutoModelForTokenClassification.from_pretrained( args.baseline_model, from_tf=bool(".ckpt" in args.baseline_model), config=config ) first_model_path = args.first_model_path first_model = AutoModelForTokenClassification.from_pretrained( first_model_path, from_tf=bool(".ckpt" in first_model_path), config=config ) models_to_merge.append(first_model) training_data_amounts_temp.append(args.amount_first_model) second_model_path = args.second_model_path second_model = AutoModelForTokenClassification.from_pretrained( second_model_path, from_tf=bool(".ckpt" in second_model_path), config=config ) models_to_merge.append(second_model) training_data_amounts_temp.append(args.amount_second_model) further_models = args.further_models.split() further_amounts = args.further_amounts.split() assert len(further_models) == len(further_amounts), "For each trained model a corresponding amount of the used " \ "training data is needed " for further_model, amount in zip(further_models, further_amounts): model = AutoModelForTokenClassification.from_pretrained( further_model, from_tf=bool(".ckpt" in further_model), config=config ) models_to_merge.append(model) training_data_amounts_temp.append(int(amount)) total_amount = sum(training_data_amounts_temp) training_data_amounts = [c / total_amount for c in training_data_amounts_temp] averaged_weights = average_weights(models_to_merge, training_data_amounts) updated_model = update_a_model(baseline_model, averaged_weights) if not os.path.exists(args.output_dir): os.mkdir(args.output_dir) WEIGHTS_NAME = "pytorch_model.bin" output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME) torch.save(updated_model.state_dict(), output_model_file) CONFIG_NAME = "config.json" output_config_file = os.path.join(args.output_dir, CONFIG_NAME) with open(output_config_file, 'w') as f: f.write(updated_model.config.to_json_string()) print('Model was saved to ', args.output_dir) with open(os.path.join(args.output_dir, "merged_models.txt"), "w") as f: print("--------------------------------------", file=f) print(f"Model 1: {first_model_path}", file=f) print(f"Model 2: {second_model_path}", file=f) c = 3 for model_path in args.further_models.split(): print(f"Model {str(c)}: {model_path}", file=f) c += 1 print(f"Coefficients: {str(training_data_amounts)}", file=f)
weaver.py
from dataclasses import dataclass, field from typing import Optional from transformers import AutoModelForTokenClassification, AutoConfig from transformers import HfArgumentParser import transformers import torch import logging import os from collections import OrderedDict from tqdm import tqdm os.environ["WANDB_DISABLED"] = "true" @dataclass class ModelArguments: """ Arguments for the models that should be merged and the amounts of training data sets for weighted averaging. """ output_dir: str = field( metadata={"help": "Path where the new model should be saved"} ) baseline_model: str = field( metadata={"help": "Name or path of pre-trained transformer model."} ) amount_of_labels: int = field( metadata={"help": "Number of labels the models were trained on."} ) first_model_path: str = field( metadata={"help": "Path to the first model."} ) amount_first_model: int = field( metadata={"help": "Amount of training data used for training the model."} ) second_model_path: str = field( metadata={"help": "Path to the second model."} ) amount_second_model: int = field( metadata={"help": "Amount of training data used for training the model."} ) further_models: Optional[str] = field( default="", metadata={"help": "Whitespace-separated list containing further models that should be merged for" "federated learning settings."} ) further_amounts: Optional[str] = field( default="", metadata={"help": "Whitespace-separated list consisting of further amounts corresponding to the" "amount of training data the further models were trained on"} ) def average_weights(input_models, coefficients): """average weights of different transformer models based on the amount of training data they were trained on""" weights_averaged = OrderedDict() for i, current_model in tqdm(enumerate(input_models), leave=False): current_weights = current_model.state_dict() for key in current_weights.keys(): if i == 0: weights_averaged[key] = coefficients[i] * current_weights[key] else: weights_averaged[key] += coefficients[i] * current_weights[key] return weights_averaged def update_a_model(base_model, weights): """update a base model with new weights""" base_model.load_state_dict(weights) return base_model if __name__ == '__main__': transformers.logging.set_verbosity_error() logger = logging.getLogger(__name__) # parse arguments parser = HfArgumentParser(ModelArguments) args = parser.parse_args() # baseline_model = "bert-base-cased" models_to_merge = [] training_data_amounts_temp = [] config = AutoConfig.from_pretrained( pretrained_model_name_or_path=args.baseline_model, num_labels=args.amount_of_labels ) # load models # baseline baseline_model = AutoModelForTokenClassification.from_pretrained( args.baseline_model, from_tf=bool(".ckpt" in args.baseline_model), config=config ) first_model_path = args.first_model_path first_model = AutoModelForTokenClassification.from_pretrained( first_model_path, from_tf=bool(".ckpt" in first_model_path), config=config ) models_to_merge.append(first_model) training_data_amounts_temp.append(args.amount_first_model) second_model_path = args.second_model_path second_model = AutoModelForTokenClassification.from_pretrained( second_model_path, from_tf=bool(".ckpt" in second_model_path), config=config ) models_to_merge.append(second_model) training_data_amounts_temp.append(args.amount_second_model) further_models = args.further_models.split() further_amounts = args.further_amounts.split() assert len(further_models) == len(further_amounts), "For each trained model a corresponding amount of the used " \ "training data is needed " for further_model, amount in zip(further_models, further_amounts): model = AutoModelForTokenClassification.from_pretrained( further_model, from_tf=bool(".ckpt" in further_model), config=config ) models_to_merge.append(model) training_data_amounts_temp.append(int(amount)) total_amount = sum(training_data_amounts_temp) training_data_amounts = [c / total_amount for c in training_data_amounts_temp] averaged_weights = average_weights(models_to_merge, training_data_amounts) updated_model = update_a_model(baseline_model, averaged_weights) if not os.path.exists(args.output_dir): os.mkdir(args.output_dir) WEIGHTS_NAME = "pytorch_model.bin" output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME) torch.save(updated_model.state_dict(), output_model_file) CONFIG_NAME = "config.json" output_config_file = os.path.join(args.output_dir, CONFIG_NAME) with open(output_config_file, 'w') as f: f.write(updated_model.config.to_json_string()) print('Model was saved to ', args.output_dir) with open(os.path.join(args.output_dir, "merged_models.txt"), "w") as f: print("--------------------------------------", file=f) print(f"Model 1: {first_model_path}", file=f) print(f"Model 2: {second_model_path}", file=f) c = 3 for model_path in args.further_models.split(): print(f"Model {str(c)}: {model_path}", file=f) c += 1 print(f"Coefficients: {str(training_data_amounts)}", file=f)
0.891782
0.376451
import numpy as np from . import core def mass(Q, T, M_T, Σ_T, trivial_idx=None, excl_zone=0, left=False, right=False): """ Compute "Mueen's Algorithm for Similarity Search" (MASS) Parameters ---------- Q : ndarray Query array or subsequence T : ndarray Time series array or sequence M_T : ndarray Sliding mean for `T` Σ_T : ndarray Sliding standard deviation for `T` trivial_idx : int Index for the start of the trivial self-join excl_zone : int The half width for the exclusion zone relative to the `trivial_idx`. If the `trivial_idx` is `None` then this parameter is ignored. left : bool Return the left matrix profile indices if `True`. If `right` is True then this parameter is ignored. right : bool Return the right matrix profiles indices if `True` Returns ------- P : ndarray Matrix profile I : ndarray Matrix profile indices """ D = core.mass(Q, T, M_T, Σ_T) if trivial_idx is not None: zone_start = max(0, trivial_idx-excl_zone) zone_stop = min(T.shape[0]-Q.shape[0]+1, trivial_idx+excl_zone) D[zone_start:zone_stop] = np.inf #Get left and right matrix profiles IL = -1 PL = np.inf if D[:trivial_idx].size: IL = np.argmin(D[:trivial_idx]) PL = D[IL] if zone_start <= IL <= zone_stop: IL = -1 IR = -1 PR = -1 if D[trivial_idx:].size: IR = trivial_idx + np.argmin(D[trivial_idx:]) PR = D[IR] if zone_start <= IR <= zone_stop: IR = -1 # Element-wise Min I = np.argmin(D) P = D[I] if trivial_idx is not None and left: I = IL P = PL if trivial_idx is not None and right: I = IR P = PR return P, I def stamp(T_A, T_B, m, ignore_trivial=False): """ Compute matrix profile and indices using the "Scalable Time series Anytime Matrix Profile" (STAMP) algorithm and MASS (2017 - with FFT). Parameters ---------- T_A : ndarray The time series or sequence for which the matrix profile index will be returned T_B : ndarray The time series or sequence that contain your query subsequences m : int Window size ignore_trivial : bool `True` if this is a self join and `False` otherwise (i.e., AB-join). Returns ------- out : ndarray Two column numpy array where the first column is the matrix profile and the second column is the matrix profile indices Notes ----- DOI: 10.1109/ICDM.2016.0179 See Table III Timeseries, T_B, will be annotated with the distance location (or index) of all its subsequences in another times series, T_A. For every subsequence, Q, in T_B, you will get a distance and index for the closest subsequence in T_A. Thus, the array returned will have length T_B.shape[0]-m+1 """ core.check_dtype(T_A) core.check_dtype(T_B) subseq_T_B = core.rolling_window(T_B, m) excl_zone = int(np.ceil(m/2)) M_T, Σ_T = core.compute_mean_std(T_A, m) # Add exclusionary zone if ignore_trivial: out = [mass(subseq, T_A, M_T, Σ_T, i, excl_zone) for i, subseq in enumerate(subseq_T_B)] else: out = [mass(subseq, T_A, M_T, Σ_T) for subseq in subseq_T_B] out = np.array(out, dtype=object) return out
stumpy/stamp.py
import numpy as np from . import core def mass(Q, T, M_T, Σ_T, trivial_idx=None, excl_zone=0, left=False, right=False): """ Compute "Mueen's Algorithm for Similarity Search" (MASS) Parameters ---------- Q : ndarray Query array or subsequence T : ndarray Time series array or sequence M_T : ndarray Sliding mean for `T` Σ_T : ndarray Sliding standard deviation for `T` trivial_idx : int Index for the start of the trivial self-join excl_zone : int The half width for the exclusion zone relative to the `trivial_idx`. If the `trivial_idx` is `None` then this parameter is ignored. left : bool Return the left matrix profile indices if `True`. If `right` is True then this parameter is ignored. right : bool Return the right matrix profiles indices if `True` Returns ------- P : ndarray Matrix profile I : ndarray Matrix profile indices """ D = core.mass(Q, T, M_T, Σ_T) if trivial_idx is not None: zone_start = max(0, trivial_idx-excl_zone) zone_stop = min(T.shape[0]-Q.shape[0]+1, trivial_idx+excl_zone) D[zone_start:zone_stop] = np.inf #Get left and right matrix profiles IL = -1 PL = np.inf if D[:trivial_idx].size: IL = np.argmin(D[:trivial_idx]) PL = D[IL] if zone_start <= IL <= zone_stop: IL = -1 IR = -1 PR = -1 if D[trivial_idx:].size: IR = trivial_idx + np.argmin(D[trivial_idx:]) PR = D[IR] if zone_start <= IR <= zone_stop: IR = -1 # Element-wise Min I = np.argmin(D) P = D[I] if trivial_idx is not None and left: I = IL P = PL if trivial_idx is not None and right: I = IR P = PR return P, I def stamp(T_A, T_B, m, ignore_trivial=False): """ Compute matrix profile and indices using the "Scalable Time series Anytime Matrix Profile" (STAMP) algorithm and MASS (2017 - with FFT). Parameters ---------- T_A : ndarray The time series or sequence for which the matrix profile index will be returned T_B : ndarray The time series or sequence that contain your query subsequences m : int Window size ignore_trivial : bool `True` if this is a self join and `False` otherwise (i.e., AB-join). Returns ------- out : ndarray Two column numpy array where the first column is the matrix profile and the second column is the matrix profile indices Notes ----- DOI: 10.1109/ICDM.2016.0179 See Table III Timeseries, T_B, will be annotated with the distance location (or index) of all its subsequences in another times series, T_A. For every subsequence, Q, in T_B, you will get a distance and index for the closest subsequence in T_A. Thus, the array returned will have length T_B.shape[0]-m+1 """ core.check_dtype(T_A) core.check_dtype(T_B) subseq_T_B = core.rolling_window(T_B, m) excl_zone = int(np.ceil(m/2)) M_T, Σ_T = core.compute_mean_std(T_A, m) # Add exclusionary zone if ignore_trivial: out = [mass(subseq, T_A, M_T, Σ_T, i, excl_zone) for i, subseq in enumerate(subseq_T_B)] else: out = [mass(subseq, T_A, M_T, Σ_T) for subseq in subseq_T_B] out = np.array(out, dtype=object) return out
0.941654
0.757862
from datetime import datetime from kubernetes import client, config import logging import os import subprocess import time ANNOTATION_PREFIX = 'time-sync.riasc.eu' NODE_NAME = os.environ.get('NODE_NAME', 'infis-pi') def get_status(): sources = {} fields = { 'sources': sources } ret = subprocess.run(['chronyc', '-ncm', 'tracking', 'sources'], capture_output=True, check=True) lines = ret.stdout.decode('ascii').split('\n') cols = lines[0].split(',') fields['ref_id'] = int(cols[0]) fields['ref_name'] = cols[1] fields['stratum'] = int(cols[2]) fields['ref_time'] = datetime.utcfromtimestamp(float(cols[3])) fields['current_correction'] = float(cols[4]) fields['last_offset'] = float(cols[5]) fields['rms_offset'] = float(cols[6]) fields['freq_ppm'] = float(cols[7]) fields['resid_freq_ppm'] = float(cols[8]) fields['skew_ppm'] = float(cols[9]) fields['root_delay'] = float(cols[10]) fields['root_dispersion'] = float(cols[11]) fields['last_update_interval'] = float(cols[12]) fields['leap_status'] = cols[13].lower() for line in lines[1:]: cols = line.split(',') if len(cols) < 8: continue name = cols[2] if cols[0] == '^': mode = 'server' elif cols[0] == '=': mode = 'peer' elif cols[0] == '#': mode = 'ref_clock' if cols[1] == '*': state = 'synced' elif cols[1] == '+': state = 'combined' elif cols[1] == '-': state = 'excluded' elif cols[1] == '?': state = 'lost' elif cols[1] == 'x': state = 'false' elif cols[1] == '~': state = 'too_variable' sources[name] = { 'mode': mode, 'state': state, 'stratum': cols[3], 'poll': cols[4], 'reach': cols[5], 'last_rx': cols[6], 'last_sample': cols[7] } return fields def is_synced(status): if status is None: return None for _, source in status.get('sources', {}).items(): if source.get('state', 'unknown') == 'synced': return True return False def patch_node_status(v1, status): synced = is_synced(status) if synced is True: condition = { 'type': 'TimeSynced', 'status': 'True', 'reason': 'ChronyHasSyncSource', 'message': 'Time of node is synchronized' } elif synced is False: condition = { 'type': 'TimeSynced', 'status': 'False', 'reason': 'ChronyHasNoSyncSource', 'message': 'Time of node is not synchronized' } else: condition = { 'type': 'TimeSynced', 'status': 'Unknown', 'reason': 'ChronyNotRunning', 'message': 'Time of node is not synchronized' } patch = { 'status': { 'conditions': [condition] } } ret = v1.patch_node_status(NODE_NAME, patch) logging.info('Updated node condition') def patch_node(v1, status): annotations = { ANNOTATION_PREFIX + '/' + key.replace('_', '-'): str(status[key]) if status else None for key in ['stratum', 'ref_name', 'leap_status'] } patch = { 'metadata': { 'annotations': annotations } } v1.patch_node(NODE_NAME, patch) logging.info('Updated node annotations') def main(): logging.basicConfig(level=logging.INFO) if os.environ.get('KUBECONFIG'): config.load_kube_config() else: config.load_incluster_config() v1 = client.CoreV1Api() while True: try: status = get_status() # status = {'sources': {'172.16.31.10': {'mode': 'server', 'state': 'combined', 'stratum': '1', 'poll': '10', 'reach': '377', 'last_rx': '461', 'last_sample': '-0.000032053'}, '172.16.31.10': {'mode': 'server', 'state': 'synced', 'stratum': '1', 'poll': '10', 'reach': '377', 'last_rx': '392', 'last_sample': '-0.000043199'}}, 'ref_id': 86820511, 'ref_name': '172.16.31.10', 'stratum': 2, 'ref_time': datetime.datetime(2021, 6, 28, 13, 43, 10, 329265), 'current_correction': 1.7534e-05, 'last_offset': 2.552e-06, 'rms_offset': 1.9959e-05, 'freq_ppm': -87.802, 'resid_freq_ppm': 0.0, 'skew_ppm': 0.006, 'root_delay': 0.000375683, 'root_dispersion': 0.00056641, 'last_update_interval': 1024.8, 'leap_status': 'normal'} logging.info('Got status: %s', status) except Exception as e: logging.warning('Failed to query Chrony status: %s', e) status = None patch_node_status(v1, status) patch_node(v1, status) time.sleep(10) if __name__ == '__main__': main()
images/time-sync/chrony-monitor.py
from datetime import datetime from kubernetes import client, config import logging import os import subprocess import time ANNOTATION_PREFIX = 'time-sync.riasc.eu' NODE_NAME = os.environ.get('NODE_NAME', 'infis-pi') def get_status(): sources = {} fields = { 'sources': sources } ret = subprocess.run(['chronyc', '-ncm', 'tracking', 'sources'], capture_output=True, check=True) lines = ret.stdout.decode('ascii').split('\n') cols = lines[0].split(',') fields['ref_id'] = int(cols[0]) fields['ref_name'] = cols[1] fields['stratum'] = int(cols[2]) fields['ref_time'] = datetime.utcfromtimestamp(float(cols[3])) fields['current_correction'] = float(cols[4]) fields['last_offset'] = float(cols[5]) fields['rms_offset'] = float(cols[6]) fields['freq_ppm'] = float(cols[7]) fields['resid_freq_ppm'] = float(cols[8]) fields['skew_ppm'] = float(cols[9]) fields['root_delay'] = float(cols[10]) fields['root_dispersion'] = float(cols[11]) fields['last_update_interval'] = float(cols[12]) fields['leap_status'] = cols[13].lower() for line in lines[1:]: cols = line.split(',') if len(cols) < 8: continue name = cols[2] if cols[0] == '^': mode = 'server' elif cols[0] == '=': mode = 'peer' elif cols[0] == '#': mode = 'ref_clock' if cols[1] == '*': state = 'synced' elif cols[1] == '+': state = 'combined' elif cols[1] == '-': state = 'excluded' elif cols[1] == '?': state = 'lost' elif cols[1] == 'x': state = 'false' elif cols[1] == '~': state = 'too_variable' sources[name] = { 'mode': mode, 'state': state, 'stratum': cols[3], 'poll': cols[4], 'reach': cols[5], 'last_rx': cols[6], 'last_sample': cols[7] } return fields def is_synced(status): if status is None: return None for _, source in status.get('sources', {}).items(): if source.get('state', 'unknown') == 'synced': return True return False def patch_node_status(v1, status): synced = is_synced(status) if synced is True: condition = { 'type': 'TimeSynced', 'status': 'True', 'reason': 'ChronyHasSyncSource', 'message': 'Time of node is synchronized' } elif synced is False: condition = { 'type': 'TimeSynced', 'status': 'False', 'reason': 'ChronyHasNoSyncSource', 'message': 'Time of node is not synchronized' } else: condition = { 'type': 'TimeSynced', 'status': 'Unknown', 'reason': 'ChronyNotRunning', 'message': 'Time of node is not synchronized' } patch = { 'status': { 'conditions': [condition] } } ret = v1.patch_node_status(NODE_NAME, patch) logging.info('Updated node condition') def patch_node(v1, status): annotations = { ANNOTATION_PREFIX + '/' + key.replace('_', '-'): str(status[key]) if status else None for key in ['stratum', 'ref_name', 'leap_status'] } patch = { 'metadata': { 'annotations': annotations } } v1.patch_node(NODE_NAME, patch) logging.info('Updated node annotations') def main(): logging.basicConfig(level=logging.INFO) if os.environ.get('KUBECONFIG'): config.load_kube_config() else: config.load_incluster_config() v1 = client.CoreV1Api() while True: try: status = get_status() # status = {'sources': {'172.16.31.10': {'mode': 'server', 'state': 'combined', 'stratum': '1', 'poll': '10', 'reach': '377', 'last_rx': '461', 'last_sample': '-0.000032053'}, '172.16.31.10': {'mode': 'server', 'state': 'synced', 'stratum': '1', 'poll': '10', 'reach': '377', 'last_rx': '392', 'last_sample': '-0.000043199'}}, 'ref_id': 86820511, 'ref_name': '172.16.31.10', 'stratum': 2, 'ref_time': datetime.datetime(2021, 6, 28, 13, 43, 10, 329265), 'current_correction': 1.7534e-05, 'last_offset': 2.552e-06, 'rms_offset': 1.9959e-05, 'freq_ppm': -87.802, 'resid_freq_ppm': 0.0, 'skew_ppm': 0.006, 'root_delay': 0.000375683, 'root_dispersion': 0.00056641, 'last_update_interval': 1024.8, 'leap_status': 'normal'} logging.info('Got status: %s', status) except Exception as e: logging.warning('Failed to query Chrony status: %s', e) status = None patch_node_status(v1, status) patch_node(v1, status) time.sleep(10) if __name__ == '__main__': main()
0.405096
0.205217
from cosivina.base import * elementSpec = [] class Element(object): ''' Base class for elements. ''' def __init__(self, label): self.label = label self.parameters = {} self.components = {} self.defaultOutputComponent = '' self.inputElementLabels = [] self.inputComponents = [] self.inputs = [] self.nInputs = 0 def init(self): ''' Initialize element. ''' pass def step(self, time, deltaT): ''' Perform a single simulation step. ''' pass def close(self): ''' Close any connections to files or hardware. ''' pass def isParameter(self, name): ''' Check if string is name of parameter in element. ''' return name in self.parameters def isComponent(self, name): ''' Check if string is name of component in element. ''' return name in self.components def parameterList(self): ''' Get a list of element's parameter names. ''' return list(self.parameters.keys()) def getParameterStatus(self, name): ''' Get int value indicating change status of parameter. ''' if not name in self.parameters: raise ValueError('Parameter name not found.') return self.parameters[name] def addInput(self, inputElementLabel, inputComponent): ''' Add an input to the element. ''' self.inputElementLabels.append(inputElementLabel) self.inputComponents.append(inputComponent) self.nInputs += 1 if options.useNumba: elementSpec = [ ('label', stringType), ('parameters', types.DictType(stringType, intType)), ('components', types.DictType(stringType, intType)), ('defaultOutputComponent', stringType), ('inputElementLabels', stringListType), ('inputComponents', stringListType), ('inputs', types.ListType(arrayType2D)), ('nInputs', intType) ] def numbaInit(self, label): self.label = label self.parameters = typed.Dict.empty(stringType, intType) self.components = typed.Dict.empty(stringType, intType) self.defaultOutputComponent = '' self.inputElementLabels = typed.List.empty_list(stringType) self.inputComponents = typed.List.empty_list(stringType) self.inputs = typed.List.empty_list(arrayType2D) self.nInputs = intType(0) Element.__init__ = numbaInit
cosivina/Element.py
from cosivina.base import * elementSpec = [] class Element(object): ''' Base class for elements. ''' def __init__(self, label): self.label = label self.parameters = {} self.components = {} self.defaultOutputComponent = '' self.inputElementLabels = [] self.inputComponents = [] self.inputs = [] self.nInputs = 0 def init(self): ''' Initialize element. ''' pass def step(self, time, deltaT): ''' Perform a single simulation step. ''' pass def close(self): ''' Close any connections to files or hardware. ''' pass def isParameter(self, name): ''' Check if string is name of parameter in element. ''' return name in self.parameters def isComponent(self, name): ''' Check if string is name of component in element. ''' return name in self.components def parameterList(self): ''' Get a list of element's parameter names. ''' return list(self.parameters.keys()) def getParameterStatus(self, name): ''' Get int value indicating change status of parameter. ''' if not name in self.parameters: raise ValueError('Parameter name not found.') return self.parameters[name] def addInput(self, inputElementLabel, inputComponent): ''' Add an input to the element. ''' self.inputElementLabels.append(inputElementLabel) self.inputComponents.append(inputComponent) self.nInputs += 1 if options.useNumba: elementSpec = [ ('label', stringType), ('parameters', types.DictType(stringType, intType)), ('components', types.DictType(stringType, intType)), ('defaultOutputComponent', stringType), ('inputElementLabels', stringListType), ('inputComponents', stringListType), ('inputs', types.ListType(arrayType2D)), ('nInputs', intType) ] def numbaInit(self, label): self.label = label self.parameters = typed.Dict.empty(stringType, intType) self.components = typed.Dict.empty(stringType, intType) self.defaultOutputComponent = '' self.inputElementLabels = typed.List.empty_list(stringType) self.inputComponents = typed.List.empty_list(stringType) self.inputs = typed.List.empty_list(arrayType2D) self.nInputs = intType(0) Element.__init__ = numbaInit
0.628065
0.193967
import pandas as pd from sklearn import model_selection from sklearn.tree import DecisionTreeClassifier def predict(home_team, away_team, city, toss_winner, toss_decision): matches_cleaned_data = pd.read_csv('./Dataset/matches_cleaned.csv') matches_df = matches_cleaned_data[['team1', 'team2', 'city', 'toss_winner', 'toss_decision', 'winner']] # Split-out validation dataset array = matches_df.values x = array[:, 0:5] y = array[:, 5] validation_size = 0.10 seed = 7 x_train, x_validation, y_train, y_validation = model_selection.train_test_split(x, y, test_size=validation_size, random_state=seed) # Test options and evaluation metric knn = DecisionTreeClassifier() knn.fit(x_train, y_train) results = convert_to_numerical_field(home_team, away_team, city, toss_winner, toss_decision) predictions = knn.predict([results]) team = '' if predictions[0] == '6': team = 'KKR' if predictions[0] == "5": team = 'RCB' if predictions[0] == "9": team = 'CSK' if predictions[0] == "10": team = 'RR' if predictions[0] == "7": team = 'DD' if predictions[0] == "8": team = 'KXIP' if predictions[0] == "1": team = 'SRH' if predictions[0] == "2": team = 'MI' print("model->" + team) if int(predictions) != convert_again(home_team).__int__() and int(predictions) != convert_again(away_team).__int__(): print("Exception Case") winner = convert_to_shortform(calculate_ef_score(home_team, away_team)) print("EF score data ->" + winner) return winner else: return team.__str__() def convert_to_shortform(winning_team): if winning_team == 'Kolkata': return 'KKR' if winning_team == "Bangalore": return 'RCB' if winning_team == "Pune": return 'CSK' if winning_team == "Jaipur": return 'RR' if winning_team == "Delhi": return 'DD' if winning_team == "Dharamshala": return 'KXIP' if winning_team == "Hyderabad": return 'SRH' if winning_team == "Mumbai": return 'MI' def convert_again(home_team): if home_team == 'Kolkata': return 6 if home_team == "Bangalore": return 5 if home_team == "Pune": return 9 if home_team == "Jaipur": return 10 if home_team == "Delhi": return 7 if home_team == "Dharamshala": return 8 if home_team == "Hyderabad": return 1 if home_team == "Mumbai": return 2 def convert_to_numerical_field(home_team, away_team, city, toss_winner, toss_decision): list = [] if home_team == 'Kolkata': list.append(6) if home_team == "Bangalore": list.append(5) if home_team == "Pune": list.append(9) if home_team == "Jaipur": list.append(10) if home_team == "Delhi": list.append(7) if home_team == "Dharamshala": list.append(8) if home_team == "Hyderabad": list.append(1) if home_team == "Mumbai": list.append(2) if away_team == "Kolkata": list.append(6) if away_team == "Bangalore": list.append(5) if away_team == "Pune": list.append(9) if away_team == "Jaipur": list.append(10) if away_team == "Delhi": list.append(7) if away_team == "Dharamshala": list.append(8) if away_team == "Hyderabad": list.append(1) if away_team == "Mumbai": list.append(2) if city[6:] == "Kolkata": list.append(7) if city[6:] == "Bangalore": list.append(5) if city[6:] == "Pune": list.append(2) if city[6:] == "Jaipur": list.append(11) if city[6:] == "Delhi": list.append(8) if city[6:] == "Dharamshala": list.append(24) if city[6:] == "Hyderabad": list.append(1) if city[6:] == "Mumbai": list.append(6) if toss_winner == "KKR": list.append(6) if toss_winner == "RCB": list.append(5) if toss_winner == "CSK": list.append(9) if toss_winner == "RR": list.append(10) if toss_winner == "DD": list.append(7) if toss_winner == "KXIP": list.append(8) if toss_winner == "SRH": list.append(1) if toss_winner == "MI": list.append(2) if toss_decision == "Bat": list.append(2) if toss_decision == "Field": list.append(1) return list # prediction from site scrape data def calculate_ef_score(home, away): data = pd.read_csv('./Dataset/_team_rank.csv') home_score = list(data.loc[data['Team'] == home]['sum']) away_score = list(data.loc[data['Team'] == away]['sum']) if home_score > away_score: return home else: return away # predict('Jaipur', 'Hyderabad', 'City: Jaipur', 'RR', 'Bat')
prediction.py
import pandas as pd from sklearn import model_selection from sklearn.tree import DecisionTreeClassifier def predict(home_team, away_team, city, toss_winner, toss_decision): matches_cleaned_data = pd.read_csv('./Dataset/matches_cleaned.csv') matches_df = matches_cleaned_data[['team1', 'team2', 'city', 'toss_winner', 'toss_decision', 'winner']] # Split-out validation dataset array = matches_df.values x = array[:, 0:5] y = array[:, 5] validation_size = 0.10 seed = 7 x_train, x_validation, y_train, y_validation = model_selection.train_test_split(x, y, test_size=validation_size, random_state=seed) # Test options and evaluation metric knn = DecisionTreeClassifier() knn.fit(x_train, y_train) results = convert_to_numerical_field(home_team, away_team, city, toss_winner, toss_decision) predictions = knn.predict([results]) team = '' if predictions[0] == '6': team = 'KKR' if predictions[0] == "5": team = 'RCB' if predictions[0] == "9": team = 'CSK' if predictions[0] == "10": team = 'RR' if predictions[0] == "7": team = 'DD' if predictions[0] == "8": team = 'KXIP' if predictions[0] == "1": team = 'SRH' if predictions[0] == "2": team = 'MI' print("model->" + team) if int(predictions) != convert_again(home_team).__int__() and int(predictions) != convert_again(away_team).__int__(): print("Exception Case") winner = convert_to_shortform(calculate_ef_score(home_team, away_team)) print("EF score data ->" + winner) return winner else: return team.__str__() def convert_to_shortform(winning_team): if winning_team == 'Kolkata': return 'KKR' if winning_team == "Bangalore": return 'RCB' if winning_team == "Pune": return 'CSK' if winning_team == "Jaipur": return 'RR' if winning_team == "Delhi": return 'DD' if winning_team == "Dharamshala": return 'KXIP' if winning_team == "Hyderabad": return 'SRH' if winning_team == "Mumbai": return 'MI' def convert_again(home_team): if home_team == 'Kolkata': return 6 if home_team == "Bangalore": return 5 if home_team == "Pune": return 9 if home_team == "Jaipur": return 10 if home_team == "Delhi": return 7 if home_team == "Dharamshala": return 8 if home_team == "Hyderabad": return 1 if home_team == "Mumbai": return 2 def convert_to_numerical_field(home_team, away_team, city, toss_winner, toss_decision): list = [] if home_team == 'Kolkata': list.append(6) if home_team == "Bangalore": list.append(5) if home_team == "Pune": list.append(9) if home_team == "Jaipur": list.append(10) if home_team == "Delhi": list.append(7) if home_team == "Dharamshala": list.append(8) if home_team == "Hyderabad": list.append(1) if home_team == "Mumbai": list.append(2) if away_team == "Kolkata": list.append(6) if away_team == "Bangalore": list.append(5) if away_team == "Pune": list.append(9) if away_team == "Jaipur": list.append(10) if away_team == "Delhi": list.append(7) if away_team == "Dharamshala": list.append(8) if away_team == "Hyderabad": list.append(1) if away_team == "Mumbai": list.append(2) if city[6:] == "Kolkata": list.append(7) if city[6:] == "Bangalore": list.append(5) if city[6:] == "Pune": list.append(2) if city[6:] == "Jaipur": list.append(11) if city[6:] == "Delhi": list.append(8) if city[6:] == "Dharamshala": list.append(24) if city[6:] == "Hyderabad": list.append(1) if city[6:] == "Mumbai": list.append(6) if toss_winner == "KKR": list.append(6) if toss_winner == "RCB": list.append(5) if toss_winner == "CSK": list.append(9) if toss_winner == "RR": list.append(10) if toss_winner == "DD": list.append(7) if toss_winner == "KXIP": list.append(8) if toss_winner == "SRH": list.append(1) if toss_winner == "MI": list.append(2) if toss_decision == "Bat": list.append(2) if toss_decision == "Field": list.append(1) return list # prediction from site scrape data def calculate_ef_score(home, away): data = pd.read_csv('./Dataset/_team_rank.csv') home_score = list(data.loc[data['Team'] == home]['sum']) away_score = list(data.loc[data['Team'] == away]['sum']) if home_score > away_score: return home else: return away # predict('Jaipur', 'Hyderabad', 'City: Jaipur', 'RR', 'Bat')
0.303629
0.401453
import numpy as np from model.content_types import ContentType from model.group_chat import GroupChat from model.message import Message from model.reaction import Reaction class JsonParser: """ Parses the facebook data files to a GroupChat object """ def json_to_group_chat(self, data_files): users = set() messages = [] for data in data_files: users.update(self.__get_participants_from_json(data["participants"])) messages.extend(self.__get_messages_from_json(data["messages"])) return GroupChat(users, np.array(messages)) def __get_participants_from_json(self, json_participants): return [name["name"].encode("latin_1").decode("utf_8") for name in json_participants] def __get_messages_from_json(self, json_messages): messages = [] for dict_message in json_messages: timestamp = dict_message["timestamp_ms"] sender = dict_message["sender_name"].encode("latin_1").decode("utf_8") # Ensure name is correct reactions = self.__parse_reactions_from_json(dict_message) content_type = self.__parse_type_from_json(dict_message["type"], dict_message) content = self.__parse_content_from_json(content_type, dict_message) new_message = Message(timestamp, sender, reactions, content_type, content) messages.append(new_message) return messages def __parse_reactions_from_json(self, dict_message): if "reactions" in dict_message: reactions = [] for reaction in dict_message["reactions"]: reactions.append(Reaction(reaction["actor"], reaction["reaction"])) return reactions return None # The case where no one reacted to the message def __parse_type_from_json(self, json_type, dict_message): """ Converts facebook type to internal :param json_type: The type specified in the file :param dict_message: The whole dict used to find internal differences :return: An enum specifying the content type """ if json_type == "Generic": # Generic has multiple payloads we need to check if "sticker" in dict_message: return ContentType.STICKER elif "gifs" in dict_message: return ContentType.GIF elif "videos" in dict_message: return ContentType.VIDEO elif "photos" in dict_message: return ContentType.IMAGE elif "content" in dict_message: return ContentType.TEXT elif "audio_files" in dict_message: return ContentType.AUDIO elif len(dict_message) == 3: # The case where empty message, we verify by controlling nr fields return ContentType.EMPTY else: # Todo fortsätt med att fixa all olika möjlig data raise ValueError("The generic type had unknown payload, " + str(dict_message)) elif json_type == "Share": return ContentType.SHARE elif json_type == "Call": return ContentType.CALL elif json_type == "Subscribe": return ContentType.SUBSCRIBE else: raise ValueError("Unsupported json type, " + str(json_type)) def __parse_content_from_json(self, content_type, dict_message): """ Parses the JSON to get information from the message depending on its type. :param content_type: The type of content :param dict_message: The json :return: The content of the message """ if content_type == ContentType.TEXT: return dict_message["content"].encode("latin_1").decode("utf_8").lower() # Fixing encoding of the data elif content_type == ContentType.SHARE: if "share" in dict_message: if "link" in dict_message["share"]: # For sharing links return dict_message["share"]["link"] elif "share_text" in dict_message["share"]: # For sharing location return dict_message["share"]["share_text"] else: raise ValueError("The message had an unknown share content " + str(dict_message["share"])) else: if "content" in dict_message: return dict_message["content"] else: raise ValueError("The message was share classified but no content " + str(dict_message["share"])) elif content_type == ContentType.GIF: return self.__get_nested_uri(dict_message["gifs"]) elif content_type == ContentType.IMAGE: return self.__get_nested_uri(dict_message["photos"]) elif content_type == ContentType.VIDEO: return self.__get_nested_uri(dict_message["videos"]) # Only takes the uri, ignore ts of video and thumbnail elif content_type == ContentType.STICKER: return dict_message["sticker"]["uri"] elif content_type == ContentType.EMPTY: return "Empty" elif content_type == ContentType.CALL: return dict_message["call_duration"] # Returns how long the call was elif content_type == ContentType.SUBSCRIBE: new_users = [] for user in dict_message["users"]: new_users.append(user["name"]) return new_users elif content_type == ContentType.AUDIO: return self.__get_nested_uri(dict_message["audio_files"]) else: raise ValueError("content_type is not known" + str(content_type)) def __get_nested_uri(self, data): entities = [] for entity in data: entities.append(entity["uri"]) # Only takes the uri, ignore possibly other attribues return entities
json_parser.py
import numpy as np from model.content_types import ContentType from model.group_chat import GroupChat from model.message import Message from model.reaction import Reaction class JsonParser: """ Parses the facebook data files to a GroupChat object """ def json_to_group_chat(self, data_files): users = set() messages = [] for data in data_files: users.update(self.__get_participants_from_json(data["participants"])) messages.extend(self.__get_messages_from_json(data["messages"])) return GroupChat(users, np.array(messages)) def __get_participants_from_json(self, json_participants): return [name["name"].encode("latin_1").decode("utf_8") for name in json_participants] def __get_messages_from_json(self, json_messages): messages = [] for dict_message in json_messages: timestamp = dict_message["timestamp_ms"] sender = dict_message["sender_name"].encode("latin_1").decode("utf_8") # Ensure name is correct reactions = self.__parse_reactions_from_json(dict_message) content_type = self.__parse_type_from_json(dict_message["type"], dict_message) content = self.__parse_content_from_json(content_type, dict_message) new_message = Message(timestamp, sender, reactions, content_type, content) messages.append(new_message) return messages def __parse_reactions_from_json(self, dict_message): if "reactions" in dict_message: reactions = [] for reaction in dict_message["reactions"]: reactions.append(Reaction(reaction["actor"], reaction["reaction"])) return reactions return None # The case where no one reacted to the message def __parse_type_from_json(self, json_type, dict_message): """ Converts facebook type to internal :param json_type: The type specified in the file :param dict_message: The whole dict used to find internal differences :return: An enum specifying the content type """ if json_type == "Generic": # Generic has multiple payloads we need to check if "sticker" in dict_message: return ContentType.STICKER elif "gifs" in dict_message: return ContentType.GIF elif "videos" in dict_message: return ContentType.VIDEO elif "photos" in dict_message: return ContentType.IMAGE elif "content" in dict_message: return ContentType.TEXT elif "audio_files" in dict_message: return ContentType.AUDIO elif len(dict_message) == 3: # The case where empty message, we verify by controlling nr fields return ContentType.EMPTY else: # Todo fortsätt med att fixa all olika möjlig data raise ValueError("The generic type had unknown payload, " + str(dict_message)) elif json_type == "Share": return ContentType.SHARE elif json_type == "Call": return ContentType.CALL elif json_type == "Subscribe": return ContentType.SUBSCRIBE else: raise ValueError("Unsupported json type, " + str(json_type)) def __parse_content_from_json(self, content_type, dict_message): """ Parses the JSON to get information from the message depending on its type. :param content_type: The type of content :param dict_message: The json :return: The content of the message """ if content_type == ContentType.TEXT: return dict_message["content"].encode("latin_1").decode("utf_8").lower() # Fixing encoding of the data elif content_type == ContentType.SHARE: if "share" in dict_message: if "link" in dict_message["share"]: # For sharing links return dict_message["share"]["link"] elif "share_text" in dict_message["share"]: # For sharing location return dict_message["share"]["share_text"] else: raise ValueError("The message had an unknown share content " + str(dict_message["share"])) else: if "content" in dict_message: return dict_message["content"] else: raise ValueError("The message was share classified but no content " + str(dict_message["share"])) elif content_type == ContentType.GIF: return self.__get_nested_uri(dict_message["gifs"]) elif content_type == ContentType.IMAGE: return self.__get_nested_uri(dict_message["photos"]) elif content_type == ContentType.VIDEO: return self.__get_nested_uri(dict_message["videos"]) # Only takes the uri, ignore ts of video and thumbnail elif content_type == ContentType.STICKER: return dict_message["sticker"]["uri"] elif content_type == ContentType.EMPTY: return "Empty" elif content_type == ContentType.CALL: return dict_message["call_duration"] # Returns how long the call was elif content_type == ContentType.SUBSCRIBE: new_users = [] for user in dict_message["users"]: new_users.append(user["name"]) return new_users elif content_type == ContentType.AUDIO: return self.__get_nested_uri(dict_message["audio_files"]) else: raise ValueError("content_type is not known" + str(content_type)) def __get_nested_uri(self, data): entities = [] for entity in data: entities.append(entity["uri"]) # Only takes the uri, ignore possibly other attribues return entities
0.444565
0.218065
import numpy as np from scipy import linalg from pressio4py import logger, solvers, ode, rom np.set_printoptions(linewidth=140) class MyTestApp: def __init__(self, N): self.N_ = N self.callCount_ = 0 def createDiscreteTimeResidual(self): return np.zeros(self.N_) def createApplyDiscreteTimeJacobianResult(self, B): return np.zeros((self.N_, B.shape[1])) def discreteTimeResidual(self, step, time, dt, R, ynp1, yn): self.callCount_ += 1 assert(len(R) == self.N_) assert(len(ynp1) == self.N_) assert(len(yn) == self.N_) if self.callCount_ == 1: ynp1_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(ynp1, ynp1_gold, atol=1e-12) ) yn_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(yn, yn_gold, atol=1e-12) ) if self.callCount_ == 2: ynp1_gold = np.array([6.,12.,18.,24.,30.,36.,42.]) assert( np.allclose(ynp1, ynp1_gold, atol=1e-12) ) yn_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(yn, yn_gold, atol=1e-12) ) R[:] = 1. print("ynp1") print(ynp1) print("yn") print(yn) def applyDiscreteTimeJacobian(self, step, time, dt, B, A, ynp1, yn): A[0,:] = 0. A[1,:] = 2. A[2,:] = 1. A[3,:] = 3. A[4,:] = 2. A[5,:] = 4. A[6,:] = 5. #---------------------------- class MyLinSolver: # recall that this is called from the nonlinear solver # and x is the correction to apply to the nonlinear state def solve(self, A, b, x): print(A) print(b) x[:] = 1. bGold = -np.ones(3)*(17) assert( np.allclose(b, bGold, atol=1e-12) ) hGold = np.ones((3,3))*59. assert( np.allclose(A, hGold, atol=1e-12) ) #---------------------------- def test(): logger.initialize(logger.logto.terminal) logger.setVerbosity([logger.loglevel.info]) Ngrid = 7 romSize = 3 dt = 2. appObj = MyTestApp(Ngrid) yRef = np.zeros(Ngrid) phi = np.zeros((Ngrid, romSize), order='F') for i in range(Ngrid): phi[i,:] = float(i+1) print("\n") print(phi) decoder = rom.Decoder(phi) yRom = np.ones(romSize) problem = rom.lspg.unsteady.DiscreteTimeProblemTwoStates(appObj, decoder, yRom, yRef) lsO = MyLinSolver() nlsO = solvers.create_gauss_newton(problem, yRom, lsO) nlsO.setUpdatingCriterion(solvers.update.Standard) nlsO.setMaxIterations(2) nlsO.setStoppingCriterion(solvers.stop.AfterMaxIters) # solve ode.advance_n_steps(problem, yRom, 0., dt, 1, nlsO) assert( np.allclose(yRom, np.array([2.,2.,2.]), 1e-12) ) logger.finalize()
tests_functional_small/test_rom_lspg_unsteady_discretetime_default_trivialapp_two_states.py
import numpy as np from scipy import linalg from pressio4py import logger, solvers, ode, rom np.set_printoptions(linewidth=140) class MyTestApp: def __init__(self, N): self.N_ = N self.callCount_ = 0 def createDiscreteTimeResidual(self): return np.zeros(self.N_) def createApplyDiscreteTimeJacobianResult(self, B): return np.zeros((self.N_, B.shape[1])) def discreteTimeResidual(self, step, time, dt, R, ynp1, yn): self.callCount_ += 1 assert(len(R) == self.N_) assert(len(ynp1) == self.N_) assert(len(yn) == self.N_) if self.callCount_ == 1: ynp1_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(ynp1, ynp1_gold, atol=1e-12) ) yn_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(yn, yn_gold, atol=1e-12) ) if self.callCount_ == 2: ynp1_gold = np.array([6.,12.,18.,24.,30.,36.,42.]) assert( np.allclose(ynp1, ynp1_gold, atol=1e-12) ) yn_gold = np.array([3.,6.,9.,12.,15.,18.,21.]) assert( np.allclose(yn, yn_gold, atol=1e-12) ) R[:] = 1. print("ynp1") print(ynp1) print("yn") print(yn) def applyDiscreteTimeJacobian(self, step, time, dt, B, A, ynp1, yn): A[0,:] = 0. A[1,:] = 2. A[2,:] = 1. A[3,:] = 3. A[4,:] = 2. A[5,:] = 4. A[6,:] = 5. #---------------------------- class MyLinSolver: # recall that this is called from the nonlinear solver # and x is the correction to apply to the nonlinear state def solve(self, A, b, x): print(A) print(b) x[:] = 1. bGold = -np.ones(3)*(17) assert( np.allclose(b, bGold, atol=1e-12) ) hGold = np.ones((3,3))*59. assert( np.allclose(A, hGold, atol=1e-12) ) #---------------------------- def test(): logger.initialize(logger.logto.terminal) logger.setVerbosity([logger.loglevel.info]) Ngrid = 7 romSize = 3 dt = 2. appObj = MyTestApp(Ngrid) yRef = np.zeros(Ngrid) phi = np.zeros((Ngrid, romSize), order='F') for i in range(Ngrid): phi[i,:] = float(i+1) print("\n") print(phi) decoder = rom.Decoder(phi) yRom = np.ones(romSize) problem = rom.lspg.unsteady.DiscreteTimeProblemTwoStates(appObj, decoder, yRom, yRef) lsO = MyLinSolver() nlsO = solvers.create_gauss_newton(problem, yRom, lsO) nlsO.setUpdatingCriterion(solvers.update.Standard) nlsO.setMaxIterations(2) nlsO.setStoppingCriterion(solvers.stop.AfterMaxIters) # solve ode.advance_n_steps(problem, yRom, 0., dt, 1, nlsO) assert( np.allclose(yRom, np.array([2.,2.,2.]), 1e-12) ) logger.finalize()
0.591015
0.625095
import os import platform import shutil import socket import tempfile import threading import unittest import ipaddr import portpicker import logging from grr.lib import data_store from grr.lib import data_store_test from grr.lib import flags from grr.lib import test_lib from grr.lib import utils from grr.lib.data_stores import http_data_store from grr.lib.data_stores import sqlite_data_store from grr.server.data_server import data_server class StoppableHTTPServer(data_server.ThreadedHTTPServer): """HTTP server that can be stopped.""" STOP = False def serve_forever(self): self.socket.settimeout(1) while not self.STOP: self.handle_request() self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() class MockRequestHandler(data_server.DataServerHandler): """Mock request handler that can stop a server.""" def do_POST(self): # pylint: disable=invalid-name if self.path == "/exit": StoppableHTTPServer.STOP = True return self._EmptyResponse(200) else: return super(MockRequestHandler, self).do_POST() class MockRequestHandler1(MockRequestHandler): pass class MockRequestHandler2(MockRequestHandler): pass STARTED_SERVER = None HTTP_DB = None PORT = None TMP_DIR = tempfile.mkdtemp(dir=(os.environ.get("TEST_TMPDIR") or "/tmp")) CONFIG_OVERRIDER = None def _GetLocalIPAsString(): return utils.ResolveHostnameToIP("localhost", 0) def _StartServers(): global HTTP_DB global STARTED_SERVER logging.info("Using TMP_DIR:" + TMP_DIR) temp_dir_1 = TMP_DIR + "/1" temp_dir_2 = TMP_DIR + "/2" os.mkdir(temp_dir_1) os.mkdir(temp_dir_2) HTTP_DB = [ sqlite_data_store.SqliteDataStore(temp_dir_1), sqlite_data_store.SqliteDataStore(temp_dir_2) ] if ipaddr.IPAddress(_GetLocalIPAsString()).version == 6: af = socket.AF_INET6 else: af = socket.AF_INET STARTED_SERVER = [ threading.Thread( target=data_server.Start, args=(HTTP_DB[0], PORT[0], af, True, StoppableHTTPServer, MockRequestHandler1)), threading.Thread( target=data_server.Start, args=(HTTP_DB[1], PORT[1], af, False, StoppableHTTPServer, MockRequestHandler2)) ] STARTED_SERVER[0].start() STARTED_SERVER[1].start() def _SetConfig(): global CONFIG_OVERRIDER local_ip = _GetLocalIPAsString() if ipaddr.IPAddress(local_ip).version == 6: urn_template = "http://[%s]:%d" else: urn_template = "http://%s:%d" CONFIG_OVERRIDER = test_lib.ConfigOverrider({ "Dataserver.server_list": [ urn_template % (local_ip, PORT[0]), urn_template % (local_ip, PORT[1]) ], "Dataserver.server_username": "root", "Dataserver.server_password": "<PASSWORD>", "Dataserver.client_credentials": ["user:user:rw"], "HTTPDataStore.username": "user", "HTTPDataStore.password": "<PASSWORD>", "Datastore.location": TMP_DIR }) CONFIG_OVERRIDER.Start() def _CloseServers(): # Directly tell both HTTP servers to stop. StoppableHTTPServer.STOP = True def SetupDataStore(): global PORT if PORT: return PORT = [portpicker.PickUnusedPort(), portpicker.PickUnusedPort()] _SetConfig() _StartServers() try: data_store.DB = http_data_store.HTTPDataStore() data_store.DB.Initialize() except http_data_store.HTTPDataStoreError: data_store.DB = None _CloseServers() @unittest.skipUnless(platform.system() == "Linux", "We only expect the datastore to work on Linux") def setUpModule(): SetupDataStore() def tearDownModule(): _CloseServers() CONFIG_OVERRIDER.Stop() class HTTPDataStoreMixin(object): def setUp(self): super(HTTPDataStoreMixin, self).setUp() # These tests change the config so we preserve state. self.config_stubber = test_lib.PreserveConfig() self.config_stubber.Start() def tearDown(self): super(HTTPDataStoreMixin, self).tearDown() self.config_stubber.Stop() def InitDatastore(self): # Make sure that there are no rpc calls in progress. (Some Inithooks # create aff4 objects with sync=False) if data_store.DB: data_store.DB.Flush() # Hard reset of the sqlite directory trees. if HTTP_DB: try: HTTP_DB[0].cache.Flush() shutil.rmtree(HTTP_DB[0].cache.root_path) except (OSError, IOError): pass try: HTTP_DB[1].cache.Flush() shutil.rmtree(HTTP_DB[1].cache.root_path) except (OSError, IOError): pass @unittest.skipUnless(platform.system() == "Linux", "We only expect the datastore to work on Linux") class HTTPDataStoreTest(HTTPDataStoreMixin, data_store_test._DataStoreTest): """Test the remote data store.""" def __init__(self, *args): super(HTTPDataStoreTest, self).__init__(*args) def testDataStoreInit(self): # This just makes sure the datastore can actually initialize. pass def main(args): test_lib.main(args) if __name__ == "__main__": flags.StartMain(main)
grr/lib/data_stores/http_data_store_test.py
import os import platform import shutil import socket import tempfile import threading import unittest import ipaddr import portpicker import logging from grr.lib import data_store from grr.lib import data_store_test from grr.lib import flags from grr.lib import test_lib from grr.lib import utils from grr.lib.data_stores import http_data_store from grr.lib.data_stores import sqlite_data_store from grr.server.data_server import data_server class StoppableHTTPServer(data_server.ThreadedHTTPServer): """HTTP server that can be stopped.""" STOP = False def serve_forever(self): self.socket.settimeout(1) while not self.STOP: self.handle_request() self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() class MockRequestHandler(data_server.DataServerHandler): """Mock request handler that can stop a server.""" def do_POST(self): # pylint: disable=invalid-name if self.path == "/exit": StoppableHTTPServer.STOP = True return self._EmptyResponse(200) else: return super(MockRequestHandler, self).do_POST() class MockRequestHandler1(MockRequestHandler): pass class MockRequestHandler2(MockRequestHandler): pass STARTED_SERVER = None HTTP_DB = None PORT = None TMP_DIR = tempfile.mkdtemp(dir=(os.environ.get("TEST_TMPDIR") or "/tmp")) CONFIG_OVERRIDER = None def _GetLocalIPAsString(): return utils.ResolveHostnameToIP("localhost", 0) def _StartServers(): global HTTP_DB global STARTED_SERVER logging.info("Using TMP_DIR:" + TMP_DIR) temp_dir_1 = TMP_DIR + "/1" temp_dir_2 = TMP_DIR + "/2" os.mkdir(temp_dir_1) os.mkdir(temp_dir_2) HTTP_DB = [ sqlite_data_store.SqliteDataStore(temp_dir_1), sqlite_data_store.SqliteDataStore(temp_dir_2) ] if ipaddr.IPAddress(_GetLocalIPAsString()).version == 6: af = socket.AF_INET6 else: af = socket.AF_INET STARTED_SERVER = [ threading.Thread( target=data_server.Start, args=(HTTP_DB[0], PORT[0], af, True, StoppableHTTPServer, MockRequestHandler1)), threading.Thread( target=data_server.Start, args=(HTTP_DB[1], PORT[1], af, False, StoppableHTTPServer, MockRequestHandler2)) ] STARTED_SERVER[0].start() STARTED_SERVER[1].start() def _SetConfig(): global CONFIG_OVERRIDER local_ip = _GetLocalIPAsString() if ipaddr.IPAddress(local_ip).version == 6: urn_template = "http://[%s]:%d" else: urn_template = "http://%s:%d" CONFIG_OVERRIDER = test_lib.ConfigOverrider({ "Dataserver.server_list": [ urn_template % (local_ip, PORT[0]), urn_template % (local_ip, PORT[1]) ], "Dataserver.server_username": "root", "Dataserver.server_password": "<PASSWORD>", "Dataserver.client_credentials": ["user:user:rw"], "HTTPDataStore.username": "user", "HTTPDataStore.password": "<PASSWORD>", "Datastore.location": TMP_DIR }) CONFIG_OVERRIDER.Start() def _CloseServers(): # Directly tell both HTTP servers to stop. StoppableHTTPServer.STOP = True def SetupDataStore(): global PORT if PORT: return PORT = [portpicker.PickUnusedPort(), portpicker.PickUnusedPort()] _SetConfig() _StartServers() try: data_store.DB = http_data_store.HTTPDataStore() data_store.DB.Initialize() except http_data_store.HTTPDataStoreError: data_store.DB = None _CloseServers() @unittest.skipUnless(platform.system() == "Linux", "We only expect the datastore to work on Linux") def setUpModule(): SetupDataStore() def tearDownModule(): _CloseServers() CONFIG_OVERRIDER.Stop() class HTTPDataStoreMixin(object): def setUp(self): super(HTTPDataStoreMixin, self).setUp() # These tests change the config so we preserve state. self.config_stubber = test_lib.PreserveConfig() self.config_stubber.Start() def tearDown(self): super(HTTPDataStoreMixin, self).tearDown() self.config_stubber.Stop() def InitDatastore(self): # Make sure that there are no rpc calls in progress. (Some Inithooks # create aff4 objects with sync=False) if data_store.DB: data_store.DB.Flush() # Hard reset of the sqlite directory trees. if HTTP_DB: try: HTTP_DB[0].cache.Flush() shutil.rmtree(HTTP_DB[0].cache.root_path) except (OSError, IOError): pass try: HTTP_DB[1].cache.Flush() shutil.rmtree(HTTP_DB[1].cache.root_path) except (OSError, IOError): pass @unittest.skipUnless(platform.system() == "Linux", "We only expect the datastore to work on Linux") class HTTPDataStoreTest(HTTPDataStoreMixin, data_store_test._DataStoreTest): """Test the remote data store.""" def __init__(self, *args): super(HTTPDataStoreTest, self).__init__(*args) def testDataStoreInit(self): # This just makes sure the datastore can actually initialize. pass def main(args): test_lib.main(args) if __name__ == "__main__": flags.StartMain(main)
0.423339
0.109753
from PyQt5.QtWidgets import QLabel import constants def get_label(text): temp_label = QLabel(text) if 'LEC' in text: temp_label.setStyleSheet("background-color: lightskyblue; font-family: Arial; font-size: 22px") elif 'TUT' in text: temp_label.setStyleSheet("background-color: springgreen; font-family: Arial; font-size: 22px") elif 'LAB' in text: temp_label.setStyleSheet("background-color: salmon; font-family: Arial; font-size: 22px") else: temp_label.setStyleSheet("background-color: lightcoral; font-family: Arial; font-size: 22px") return temp_label class PlannerMgr: def __init__(self, planner_table): self.__planner_table = planner_table # Attempt to plan the semester based on the selected modules and indexes def update(self, modules_list, index_node_list): self.__planner_table.clearContents() # Plan the lecture first as they are the more important one as they dont change based on index self.plan_lecture(modules_list, index_node_list) # Attempt to plan the lecture to planner table def plan_lecture(self, modules_list, index_node_list): # Loop through the length of modules_list for i in range(len(modules_list)): # Get the course code from modules list course_code = modules_list[i].split(':')[0] # Loop through the info that an "indexed" index_node for info in index_node_list[i].info: # Get the info start and end time start_time = info['TIME'].split('-')[0] end_time = info['TIME'].split('-')[1] # Translate start and end time to start and end time index start_time_index, end_time_index = constants.get_time_range(start_time, end_time) # Translate the day to day index day_index = constants.get_day_index(info['DAY']) self.update_table(day_index, start_time_index, end_time_index, info, course_code) # Update the planner table def update_table(self, day_index, start_time_range, end_time_range, info, course_code): for row in range(start_time_range, end_time_range): if info['TYPE'] == 'LAB': if info['REMARK'] == 'Teaching Wk1,3,5,7,9,11,13': self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: Odd {info["TYPE"]}')) elif info['REMARK'] == 'Teaching Wk2,4,6,8,10,12': self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: Even {info["TYPE"]}')) else: self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: All {info["TYPE"]}')) else: self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: {info["TYPE"]}'))
src/plannerMgr.py
from PyQt5.QtWidgets import QLabel import constants def get_label(text): temp_label = QLabel(text) if 'LEC' in text: temp_label.setStyleSheet("background-color: lightskyblue; font-family: Arial; font-size: 22px") elif 'TUT' in text: temp_label.setStyleSheet("background-color: springgreen; font-family: Arial; font-size: 22px") elif 'LAB' in text: temp_label.setStyleSheet("background-color: salmon; font-family: Arial; font-size: 22px") else: temp_label.setStyleSheet("background-color: lightcoral; font-family: Arial; font-size: 22px") return temp_label class PlannerMgr: def __init__(self, planner_table): self.__planner_table = planner_table # Attempt to plan the semester based on the selected modules and indexes def update(self, modules_list, index_node_list): self.__planner_table.clearContents() # Plan the lecture first as they are the more important one as they dont change based on index self.plan_lecture(modules_list, index_node_list) # Attempt to plan the lecture to planner table def plan_lecture(self, modules_list, index_node_list): # Loop through the length of modules_list for i in range(len(modules_list)): # Get the course code from modules list course_code = modules_list[i].split(':')[0] # Loop through the info that an "indexed" index_node for info in index_node_list[i].info: # Get the info start and end time start_time = info['TIME'].split('-')[0] end_time = info['TIME'].split('-')[1] # Translate start and end time to start and end time index start_time_index, end_time_index = constants.get_time_range(start_time, end_time) # Translate the day to day index day_index = constants.get_day_index(info['DAY']) self.update_table(day_index, start_time_index, end_time_index, info, course_code) # Update the planner table def update_table(self, day_index, start_time_range, end_time_range, info, course_code): for row in range(start_time_range, end_time_range): if info['TYPE'] == 'LAB': if info['REMARK'] == 'Teaching Wk1,3,5,7,9,11,13': self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: Odd {info["TYPE"]}')) elif info['REMARK'] == 'Teaching Wk2,4,6,8,10,12': self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: Even {info["TYPE"]}')) else: self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: All {info["TYPE"]}')) else: self.__planner_table.setCellWidget(row, day_index, get_label(f'{course_code}: {info["TYPE"]}'))
0.347869
0.221898
from flask import Flask import flask import os import base64 import markdown from markupsafe import Markup import json app = Flask(__name__) app.config.from_pyfile('settings.py') blogs = [] with open('data/data.json', 'r') as f: placeholder = (json.load(f)) for item in placeholder: blogs.append({'title':item['title'], 'content':item['content']}) @app.route('/') def index(): CurrentPage = 0 Length = len(blogs) tempBlogs = [] if len(blogs) > 4: for i in range(0,5): tempBlogs.append(blogs[i]) else: tempBlogs = blogs if 'csrf_token' not in flask.session: flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii') auth_user = flask.session.get('auth_user', None) resp = flask.make_response(flask.render_template('index.html', auth_user=auth_user, csrf_token=flask.session['csrf_token'],Length = Length, CurrentPage = CurrentPage, blogs = tempBlogs)) return resp @app.route('/<int:pageNum>') def page_Handler(pageNum): if 'csrf_token' not in flask.session: flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii') auth_user = flask.session.get('auth_user', None) tempBlogs = [] max = 0 if (pageNum + 5) < len(blogs): max = pageNum + 5 else: max = len(blogs) for i in range(pageNum,max): tempBlogs.append(blogs[i]) Length = len(blogs) resp = flask.make_response(flask.render_template('index.html', auth_user=auth_user, csrf_token=flask.session['csrf_token'], check=1, blogs = tempBlogs, CurrentPage = pageNum, Length = Length)) return resp @app.route('/login', methods=['POST']) def handle_login(): # POST request to /login - check user user = flask.request.form['user'] password = flask.request.form['password'] if user == 'admin' and password == app.config['ADMIN_PASSWORD']: # User is good! Save in the session flask.session['auth_user'] = user # And redirect to '/', since this is a successful POST return flask.redirect('/', 303) else: # For an error in POST, we'll just re-show the form with an error message return flask.render_template('index.html', state='bad', CurrentPage = 0, Length = len(blogs)) @app.route('/logout') def handle_logout(): # user wants to say goodbye, just forget about them del flask.session['auth_user'] return flask.redirect('/') @app.errorhandler(404) def not_found(err): return (flask.render_template('404.html', path=flask.request.path), 404) @app.route('/addBlogButton') def add_Blog(): return flask.render_template('addBlog.html', auth_user=flask.session.get('auth_user', None),csrf_token=flask.session['csrf_token']) @app.route('/addBlog', methods=['POST']) def add_Blog_Handle(): if 'auth_user' not in flask.session: app.logger.warn('unauthorized user tried to add blog') flask.abort(401) if flask.request.form['_csrf_token'] != flask.session['csrf_token']: app.logger.debug('invalid CSRF token in blog form') flask.abort(400) title = flask.request.form['title'] if title == "": title = "None" content = flask.request.form['content'] if content == "": return flask.render_template('addBlog.html',csrf_token=flask.session['csrf_token'], check = 0) blogs.append({'title':title,'content':content}) with open('data/data.json', 'w') as f: json.dump(blogs, f) return flask.redirect(flask.url_for('posts', pid=len(blogs) - 1), code=303) @app.route('/posts/<int:pid>') def posts(pid): tempPost = blogs[pid] content = Markup(markdown.markdown(tempPost['content'], output_format='html5')) return flask.render_template('posts.html', tempPost = tempPost, content = content ,pid = pid, csrf_token=flask.session['csrf_token']) @app.route('/removeBlog',methods = ['POST']) def remove_Blog_Handle(): if 'auth_user' not in flask.session: app.logger.warn('unauthorized user tried to add animal') flask.abort(401) if flask.request.form['_csrf_token'] != flask.session['csrf_token']: app.logger.debug('invalid CSRF token in blog form') flask.abort(400) id = int(flask.request.form['id']) blogs.remove(blogs[id]) with open('data/data.json', 'w') as f: json.dump(blogs, f) return flask.redirect(flask.url_for('index')) if __name__ == '__main__': app.run(debug = True)
A3.py
from flask import Flask import flask import os import base64 import markdown from markupsafe import Markup import json app = Flask(__name__) app.config.from_pyfile('settings.py') blogs = [] with open('data/data.json', 'r') as f: placeholder = (json.load(f)) for item in placeholder: blogs.append({'title':item['title'], 'content':item['content']}) @app.route('/') def index(): CurrentPage = 0 Length = len(blogs) tempBlogs = [] if len(blogs) > 4: for i in range(0,5): tempBlogs.append(blogs[i]) else: tempBlogs = blogs if 'csrf_token' not in flask.session: flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii') auth_user = flask.session.get('auth_user', None) resp = flask.make_response(flask.render_template('index.html', auth_user=auth_user, csrf_token=flask.session['csrf_token'],Length = Length, CurrentPage = CurrentPage, blogs = tempBlogs)) return resp @app.route('/<int:pageNum>') def page_Handler(pageNum): if 'csrf_token' not in flask.session: flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii') auth_user = flask.session.get('auth_user', None) tempBlogs = [] max = 0 if (pageNum + 5) < len(blogs): max = pageNum + 5 else: max = len(blogs) for i in range(pageNum,max): tempBlogs.append(blogs[i]) Length = len(blogs) resp = flask.make_response(flask.render_template('index.html', auth_user=auth_user, csrf_token=flask.session['csrf_token'], check=1, blogs = tempBlogs, CurrentPage = pageNum, Length = Length)) return resp @app.route('/login', methods=['POST']) def handle_login(): # POST request to /login - check user user = flask.request.form['user'] password = flask.request.form['password'] if user == 'admin' and password == app.config['ADMIN_PASSWORD']: # User is good! Save in the session flask.session['auth_user'] = user # And redirect to '/', since this is a successful POST return flask.redirect('/', 303) else: # For an error in POST, we'll just re-show the form with an error message return flask.render_template('index.html', state='bad', CurrentPage = 0, Length = len(blogs)) @app.route('/logout') def handle_logout(): # user wants to say goodbye, just forget about them del flask.session['auth_user'] return flask.redirect('/') @app.errorhandler(404) def not_found(err): return (flask.render_template('404.html', path=flask.request.path), 404) @app.route('/addBlogButton') def add_Blog(): return flask.render_template('addBlog.html', auth_user=flask.session.get('auth_user', None),csrf_token=flask.session['csrf_token']) @app.route('/addBlog', methods=['POST']) def add_Blog_Handle(): if 'auth_user' not in flask.session: app.logger.warn('unauthorized user tried to add blog') flask.abort(401) if flask.request.form['_csrf_token'] != flask.session['csrf_token']: app.logger.debug('invalid CSRF token in blog form') flask.abort(400) title = flask.request.form['title'] if title == "": title = "None" content = flask.request.form['content'] if content == "": return flask.render_template('addBlog.html',csrf_token=flask.session['csrf_token'], check = 0) blogs.append({'title':title,'content':content}) with open('data/data.json', 'w') as f: json.dump(blogs, f) return flask.redirect(flask.url_for('posts', pid=len(blogs) - 1), code=303) @app.route('/posts/<int:pid>') def posts(pid): tempPost = blogs[pid] content = Markup(markdown.markdown(tempPost['content'], output_format='html5')) return flask.render_template('posts.html', tempPost = tempPost, content = content ,pid = pid, csrf_token=flask.session['csrf_token']) @app.route('/removeBlog',methods = ['POST']) def remove_Blog_Handle(): if 'auth_user' not in flask.session: app.logger.warn('unauthorized user tried to add animal') flask.abort(401) if flask.request.form['_csrf_token'] != flask.session['csrf_token']: app.logger.debug('invalid CSRF token in blog form') flask.abort(400) id = int(flask.request.form['id']) blogs.remove(blogs[id]) with open('data/data.json', 'w') as f: json.dump(blogs, f) return flask.redirect(flask.url_for('index')) if __name__ == '__main__': app.run(debug = True)
0.228931
0.077692
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester process = cms.Process("emdqm") process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff') process.GlobalTag.globaltag = 'START72_V1::All' process.load("FWCore.MessageService.MessageLogger_cfi") # suppress printout of error messages on every event when a collection is missing in the event process.MessageLogger.cerr.EmDQMInvalidRefs = cms.untracked.PSet(limit = cms.untracked.int32(5)) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) #process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(2) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( 'file:../../../HLTrigger/Configuration/test/outputAForPP.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValH130GGgluonfusion_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/C87CDC3A-B1D0-E311-8890-02163E00E6DE.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValWE_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/665BE840-B4D0-E311-BBA6-02163E00E694.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValPhotonJets_Pt_10_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/C0AB31B9-A2D0-E311-A15D-02163E00E725.root', ) ) process.load("HLTriggerOffline.Egamma.EgammaValidationAutoConf_cff") # set output to verbose = all process.emdqm.verbosity = cms.untracked.uint32(3) # switch to select between only MC matched histograms or all histograms process.emdqm.mcMatchedOnly = cms.untracked.bool(False) # switch for phi plots process.emdqm.noPhiPlots = cms.untracked.bool(False) # switch for 2D isolation plots process.emdqm.noIsolationPlots = cms.untracked.bool(False) # which trigger object and process should we run on? #process.emdqm.triggerobject = cms.InputTag("hltTriggerSummaryRAW","","HLTTEST") process.p = cms.Path( # require generated particles in fiducial volume process.egammaSelectors * process.egammaValidationSequence ) #---------------------------------------- process.post=DQMEDHarvester("EmDQMPostProcessor", subDir = cms.untracked.string("HLT/HLTEgammaValidation"), dataSet = cms.untracked.string("unknown"), noPhiPlots = cms.untracked.bool(False), ignoreEmpty = cms.untracked.bool(False), ) #process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True)) #---------------------------------------- # DQM service #---------------------------------------- process.load("DQMServices.Core.DQM_cfg") process.load("DQMServices.Components.DQMEnvironment_cfi") process.dqmSaver.convention = 'Offline' process.dqmSaver.workflow = '/RelVal/HLTriggerOffline/Egamma' process.dqmSaver.saveByRun = cms.untracked.int32(-1) process.dqmSaver.saveAtJobEnd = cms.untracked.bool(True) process.ppost = cms.EndPath(process.post+process.dqmSaver) #---------------------------------------- # End of original testEmDQM_cfg.py #----------------------------------------
HLTriggerOffline/Egamma/test/testEmDQM_cfg.py
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester process = cms.Process("emdqm") process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff') process.GlobalTag.globaltag = 'START72_V1::All' process.load("FWCore.MessageService.MessageLogger_cfi") # suppress printout of error messages on every event when a collection is missing in the event process.MessageLogger.cerr.EmDQMInvalidRefs = cms.untracked.PSet(limit = cms.untracked.int32(5)) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) #process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(2) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( 'file:../../../HLTrigger/Configuration/test/outputAForPP.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValH130GGgluonfusion_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/C87CDC3A-B1D0-E311-8890-02163E00E6DE.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValWE_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/665BE840-B4D0-E311-BBA6-02163E00E694.root', # '/store/relval/CMSSW_7_1_0_pre7/RelValPhotonJets_Pt_10_13/GEN-SIM-DIGI-RAW-HLTDEBUG/PRE_LS171_V7-v1/00000/C0AB31B9-A2D0-E311-A15D-02163E00E725.root', ) ) process.load("HLTriggerOffline.Egamma.EgammaValidationAutoConf_cff") # set output to verbose = all process.emdqm.verbosity = cms.untracked.uint32(3) # switch to select between only MC matched histograms or all histograms process.emdqm.mcMatchedOnly = cms.untracked.bool(False) # switch for phi plots process.emdqm.noPhiPlots = cms.untracked.bool(False) # switch for 2D isolation plots process.emdqm.noIsolationPlots = cms.untracked.bool(False) # which trigger object and process should we run on? #process.emdqm.triggerobject = cms.InputTag("hltTriggerSummaryRAW","","HLTTEST") process.p = cms.Path( # require generated particles in fiducial volume process.egammaSelectors * process.egammaValidationSequence ) #---------------------------------------- process.post=DQMEDHarvester("EmDQMPostProcessor", subDir = cms.untracked.string("HLT/HLTEgammaValidation"), dataSet = cms.untracked.string("unknown"), noPhiPlots = cms.untracked.bool(False), ignoreEmpty = cms.untracked.bool(False), ) #process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True)) #---------------------------------------- # DQM service #---------------------------------------- process.load("DQMServices.Core.DQM_cfg") process.load("DQMServices.Components.DQMEnvironment_cfi") process.dqmSaver.convention = 'Offline' process.dqmSaver.workflow = '/RelVal/HLTriggerOffline/Egamma' process.dqmSaver.saveByRun = cms.untracked.int32(-1) process.dqmSaver.saveAtJobEnd = cms.untracked.bool(True) process.ppost = cms.EndPath(process.post+process.dqmSaver) #---------------------------------------- # End of original testEmDQM_cfg.py #----------------------------------------
0.276105
0.10004
from standard_wallet.wallet import Wallet import clvm from chiasim.hashable import CoinSolution, Program, ProgramHash, SpendBundle from clvm_tools import binutils from chiasim.validation.Conditions import ConditionOpcode from utilities.puzzle_utilities import puzzlehash_from_string from utilities.keys import signature_for_solution, sign_f_for_keychain def build_spend_bundle(coin, solution, sign_f): coin_solution = CoinSolution(coin, solution) signature = signature_for_solution(solution, sign_f) return SpendBundle([coin_solution], signature) from puzzles.p2_delegated_puzzle import puzzle_for_pk # ASWallet is subclass of Wallet class ASWallet(Wallet): def __init__(self): self.as_pending_utxos = set() self.overlook = [] self.as_swap_list = [] super().__init__() return def notify(self, additions, deletions): super().notify(additions, deletions) puzzlehashes = [] for swap in self.as_swap_list: puzzlehashes.append(swap["outgoing puzzlehash"]) puzzlehashes.append(swap["incoming puzzlehash"]) if puzzlehashes != []: self.as_notify(additions, puzzlehashes) def as_notify(self, additions, puzzlehashes): for coin in additions: for puzzlehash in puzzlehashes: if coin.puzzle_hash.hex() == puzzlehash and coin.puzzle_hash not in self.overlook: self.as_pending_utxos.add(coin) self.overlook.append(coin.puzzle_hash) # finds a pending atomic swap coin to be spent def as_select_coins(self, amount, as_puzzlehash): if amount > self.current_balance or amount < 0: return None used_utxos = set() if isinstance(as_puzzlehash, str): as_puzzlehash = puzzlehash_from_string(as_puzzlehash) coins = self.my_utxos.copy() for pcoin in self.as_pending_utxos: coins.add(pcoin) for coin in coins: if coin.puzzle_hash == as_puzzlehash: used_utxos.add(coin) return used_utxos # generates the hash of the secret used for the atomic swap coin hashlocks def as_generate_secret_hash(self, secret): secret_hash_cl = f"(sha256 (q {secret}))" sec = f"({secret})" cost, secret_hash_preformat = clvm.run_program(binutils.assemble("(sha256 (f (a)))"), binutils.assemble(sec)) secret_hash = binutils.disassemble(secret_hash_preformat) return secret_hash def as_make_puzzle(self, as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash): as_pubkey_sender_cl = f"0x{as_pubkey_sender.hex()}" as_pubkey_receiver_cl = f"0x{as_pubkey_receiver.hex()}" as_payout_puzzlehash_receiver = ProgramHash(puzzle_for_pk(as_pubkey_receiver)) as_payout_puzzlehash_sender = ProgramHash(puzzle_for_pk(as_pubkey_sender)) payout_receiver = f"(c (q 0x{ConditionOpcode.CREATE_COIN.hex()}) (c (q 0x{as_payout_puzzlehash_receiver.hex()}) (c (q {as_amount}) (q ()))))" payout_sender = f"(c (q 0x{ConditionOpcode.CREATE_COIN.hex()}) (c (q 0x{as_payout_puzzlehash_sender.hex()}) (c (q {as_amount}) (q ()))))" aggsig_receiver = f"(c (q 0x{ConditionOpcode.AGG_SIG.hex()}) (c (q {as_pubkey_receiver_cl}) (c (sha256tree (a)) (q ()))))" aggsig_sender = f"(c (q 0x{ConditionOpcode.AGG_SIG.hex()}) (c (q {as_pubkey_sender_cl}) (c (sha256tree (a)) (q ()))))" receiver_puz = (f"((c (i (= (sha256 (f (r (a)))) (q {as_secret_hash})) (q (c " + aggsig_receiver + " (c " + payout_receiver + " (q ())))) (q (x (q 'invalid secret')))) (a))) ) ") timelock = f"(c (q 0x{ConditionOpcode.ASSERT_BLOCK_INDEX_EXCEEDS.hex()}) (c (q {as_timelock_block}) (q ()))) " sender_puz = "(c " + aggsig_sender + " (c " + timelock + " (c " + payout_sender + " (q ()))))" as_puz_sender = "((c (i (= (f (a)) (q 77777)) (q " + sender_puz + ") (q (x (q 'not a valid option'))) ) (a)))" as_puz = "((c (i (= (f (a)) (q 33333)) (q " + receiver_puz + " (q " + as_puz_sender + ")) (a)))" return Program(binutils.assemble(as_puz)) def as_get_new_puzzlehash(self, as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash): as_puz = self.as_make_puzzle(as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash) as_puzzlehash = ProgramHash(as_puz) return as_puzzlehash # 33333 is the receiver solution code prefix def as_make_solution_receiver(self, as_sec_to_try): sol = "(33333 " sol += f"{as_sec_to_try}" sol += ")" return Program(binutils.assemble(sol)) # 77777 is the sender solution code prefix def as_make_solution_sender(self): sol = "(77777 " sol += ")" return Program(binutils.assemble(sol)) # finds the secret used to spend a swap coin so that it can be used to spend the swap's other coin def pull_preimage(self, body, removals): for coin in removals: for swap in self.as_swap_list: if coin.puzzle_hash.hex() == swap["outgoing puzzlehash"]: l = [(puzzle_hash, puzzle_solution_program) for (puzzle_hash, puzzle_solution_program) in self.as_solution_list(body.solution_program)] for x in l: if x[0].hex() == coin.puzzle_hash.hex(): pre1 = binutils.disassemble(x[1]) preimage = pre1[(len(pre1) - 515):(len(pre1) - 3)] swap["secret"] = preimage # returns a list of tuples of the form (coin_name, puzzle_hash, conditions_dict, puzzle_solution_program) def as_solution_list(self, body_program): try: cost, sexp = clvm.run_program(body_program, []) except clvm.EvalError.EvalError: raise ValueError(body_program) npc_list = [] for name_solution in sexp.as_iter(): _ = name_solution.as_python() if len(_) != 2: raise ValueError(name_solution) if not isinstance(_[0], bytes) or len(_[0]) != 32: raise ValueError(name_solution) if not isinstance(_[1], list) or len(_[1]) != 2: raise ValueError(name_solution) puzzle_solution_program = name_solution.rest().first() puzzle_program = puzzle_solution_program.first() puzzle_hash = ProgramHash(Program(puzzle_program)) npc_list.append((puzzle_hash, puzzle_solution_program)) return npc_list def get_private_keys(self): return [self.extended_secret_key.private_child(child) for child in range(self.next_address)] def make_keychain(self): private_keys = self.get_private_keys() return dict((_.public_key(), _) for _ in private_keys) def make_signer(self): return sign_f_for_keychain(self.make_keychain()) def as_create_spend_bundle(self, as_puzzlehash, as_amount, as_timelock_block, as_secret_hash, as_pubkey_sender = None, as_pubkey_receiver = None, who = None, as_sec_to_try = None): utxos = self.as_select_coins(as_amount, as_puzzlehash) spends = [] for coin in utxos: puzzle = self.as_make_puzzle(as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash) if who == "sender": solution = self.as_make_solution_sender() elif who == "receiver": solution = self.as_make_solution_receiver(as_sec_to_try) pair = solution.to([puzzle, solution]) signer = self.make_signer() spend_bundle = build_spend_bundle(coin, Program(pair), sign_f=signer) spends.append(spend_bundle) return SpendBundle.aggregate(spends) def as_remove_swap_instances(self, removals): for coin in removals: pcoins = self.as_pending_utxos.copy() for pcoin in pcoins: if coin.puzzle_hash == pcoin.puzzle_hash: self.as_pending_utxos.remove(pcoin) for swap in self.as_swap_list: if coin.puzzle_hash.hex() == swap["outgoing puzzlehash"]: swap["outgoing puzzlehash"] = "spent" if swap["outgoing puzzlehash"] == "spent" and swap["incoming puzzlehash"] == "spent": self.as_swap_list.remove(swap) if coin.puzzle_hash.hex() == swap["incoming puzzlehash"]: swap["incoming puzzlehash"] = "spent" if swap["outgoing puzzlehash"] == "spent" and swap["incoming puzzlehash"] == "spent": self.as_swap_list.remove(swap) """ Copyright 2018 Chia Network Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """
atomic_swaps/as_wallet.py
from standard_wallet.wallet import Wallet import clvm from chiasim.hashable import CoinSolution, Program, ProgramHash, SpendBundle from clvm_tools import binutils from chiasim.validation.Conditions import ConditionOpcode from utilities.puzzle_utilities import puzzlehash_from_string from utilities.keys import signature_for_solution, sign_f_for_keychain def build_spend_bundle(coin, solution, sign_f): coin_solution = CoinSolution(coin, solution) signature = signature_for_solution(solution, sign_f) return SpendBundle([coin_solution], signature) from puzzles.p2_delegated_puzzle import puzzle_for_pk # ASWallet is subclass of Wallet class ASWallet(Wallet): def __init__(self): self.as_pending_utxos = set() self.overlook = [] self.as_swap_list = [] super().__init__() return def notify(self, additions, deletions): super().notify(additions, deletions) puzzlehashes = [] for swap in self.as_swap_list: puzzlehashes.append(swap["outgoing puzzlehash"]) puzzlehashes.append(swap["incoming puzzlehash"]) if puzzlehashes != []: self.as_notify(additions, puzzlehashes) def as_notify(self, additions, puzzlehashes): for coin in additions: for puzzlehash in puzzlehashes: if coin.puzzle_hash.hex() == puzzlehash and coin.puzzle_hash not in self.overlook: self.as_pending_utxos.add(coin) self.overlook.append(coin.puzzle_hash) # finds a pending atomic swap coin to be spent def as_select_coins(self, amount, as_puzzlehash): if amount > self.current_balance or amount < 0: return None used_utxos = set() if isinstance(as_puzzlehash, str): as_puzzlehash = puzzlehash_from_string(as_puzzlehash) coins = self.my_utxos.copy() for pcoin in self.as_pending_utxos: coins.add(pcoin) for coin in coins: if coin.puzzle_hash == as_puzzlehash: used_utxos.add(coin) return used_utxos # generates the hash of the secret used for the atomic swap coin hashlocks def as_generate_secret_hash(self, secret): secret_hash_cl = f"(sha256 (q {secret}))" sec = f"({secret})" cost, secret_hash_preformat = clvm.run_program(binutils.assemble("(sha256 (f (a)))"), binutils.assemble(sec)) secret_hash = binutils.disassemble(secret_hash_preformat) return secret_hash def as_make_puzzle(self, as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash): as_pubkey_sender_cl = f"0x{as_pubkey_sender.hex()}" as_pubkey_receiver_cl = f"0x{as_pubkey_receiver.hex()}" as_payout_puzzlehash_receiver = ProgramHash(puzzle_for_pk(as_pubkey_receiver)) as_payout_puzzlehash_sender = ProgramHash(puzzle_for_pk(as_pubkey_sender)) payout_receiver = f"(c (q 0x{ConditionOpcode.CREATE_COIN.hex()}) (c (q 0x{as_payout_puzzlehash_receiver.hex()}) (c (q {as_amount}) (q ()))))" payout_sender = f"(c (q 0x{ConditionOpcode.CREATE_COIN.hex()}) (c (q 0x{as_payout_puzzlehash_sender.hex()}) (c (q {as_amount}) (q ()))))" aggsig_receiver = f"(c (q 0x{ConditionOpcode.AGG_SIG.hex()}) (c (q {as_pubkey_receiver_cl}) (c (sha256tree (a)) (q ()))))" aggsig_sender = f"(c (q 0x{ConditionOpcode.AGG_SIG.hex()}) (c (q {as_pubkey_sender_cl}) (c (sha256tree (a)) (q ()))))" receiver_puz = (f"((c (i (= (sha256 (f (r (a)))) (q {as_secret_hash})) (q (c " + aggsig_receiver + " (c " + payout_receiver + " (q ())))) (q (x (q 'invalid secret')))) (a))) ) ") timelock = f"(c (q 0x{ConditionOpcode.ASSERT_BLOCK_INDEX_EXCEEDS.hex()}) (c (q {as_timelock_block}) (q ()))) " sender_puz = "(c " + aggsig_sender + " (c " + timelock + " (c " + payout_sender + " (q ()))))" as_puz_sender = "((c (i (= (f (a)) (q 77777)) (q " + sender_puz + ") (q (x (q 'not a valid option'))) ) (a)))" as_puz = "((c (i (= (f (a)) (q 33333)) (q " + receiver_puz + " (q " + as_puz_sender + ")) (a)))" return Program(binutils.assemble(as_puz)) def as_get_new_puzzlehash(self, as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash): as_puz = self.as_make_puzzle(as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash) as_puzzlehash = ProgramHash(as_puz) return as_puzzlehash # 33333 is the receiver solution code prefix def as_make_solution_receiver(self, as_sec_to_try): sol = "(33333 " sol += f"{as_sec_to_try}" sol += ")" return Program(binutils.assemble(sol)) # 77777 is the sender solution code prefix def as_make_solution_sender(self): sol = "(77777 " sol += ")" return Program(binutils.assemble(sol)) # finds the secret used to spend a swap coin so that it can be used to spend the swap's other coin def pull_preimage(self, body, removals): for coin in removals: for swap in self.as_swap_list: if coin.puzzle_hash.hex() == swap["outgoing puzzlehash"]: l = [(puzzle_hash, puzzle_solution_program) for (puzzle_hash, puzzle_solution_program) in self.as_solution_list(body.solution_program)] for x in l: if x[0].hex() == coin.puzzle_hash.hex(): pre1 = binutils.disassemble(x[1]) preimage = pre1[(len(pre1) - 515):(len(pre1) - 3)] swap["secret"] = preimage # returns a list of tuples of the form (coin_name, puzzle_hash, conditions_dict, puzzle_solution_program) def as_solution_list(self, body_program): try: cost, sexp = clvm.run_program(body_program, []) except clvm.EvalError.EvalError: raise ValueError(body_program) npc_list = [] for name_solution in sexp.as_iter(): _ = name_solution.as_python() if len(_) != 2: raise ValueError(name_solution) if not isinstance(_[0], bytes) or len(_[0]) != 32: raise ValueError(name_solution) if not isinstance(_[1], list) or len(_[1]) != 2: raise ValueError(name_solution) puzzle_solution_program = name_solution.rest().first() puzzle_program = puzzle_solution_program.first() puzzle_hash = ProgramHash(Program(puzzle_program)) npc_list.append((puzzle_hash, puzzle_solution_program)) return npc_list def get_private_keys(self): return [self.extended_secret_key.private_child(child) for child in range(self.next_address)] def make_keychain(self): private_keys = self.get_private_keys() return dict((_.public_key(), _) for _ in private_keys) def make_signer(self): return sign_f_for_keychain(self.make_keychain()) def as_create_spend_bundle(self, as_puzzlehash, as_amount, as_timelock_block, as_secret_hash, as_pubkey_sender = None, as_pubkey_receiver = None, who = None, as_sec_to_try = None): utxos = self.as_select_coins(as_amount, as_puzzlehash) spends = [] for coin in utxos: puzzle = self.as_make_puzzle(as_pubkey_sender, as_pubkey_receiver, as_amount, as_timelock_block, as_secret_hash) if who == "sender": solution = self.as_make_solution_sender() elif who == "receiver": solution = self.as_make_solution_receiver(as_sec_to_try) pair = solution.to([puzzle, solution]) signer = self.make_signer() spend_bundle = build_spend_bundle(coin, Program(pair), sign_f=signer) spends.append(spend_bundle) return SpendBundle.aggregate(spends) def as_remove_swap_instances(self, removals): for coin in removals: pcoins = self.as_pending_utxos.copy() for pcoin in pcoins: if coin.puzzle_hash == pcoin.puzzle_hash: self.as_pending_utxos.remove(pcoin) for swap in self.as_swap_list: if coin.puzzle_hash.hex() == swap["outgoing puzzlehash"]: swap["outgoing puzzlehash"] = "spent" if swap["outgoing puzzlehash"] == "spent" and swap["incoming puzzlehash"] == "spent": self.as_swap_list.remove(swap) if coin.puzzle_hash.hex() == swap["incoming puzzlehash"]: swap["incoming puzzlehash"] = "spent" if swap["outgoing puzzlehash"] == "spent" and swap["incoming puzzlehash"] == "spent": self.as_swap_list.remove(swap) """ Copyright 2018 Chia Network Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """
0.562898
0.250947
import webapp2 import jinja2 from webapp2_extras import auth, sessions # jinja environment jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader('static/templates')) def user_required(handler): """ decorator that checks if the user exist """ def check_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri_for('login'), abort=True) else: return handler(self, *args, **kwargs) return check_login def admin_required(handler): """ decorator that checks if the admin exist """ def admin_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect('/auth/login', abort=True) user = auth.get_user_by_session() if user and user['user_id'] == 5069036098420736: return handler(self, *args, **kwargs) else: self.redirect('/', abort = True) return admin_login # Basehandler class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """ shortcut to access the auth instance """ return auth.get_auth() @webapp2.cached_property def user_info(self): """ shortcut to access a subset of the user attributes """ return self.auth.get_user_by_session() @webapp2.cached_property def user(self): """ shortcut to the current logged in user """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None @webapp2.cached_property def user_model(self): """ return the implementation """ return self.auth.store.user_model @webapp2.cached_property def session(self): """ shortcut """ if not self._backend_name: self._backend_name = 'memcache' return self.session_store.get_session(name = self._session_name, backend = self._backend_name) def set_session(self, arg_session_name = None, arg_backend_name = 'memcache'): self._session_name = arg_session_name self._backend_name = arg_backend_name def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user template = jinja_environment.get_template(view_filename) self.response.out.write(template.render(params)) def display_message(self, message): """ utility function to display a template with a simple message """ params = { 'message' : message } self.render_template('/auth/message.html', params) # this is needed for webapp2 session to work def dispatch(self): # get a session store for this request self.session_store = sessions.get_store(request=self.request) try: # dispatch the request webapp2.RequestHandler.dispatch(self) finally: # save all session self.session_store.save_sessions(self.response) # get user' info def get_user_info(self): return self.auth.get_user_by_session()
prjGogisticsWINEVER/src/handlers/handler_webapp2_extra_auth.py
import webapp2 import jinja2 from webapp2_extras import auth, sessions # jinja environment jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader('static/templates')) def user_required(handler): """ decorator that checks if the user exist """ def check_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri_for('login'), abort=True) else: return handler(self, *args, **kwargs) return check_login def admin_required(handler): """ decorator that checks if the admin exist """ def admin_login(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect('/auth/login', abort=True) user = auth.get_user_by_session() if user and user['user_id'] == 5069036098420736: return handler(self, *args, **kwargs) else: self.redirect('/', abort = True) return admin_login # Basehandler class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def auth(self): """ shortcut to access the auth instance """ return auth.get_auth() @webapp2.cached_property def user_info(self): """ shortcut to access a subset of the user attributes """ return self.auth.get_user_by_session() @webapp2.cached_property def user(self): """ shortcut to the current logged in user """ u = self.user_info return self.user_model.get_by_id(u['user_id']) if u else None @webapp2.cached_property def user_model(self): """ return the implementation """ return self.auth.store.user_model @webapp2.cached_property def session(self): """ shortcut """ if not self._backend_name: self._backend_name = 'memcache' return self.session_store.get_session(name = self._session_name, backend = self._backend_name) def set_session(self, arg_session_name = None, arg_backend_name = 'memcache'): self._session_name = arg_session_name self._backend_name = arg_backend_name def render_template(self, view_filename, params=None): if not params: params = {} user = self.user_info params['user'] = user template = jinja_environment.get_template(view_filename) self.response.out.write(template.render(params)) def display_message(self, message): """ utility function to display a template with a simple message """ params = { 'message' : message } self.render_template('/auth/message.html', params) # this is needed for webapp2 session to work def dispatch(self): # get a session store for this request self.session_store = sessions.get_store(request=self.request) try: # dispatch the request webapp2.RequestHandler.dispatch(self) finally: # save all session self.session_store.save_sessions(self.response) # get user' info def get_user_info(self): return self.auth.get_user_by_session()
0.33372
0.057812
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import pickle # Importing the dataset dataset = pd.read_csv('/home/mostafa/workarea_POSH/RF_FrontEnd/datasets/SH_Dataset_modified2.csv',header=None) dataset=dataset.dropna() X = np.array(dataset.iloc[1:, 0:5].values,dtype='float64') # Selecting the parameters y = np.array(dataset.iloc[1:, 5:].values,dtype='float64') # Selecting the metrics c = np.arange(0,len(y)) c = c[y[:,2]<0.00] y = np.delete(y,c,axis=0) X = np.delete(X,c,axis=0) np.random.seed(1234) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler sc_X = MinMaxScaler(feature_range=(-1,1)) sc_y = StandardScaler() sX_train = sc_X.fit_transform(X_train) sy_train = sc_y.fit_transform(y_train) sX_test = sc_X.transform (X_test ) sy_test = sc_y.transform (y_test ) #================================================================== #******************** Learning ********************************** #================================================================== # Importing the Keras libraries and packages from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras import losses from tensorflow.keras import optimizers import tensorflow.keras.initializers as init # Initialising the ANN reg = Sequential() reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu', input_dim = 5)) reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu')) reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu')) reg.add(Dense(units = 6 , kernel_initializer = init.glorot_uniform(), activation = 'linear')) # Compiling the ANN reg.compile(optimizer = optimizers.Adam(lr=0.001),loss = losses.mse) # Fitting the ANN to the Training set reg.fit(sX_train, sy_train, validation_split=0.05, batch_size = 500, epochs = 10000) score = reg.evaluate(sX_test, sy_test, batch_size = 500) #================================================================== #******************** Saving the regressor ********************** #================================================================== name = 'sh28' addr = '/home/mostafa/workarea_POSH/RF_FrontEnd/reg_files/SH/' reg_json=reg.to_json() with open(addr+'model_'+name+'.json', "w") as json_file: json_file.write(reg_json) reg.save_weights(addr+'reg_'+name+'.h5') from sklearn.externals import joblib joblib.dump(sc_X, addr+'scX_'+name+'.pkl') joblib.dump(sc_y, addr+'scY_'+name+'.pkl') pickle.dump( reg.get_weights(), open( addr+'w8_'+name+'.p', "wb" ) ) #================================================================== #******************** Loading the regressor ********************* #================================================================== """ from sklearn.externals import joblib from keras.models import model_from_json json_file = open('model_vco65.json', 'r') loaded_model_json = json_file.read() json_file.close() reg = model_from_json(loaded_model_json) reg.load_weights('reg_vco65.h5') Sc_X = joblib.load('scX_vco65.pkl') Sc_y = joblib.load('scY_vco65.pkl') """ #================================================================== #************************** Prediction ************************** #================================================================== sy_pred=reg.predict(sX_test) from sklearn.metrics import mean_squared_error y_pred=sc_y.inverse_transform(sy_pred) z=(y_pred-y_test) z_pred=y_pred/np.std(y_pred,axis=0) z_test=y_test/np.std(y_pred,axis=0) scores = [mean_squared_error(sy_pred[:,i],sy_test[:,i]) for i in range(len(y_test[0,:]))] #================================================================== #************************ Visualization ************************* #================================================================== lst_metric_names = ['Power (uW)', 'Output Amp. pp (V)','Tracking Bandwidth(GHz)', 'ENOB (bit)','SNR (dB)','SFDR (dB)' ] lst_metric_coef = [1e6,1,1,1,1,1] i=0 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=1 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=2 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=3 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=4 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=5 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i])
Block/RF_FrontEnd/TSMC28_RF_FrontEnd_1.3.2020/make_reg/SHRegMaker.py
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import pickle # Importing the dataset dataset = pd.read_csv('/home/mostafa/workarea_POSH/RF_FrontEnd/datasets/SH_Dataset_modified2.csv',header=None) dataset=dataset.dropna() X = np.array(dataset.iloc[1:, 0:5].values,dtype='float64') # Selecting the parameters y = np.array(dataset.iloc[1:, 5:].values,dtype='float64') # Selecting the metrics c = np.arange(0,len(y)) c = c[y[:,2]<0.00] y = np.delete(y,c,axis=0) X = np.delete(X,c,axis=0) np.random.seed(1234) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler sc_X = MinMaxScaler(feature_range=(-1,1)) sc_y = StandardScaler() sX_train = sc_X.fit_transform(X_train) sy_train = sc_y.fit_transform(y_train) sX_test = sc_X.transform (X_test ) sy_test = sc_y.transform (y_test ) #================================================================== #******************** Learning ********************************** #================================================================== # Importing the Keras libraries and packages from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras import losses from tensorflow.keras import optimizers import tensorflow.keras.initializers as init # Initialising the ANN reg = Sequential() reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu', input_dim = 5)) reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu')) reg.add(Dense(units = 200, kernel_initializer = init.glorot_uniform(), activation = 'elu')) reg.add(Dense(units = 6 , kernel_initializer = init.glorot_uniform(), activation = 'linear')) # Compiling the ANN reg.compile(optimizer = optimizers.Adam(lr=0.001),loss = losses.mse) # Fitting the ANN to the Training set reg.fit(sX_train, sy_train, validation_split=0.05, batch_size = 500, epochs = 10000) score = reg.evaluate(sX_test, sy_test, batch_size = 500) #================================================================== #******************** Saving the regressor ********************** #================================================================== name = 'sh28' addr = '/home/mostafa/workarea_POSH/RF_FrontEnd/reg_files/SH/' reg_json=reg.to_json() with open(addr+'model_'+name+'.json', "w") as json_file: json_file.write(reg_json) reg.save_weights(addr+'reg_'+name+'.h5') from sklearn.externals import joblib joblib.dump(sc_X, addr+'scX_'+name+'.pkl') joblib.dump(sc_y, addr+'scY_'+name+'.pkl') pickle.dump( reg.get_weights(), open( addr+'w8_'+name+'.p', "wb" ) ) #================================================================== #******************** Loading the regressor ********************* #================================================================== """ from sklearn.externals import joblib from keras.models import model_from_json json_file = open('model_vco65.json', 'r') loaded_model_json = json_file.read() json_file.close() reg = model_from_json(loaded_model_json) reg.load_weights('reg_vco65.h5') Sc_X = joblib.load('scX_vco65.pkl') Sc_y = joblib.load('scY_vco65.pkl') """ #================================================================== #************************** Prediction ************************** #================================================================== sy_pred=reg.predict(sX_test) from sklearn.metrics import mean_squared_error y_pred=sc_y.inverse_transform(sy_pred) z=(y_pred-y_test) z_pred=y_pred/np.std(y_pred,axis=0) z_test=y_test/np.std(y_pred,axis=0) scores = [mean_squared_error(sy_pred[:,i],sy_test[:,i]) for i in range(len(y_test[0,:]))] #================================================================== #************************ Visualization ************************* #================================================================== lst_metric_names = ['Power (uW)', 'Output Amp. pp (V)','Tracking Bandwidth(GHz)', 'ENOB (bit)','SNR (dB)','SFDR (dB)' ] lst_metric_coef = [1e6,1,1,1,1,1] i=0 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=1 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=2 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=3 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=4 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i]) i=5 plt.figure() plt.grid();plt.scatter(y_pred[:,i]*lst_metric_coef[i],z[:,i]*lst_metric_coef[i]);plt.xlabel('SPICE Simulated '+lst_metric_names[i]);plt.ylabel('Error of '+lst_metric_names[i])
0.617282
0.498169
# Copyright (C) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT """Day Twenty-One, Allergen Assessment.""" from sys import argv from re import findall from collections import defaultdict from functools import reduce from utils import open_file, arrange, usage_and_exit, freqd2 def gen_allergen(recipes): """From a list of <recipes> group together similar allergens ingredients. """ grouped_aller = defaultdict(list) groups = [{aller: recipe[0] for aller in recipe[1]} for recipe in recipes] for dictionary in groups: for key, elem in dictionary.items(): grouped_aller[key] += [elem] return grouped_aller def intersect(groups): """Given <groups> of allergens grouped with ingredients, find the allergen contained in each of the relevant ingredients. """ intersecs = {k: reduce(lambda a, b: a.intersection(b), e) for k, e in groups.items()} inert = False found = set() while not inert: inert = True for key, elem in intersecs.items(): if isinstance(elem, set): inert = False if len(elem) == 1: intersecs[key] = [*elem][0] found |= elem else: intersecs[key] = elem.difference(found) return intersecs def solve1(freq, groups): """Count the number of occurrences of ingredients without allergens given the frequency <freq> and the <groups>. """ intersecs = intersect(groups) return sum([freq[k] for k in set(freq.keys()) .difference(set(intersecs.values()))]) def solve2(groups): """Return an alphabetical list with the ingredients arranged according to their allergens given the <groups>. """ intersecs = intersect(groups) return ",".join([intersecs[a] for a in sorted(intersecs.keys())]) # Extract the ingredients. INGR_REG = r"(?<!\()\b(\w+) " # Get the allergens. ALLER_REG = r"(?:(\w+)(?:, |\)))" if __name__ == "__main__": usage_and_exit(len(argv) != 2) input_data = arrange(open_file(argv[1])) ingredients = [set(findall(INGR_REG, recipe)) for recipe in input_data] allergens = [set(findall(ALLER_REG, recipe)) for recipe in input_data] recipe = list(zip(ingredients, allergens)) freq_data = freqd2(ingredients) group_data = gen_allergen(recipe) print(solve1(freq_data, group_data)) print(solve2(group_data))
src/day21.py
# Copyright (C) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT """Day Twenty-One, Allergen Assessment.""" from sys import argv from re import findall from collections import defaultdict from functools import reduce from utils import open_file, arrange, usage_and_exit, freqd2 def gen_allergen(recipes): """From a list of <recipes> group together similar allergens ingredients. """ grouped_aller = defaultdict(list) groups = [{aller: recipe[0] for aller in recipe[1]} for recipe in recipes] for dictionary in groups: for key, elem in dictionary.items(): grouped_aller[key] += [elem] return grouped_aller def intersect(groups): """Given <groups> of allergens grouped with ingredients, find the allergen contained in each of the relevant ingredients. """ intersecs = {k: reduce(lambda a, b: a.intersection(b), e) for k, e in groups.items()} inert = False found = set() while not inert: inert = True for key, elem in intersecs.items(): if isinstance(elem, set): inert = False if len(elem) == 1: intersecs[key] = [*elem][0] found |= elem else: intersecs[key] = elem.difference(found) return intersecs def solve1(freq, groups): """Count the number of occurrences of ingredients without allergens given the frequency <freq> and the <groups>. """ intersecs = intersect(groups) return sum([freq[k] for k in set(freq.keys()) .difference(set(intersecs.values()))]) def solve2(groups): """Return an alphabetical list with the ingredients arranged according to their allergens given the <groups>. """ intersecs = intersect(groups) return ",".join([intersecs[a] for a in sorted(intersecs.keys())]) # Extract the ingredients. INGR_REG = r"(?<!\()\b(\w+) " # Get the allergens. ALLER_REG = r"(?:(\w+)(?:, |\)))" if __name__ == "__main__": usage_and_exit(len(argv) != 2) input_data = arrange(open_file(argv[1])) ingredients = [set(findall(INGR_REG, recipe)) for recipe in input_data] allergens = [set(findall(ALLER_REG, recipe)) for recipe in input_data] recipe = list(zip(ingredients, allergens)) freq_data = freqd2(ingredients) group_data = gen_allergen(recipe) print(solve1(freq_data, group_data)) print(solve2(group_data))
0.696475
0.301658
_base_ = ['../../_base_/default_runtime.py'] dict_file = 'data/chineseocr/labels/dict_printed_chinese_english_digits.txt' label_convertor = dict( type='AttnConvertor', dict_file=dict_file, with_unknown=True) model = dict( type='SARNet', backbone=dict(type='ResNet31OCR'), encoder=dict( type='SAREncoder', enc_bi_rnn=False, enc_do_rnn=0.1, enc_gru=False, ), decoder=dict( type='ParallelSARDecoder', enc_bi_rnn=False, dec_bi_rnn=False, dec_do_rnn=0, dec_gru=False, pred_dropout=0.1, d_k=512, pred_concat=True), loss=dict(type='SARLoss'), label_convertor=label_convertor, max_seq_len=30) # optimizer optimizer = dict(type='Adam', lr=1e-3) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict(policy='step', step=[3, 4]) total_epochs = 5 img_norm_cfg = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='ResizeOCR', height=48, min_width=48, max_width=256, keep_aspect_ratio=True, width_downsample_ratio=0.25), dict(type='ToTensorOCR'), dict(type='NormalizeOCR', **img_norm_cfg), dict( type='Collect', keys=['img'], meta_keys=[ 'filename', 'ori_shape', 'img_shape', 'text', 'valid_ratio' ]), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiRotateAugOCR', rotate_degrees=[0, 90, 270], transforms=[ dict( type='ResizeOCR', height=48, min_width=48, max_width=256, keep_aspect_ratio=True, width_downsample_ratio=0.25), dict(type='ToTensorOCR'), dict(type='NormalizeOCR', **img_norm_cfg), dict( type='Collect', keys=['img'], meta_keys=[ 'filename', 'ori_shape', 'img_shape', 'valid_ratio' ]), ]) ] dataset_type = 'OCRDataset' train_prefix = 'data/chinese/' train_ann_file = train_prefix + 'labels/train.txt' train = dict( type=dataset_type, img_prefix=train_prefix, ann_file=train_ann_file, loader=dict( type='HardDiskLoader', repeat=1, parser=dict( type='LineStrParser', keys=['filename', 'text'], keys_idx=[0, 1], separator=' ')), pipeline=train_pipeline, test_mode=False) test_prefix = 'data/chineseocr/' test_ann_file = test_prefix + 'labels/test.txt' test = dict( type=dataset_type, img_prefix=test_prefix, ann_file=test_ann_file, loader=dict( type='HardDiskLoader', repeat=1, parser=dict( type='LineStrParser', keys=['filename', 'text'], keys_idx=[0, 1], separator=' ')), pipeline=test_pipeline, test_mode=False) data = dict( samples_per_gpu=40, workers_per_gpu=2, train=dict(type='ConcatDataset', datasets=[train]), val=dict(type='ConcatDataset', datasets=[test]), test=dict(type='ConcatDataset', datasets=[test])) evaluation = dict(interval=1, metric='acc')
configs/textrecog/sar/sar_r31_parallel_decoder_chinese.py
_base_ = ['../../_base_/default_runtime.py'] dict_file = 'data/chineseocr/labels/dict_printed_chinese_english_digits.txt' label_convertor = dict( type='AttnConvertor', dict_file=dict_file, with_unknown=True) model = dict( type='SARNet', backbone=dict(type='ResNet31OCR'), encoder=dict( type='SAREncoder', enc_bi_rnn=False, enc_do_rnn=0.1, enc_gru=False, ), decoder=dict( type='ParallelSARDecoder', enc_bi_rnn=False, dec_bi_rnn=False, dec_do_rnn=0, dec_gru=False, pred_dropout=0.1, d_k=512, pred_concat=True), loss=dict(type='SARLoss'), label_convertor=label_convertor, max_seq_len=30) # optimizer optimizer = dict(type='Adam', lr=1e-3) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict(policy='step', step=[3, 4]) total_epochs = 5 img_norm_cfg = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) train_pipeline = [ dict(type='LoadImageFromFile'), dict( type='ResizeOCR', height=48, min_width=48, max_width=256, keep_aspect_ratio=True, width_downsample_ratio=0.25), dict(type='ToTensorOCR'), dict(type='NormalizeOCR', **img_norm_cfg), dict( type='Collect', keys=['img'], meta_keys=[ 'filename', 'ori_shape', 'img_shape', 'text', 'valid_ratio' ]), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiRotateAugOCR', rotate_degrees=[0, 90, 270], transforms=[ dict( type='ResizeOCR', height=48, min_width=48, max_width=256, keep_aspect_ratio=True, width_downsample_ratio=0.25), dict(type='ToTensorOCR'), dict(type='NormalizeOCR', **img_norm_cfg), dict( type='Collect', keys=['img'], meta_keys=[ 'filename', 'ori_shape', 'img_shape', 'valid_ratio' ]), ]) ] dataset_type = 'OCRDataset' train_prefix = 'data/chinese/' train_ann_file = train_prefix + 'labels/train.txt' train = dict( type=dataset_type, img_prefix=train_prefix, ann_file=train_ann_file, loader=dict( type='HardDiskLoader', repeat=1, parser=dict( type='LineStrParser', keys=['filename', 'text'], keys_idx=[0, 1], separator=' ')), pipeline=train_pipeline, test_mode=False) test_prefix = 'data/chineseocr/' test_ann_file = test_prefix + 'labels/test.txt' test = dict( type=dataset_type, img_prefix=test_prefix, ann_file=test_ann_file, loader=dict( type='HardDiskLoader', repeat=1, parser=dict( type='LineStrParser', keys=['filename', 'text'], keys_idx=[0, 1], separator=' ')), pipeline=test_pipeline, test_mode=False) data = dict( samples_per_gpu=40, workers_per_gpu=2, train=dict(type='ConcatDataset', datasets=[train]), val=dict(type='ConcatDataset', datasets=[test]), test=dict(type='ConcatDataset', datasets=[test])) evaluation = dict(interval=1, metric='acc')
0.612194
0.170802
import os import math import warnings import time import numpy as np import random as rn import tensorflow as tf from tensorBNN.activationFunctions import Tanh from tensorBNN.layer import DenseLayer from tensorBNN.network import network from tensorBNN.likelihood import GaussianLikelihood from tensorBNN.metrics import SquaredError, PercentError import time startTime = time.time() # This supresses many deprecation warnings warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", category=UserWarning) # Set the GPU to use os.environ["CUDA_VISIBLE_DEVICES"] = "0" os.environ["PYTHONHASHSEED"] = "0" np.random.seed(42) rn.seed(12345) tf.random.set_seed(3) def main(): trainIn=np.linspace(-2,2,num=31) valIn=np.linspace(-2+2/30,2.0-2/30,num=30) trainOut = np.sin(trainIn*math.pi*2)*trainIn-np.cos(trainIn*math.pi) valOut = np.sin(valIn*math.pi*2)*valIn-np.cos(valIn*math.pi) data=[trainIn, trainOut, valIn, valOut] dtype=tf.float32 inputDims=1 outputDims=1 normInfo=(0,1) # mean, sd likelihood=GaussianLikelihood(sd=0.1) metricList=[SquaredError(mean=normInfo[0], sd=normInfo[1]), PercentError(mean=normInfo[0], sd=normInfo[1])] neuralNet = network( dtype, # network datatype inputDims, # dimension of input vector data[0], # training input data data[1], # training output data data[2], # validation input data data[3]) # validation output data width = 10 # perceptrons per layer hidden = 3 # number of hidden layers seed = 0 # random seed neuralNet.add( DenseLayer( # Dense layer object inputDims, # Size of layer input vector width, # Size of layer output vector seed=seed, # Random seed dtype=dtype)) # Layer datatype neuralNet.add(Tanh()) # Tanh activation function seed += 1000 # Increment random seed for n in range(hidden - 1): # Add more hidden layers neuralNet.add(DenseLayer(width, width, seed=seed, dtype=dtype)) #neuralNet.add(Relu()) neuralNet.add(Tanh()) seed += 1000 neuralNet.add(DenseLayer(width, outputDims, seed=seed, dtype=dtype)) neuralNet.setupMCMC( 0.005, # starting stepsize 0.0025, # minimum stepsize 0.01, # maximum stepsize 40, # number of stepsize options in stepsize adapter 2, # starting number of leapfrog steps 2, # minimum number of leapfrog steps 50, # maximum number of leapfrog steps 1, # stepsize between leapfrog steps in leapfrog step adapter 0.0015, # hyper parameter stepsize 5, # hyper parameter number of leapfrog steps 20, # number of burnin epochs 20, # number of cores 2) # number of averaging steps for param adapters) neuralNet.train( 1020, # epochs to train for 10, # increment between network saves likelihood, metricList=metricList, folderName="TrigRegression", # Name of folder for saved networks networksPerFile=50) # Number of networks saved per file print("Time elapsed:", time.time() - startTime) if(__name__ == "__main__"): main()
Examples/trainRegression.py
import os import math import warnings import time import numpy as np import random as rn import tensorflow as tf from tensorBNN.activationFunctions import Tanh from tensorBNN.layer import DenseLayer from tensorBNN.network import network from tensorBNN.likelihood import GaussianLikelihood from tensorBNN.metrics import SquaredError, PercentError import time startTime = time.time() # This supresses many deprecation warnings warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", category=UserWarning) # Set the GPU to use os.environ["CUDA_VISIBLE_DEVICES"] = "0" os.environ["PYTHONHASHSEED"] = "0" np.random.seed(42) rn.seed(12345) tf.random.set_seed(3) def main(): trainIn=np.linspace(-2,2,num=31) valIn=np.linspace(-2+2/30,2.0-2/30,num=30) trainOut = np.sin(trainIn*math.pi*2)*trainIn-np.cos(trainIn*math.pi) valOut = np.sin(valIn*math.pi*2)*valIn-np.cos(valIn*math.pi) data=[trainIn, trainOut, valIn, valOut] dtype=tf.float32 inputDims=1 outputDims=1 normInfo=(0,1) # mean, sd likelihood=GaussianLikelihood(sd=0.1) metricList=[SquaredError(mean=normInfo[0], sd=normInfo[1]), PercentError(mean=normInfo[0], sd=normInfo[1])] neuralNet = network( dtype, # network datatype inputDims, # dimension of input vector data[0], # training input data data[1], # training output data data[2], # validation input data data[3]) # validation output data width = 10 # perceptrons per layer hidden = 3 # number of hidden layers seed = 0 # random seed neuralNet.add( DenseLayer( # Dense layer object inputDims, # Size of layer input vector width, # Size of layer output vector seed=seed, # Random seed dtype=dtype)) # Layer datatype neuralNet.add(Tanh()) # Tanh activation function seed += 1000 # Increment random seed for n in range(hidden - 1): # Add more hidden layers neuralNet.add(DenseLayer(width, width, seed=seed, dtype=dtype)) #neuralNet.add(Relu()) neuralNet.add(Tanh()) seed += 1000 neuralNet.add(DenseLayer(width, outputDims, seed=seed, dtype=dtype)) neuralNet.setupMCMC( 0.005, # starting stepsize 0.0025, # minimum stepsize 0.01, # maximum stepsize 40, # number of stepsize options in stepsize adapter 2, # starting number of leapfrog steps 2, # minimum number of leapfrog steps 50, # maximum number of leapfrog steps 1, # stepsize between leapfrog steps in leapfrog step adapter 0.0015, # hyper parameter stepsize 5, # hyper parameter number of leapfrog steps 20, # number of burnin epochs 20, # number of cores 2) # number of averaging steps for param adapters) neuralNet.train( 1020, # epochs to train for 10, # increment between network saves likelihood, metricList=metricList, folderName="TrigRegression", # Name of folder for saved networks networksPerFile=50) # Number of networks saved per file print("Time elapsed:", time.time() - startTime) if(__name__ == "__main__"): main()
0.507324
0.349061
import math from collections import defaultdict import timeit from wikiIndexer import removeStopWords, stem, tokenise wlist = [] tlist = [] title_dic = defaultdict(int) opt_dict = defaultdict(int) global no_of_docs def get_docNum(): global no_of_docs with open("tmp/doc_count.txt", "r") as fp: for line in fp: no_of_docs = int(line.strip()) return no_of_docs print(no_of_docs) no_of_docs = get_docNum() def load_title(): global tlist global title_dic with open("tmp/title_offsets", "r") as fp1: for line in fp1: line = line.strip().split() title_dic[int(line[0].strip())] = int(line[1].strip()) fp1.close() tlist = sorted(list(title_dic.keys())) # print(title_dic) def bsearch_titleno(docid): global title_dic global tlist #print(tlist) pos = 0 low = 0 high = len(tlist)-1 # print(title_dic) # print(docid) while low <= high: mid = int((low+high)/2) if int(tlist[mid]) == docid: return title_dic[docid] elif tlist[mid] < docid: pos = mid low = mid+1 else: high = mid-1 '''print("title dic") print(title_dic[tlist[pos]])''' # print(title_dic[tlist[pos]]) # print(title_dic[tlist[pos]]) #print(docid,pos) #print(title_dic) return title_dic[tlist[pos]] def get_title(fno, docid): global title_dic with open("tmp/titles"+str(fno), "r") as fp: for line in fp: line = line.split("-") if int(line[0]) == docid: # print(line[1].strip("\n")) return line[1].strip("\n") def load_offsetfile(): global opt_dict global wlist with open("tmp/offset", "r") as fp: for line in fp: line = line.strip().split(":") opt_dict[line[0]] = line[1] fp.close() wlist = sorted(list(opt_dict.keys())) def bsearch_fileno(word): global opt_dict #print(opt_dict) global wlist #print(wlist) pos = 0 low = 0 high = len(wlist)-1 while low <= high: mid = int((low+high)/2) if wlist[mid] == word: return opt_dict[word] # print(opt_dict[word]) elif wlist[mid] < word: low = mid+1 else: pos = mid high = mid-1 # print(opt_dict[wlist[pos]]) return opt_dict[wlist[pos]] def getList(word, fno): with open("tmp/file"+str(fno), "r") as fp: for line in fp: line = line.strip().split("/") if line[0] == word: return line[1] return [] def rank_simple(posting_dict): global no_of_docs rank_list = defaultdict(float) l = posting_dict.keys() for word in l: postlist = posting_dict[word] if len(postlist) != 0: postlist = postlist.split(";") df = len(postlist) idf = math.log10(10/df) # print(postlist) for doc in postlist: doc = doc.split("-") doc_id = int(doc[0]) line = doc[1].split(":") freq = int(line[0][1:]) tf = math.log10(1+freq) rank_list[doc_id] += tf*idf # print(rank_list) return rank_list def rank_field(posting_dict, query_dict): global no_of_docs rank_list = defaultdict(float) l = posting_dict.keys() wt = {'t': 140, 'i': 80, 'c': 50, 'e': 20} for word in l: postlist = posting_dict[word] if len(postlist) != 0: postlist = postlist.split(";") df = len(postlist) idf = math.log10(no_of_docs/df) for doc in postlist: doc = doc.split("-") doc_id = int(doc[0]) line = doc[1].split(":") fields_to_match = query_dict[word] freq = 0 for j in line: if j[0] == 'b': freq += int(j[1:]) for i in fields_to_match: for j in line: if i == j[0] and i != "b": freq += (int(j[1:])*wt[j[0]]) tf = math.log10(1+freq) rank_list[doc_id] += tf*idf # print(rank_list) return rank_list def simple_query(query): global title_dic # print(title_dic) qwords = tokenise(query) qwords = removeStopWords(qwords) qwords = stem(qwords) posting_dict = defaultdict(list) for w in qwords: fno = bsearch_fileno(w) posting = getList(w, fno) posting_dict[w] = posting ranked_list = rank_simple(posting_dict) if len(ranked_list) == 0: print("No match found") else: ranked_list_sort = sorted( ranked_list, key=ranked_list.get, reverse=True) # print(ranked_list.head()) #print("ranked {} title {}".format(ranked_list, get_title(fno,ranked_list_sort[i]))) for i in range(0, 10): if i >= len(ranked_list_sort): break fno = bsearch_titleno(ranked_list_sort[i]) #print(fno, ranked_list_sort[i]) print(get_title(fno, ranked_list_sort[i])) def create_dict(qdict, line, val): line = tokenise(line) line = removeStopWords(line) line = stem(line) for i in line: qdict[i].append(val) return qdict def get_fq_dict(inp): val = 0 t, r, b, inf, c, e = "", "", "", "", "", "" tmpp = "" val = len(inp)-1 i, tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 0, 0, 0 while i < val: x = inp[i] y = inp[i+1] if "i" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 0, 1 i = i+1 elif "t" == x and ":" == y: tf, bf, cf, ef, rf, inff = 1, 0, 0, 0, 0, 0 i = i+1 elif "b" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 1, 0, 0, 0, 0 i = i+1 elif "c" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 1, 0, 0, 0 i = i+1 elif "e" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 1, 0, 0 i = i+1 elif "r" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 1, 0 i = i+1 elif tf == 1: t = t+x elif bf == 1: b = b+x elif cf == 1: c = c+x elif ef == 1: e = e+x elif rf == 1: r = r+x elif inff == 1: inf = inf+x i = i+1 v = 1 l = len(inp)-1 if tf == v: t = t+inp[l] elif bf == v: b = b+inp[l] elif cf == v: c = c+inp[l] elif ef == v: e = e+inp[l] elif rf == v: r = r+inp[l] elif inff == 1: inf = inf+inp[l] qdict = defaultdict(list) qdict = create_dict(qdict, t, "t") qdict = create_dict(qdict, b, "b") qdict = create_dict(qdict, c, "c") qdict = create_dict(qdict, e, "e") qdict = create_dict(qdict, inf, "i") return qdict # print(qdict) def field_query(query): global title_dic query_dict = get_fq_dict(query) qwords = list(query_dict.keys()) posting_dict = defaultdict(list) for w in qwords: fno = bsearch_fileno(w) posting = getList(w, fno) posting_dict[w] = posting # print(posting_dict[w]) ranked_list = rank_field(posting_dict, query_dict) if len(ranked_list) == 0: print("No match found") else: ranked_list_sort = sorted( ranked_list, key=ranked_list.get, reverse=True) for i in range(0, 10): if i >= len(ranked_list_sort): break fno = bsearch_titleno(ranked_list_sort[i]) #print(fno, ranked_list_sort[i]) print(get_title(fno, ranked_list_sort[i])) def main(): load_offsetfile() load_title() while True: print("\n\nEnter Query") query = input() query = query.lower() start = timeit.default_timer() if ("i:" in query or "b:" in query or "c:" in query or "t:" in query or "e:" in query): field_query(query) else: simple_query(query) stop = timeit.default_timer() print ("\ntime :- "+str(stop - start)) # print("tilte") #print(get_title(943, 59341885)) # print("bsearch") # print(bsearch_fileno('acd')) main()
search.py
import math from collections import defaultdict import timeit from wikiIndexer import removeStopWords, stem, tokenise wlist = [] tlist = [] title_dic = defaultdict(int) opt_dict = defaultdict(int) global no_of_docs def get_docNum(): global no_of_docs with open("tmp/doc_count.txt", "r") as fp: for line in fp: no_of_docs = int(line.strip()) return no_of_docs print(no_of_docs) no_of_docs = get_docNum() def load_title(): global tlist global title_dic with open("tmp/title_offsets", "r") as fp1: for line in fp1: line = line.strip().split() title_dic[int(line[0].strip())] = int(line[1].strip()) fp1.close() tlist = sorted(list(title_dic.keys())) # print(title_dic) def bsearch_titleno(docid): global title_dic global tlist #print(tlist) pos = 0 low = 0 high = len(tlist)-1 # print(title_dic) # print(docid) while low <= high: mid = int((low+high)/2) if int(tlist[mid]) == docid: return title_dic[docid] elif tlist[mid] < docid: pos = mid low = mid+1 else: high = mid-1 '''print("title dic") print(title_dic[tlist[pos]])''' # print(title_dic[tlist[pos]]) # print(title_dic[tlist[pos]]) #print(docid,pos) #print(title_dic) return title_dic[tlist[pos]] def get_title(fno, docid): global title_dic with open("tmp/titles"+str(fno), "r") as fp: for line in fp: line = line.split("-") if int(line[0]) == docid: # print(line[1].strip("\n")) return line[1].strip("\n") def load_offsetfile(): global opt_dict global wlist with open("tmp/offset", "r") as fp: for line in fp: line = line.strip().split(":") opt_dict[line[0]] = line[1] fp.close() wlist = sorted(list(opt_dict.keys())) def bsearch_fileno(word): global opt_dict #print(opt_dict) global wlist #print(wlist) pos = 0 low = 0 high = len(wlist)-1 while low <= high: mid = int((low+high)/2) if wlist[mid] == word: return opt_dict[word] # print(opt_dict[word]) elif wlist[mid] < word: low = mid+1 else: pos = mid high = mid-1 # print(opt_dict[wlist[pos]]) return opt_dict[wlist[pos]] def getList(word, fno): with open("tmp/file"+str(fno), "r") as fp: for line in fp: line = line.strip().split("/") if line[0] == word: return line[1] return [] def rank_simple(posting_dict): global no_of_docs rank_list = defaultdict(float) l = posting_dict.keys() for word in l: postlist = posting_dict[word] if len(postlist) != 0: postlist = postlist.split(";") df = len(postlist) idf = math.log10(10/df) # print(postlist) for doc in postlist: doc = doc.split("-") doc_id = int(doc[0]) line = doc[1].split(":") freq = int(line[0][1:]) tf = math.log10(1+freq) rank_list[doc_id] += tf*idf # print(rank_list) return rank_list def rank_field(posting_dict, query_dict): global no_of_docs rank_list = defaultdict(float) l = posting_dict.keys() wt = {'t': 140, 'i': 80, 'c': 50, 'e': 20} for word in l: postlist = posting_dict[word] if len(postlist) != 0: postlist = postlist.split(";") df = len(postlist) idf = math.log10(no_of_docs/df) for doc in postlist: doc = doc.split("-") doc_id = int(doc[0]) line = doc[1].split(":") fields_to_match = query_dict[word] freq = 0 for j in line: if j[0] == 'b': freq += int(j[1:]) for i in fields_to_match: for j in line: if i == j[0] and i != "b": freq += (int(j[1:])*wt[j[0]]) tf = math.log10(1+freq) rank_list[doc_id] += tf*idf # print(rank_list) return rank_list def simple_query(query): global title_dic # print(title_dic) qwords = tokenise(query) qwords = removeStopWords(qwords) qwords = stem(qwords) posting_dict = defaultdict(list) for w in qwords: fno = bsearch_fileno(w) posting = getList(w, fno) posting_dict[w] = posting ranked_list = rank_simple(posting_dict) if len(ranked_list) == 0: print("No match found") else: ranked_list_sort = sorted( ranked_list, key=ranked_list.get, reverse=True) # print(ranked_list.head()) #print("ranked {} title {}".format(ranked_list, get_title(fno,ranked_list_sort[i]))) for i in range(0, 10): if i >= len(ranked_list_sort): break fno = bsearch_titleno(ranked_list_sort[i]) #print(fno, ranked_list_sort[i]) print(get_title(fno, ranked_list_sort[i])) def create_dict(qdict, line, val): line = tokenise(line) line = removeStopWords(line) line = stem(line) for i in line: qdict[i].append(val) return qdict def get_fq_dict(inp): val = 0 t, r, b, inf, c, e = "", "", "", "", "", "" tmpp = "" val = len(inp)-1 i, tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 0, 0, 0 while i < val: x = inp[i] y = inp[i+1] if "i" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 0, 1 i = i+1 elif "t" == x and ":" == y: tf, bf, cf, ef, rf, inff = 1, 0, 0, 0, 0, 0 i = i+1 elif "b" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 1, 0, 0, 0, 0 i = i+1 elif "c" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 1, 0, 0, 0 i = i+1 elif "e" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 1, 0, 0 i = i+1 elif "r" == x and ":" == y: tf, bf, cf, ef, rf, inff = 0, 0, 0, 0, 1, 0 i = i+1 elif tf == 1: t = t+x elif bf == 1: b = b+x elif cf == 1: c = c+x elif ef == 1: e = e+x elif rf == 1: r = r+x elif inff == 1: inf = inf+x i = i+1 v = 1 l = len(inp)-1 if tf == v: t = t+inp[l] elif bf == v: b = b+inp[l] elif cf == v: c = c+inp[l] elif ef == v: e = e+inp[l] elif rf == v: r = r+inp[l] elif inff == 1: inf = inf+inp[l] qdict = defaultdict(list) qdict = create_dict(qdict, t, "t") qdict = create_dict(qdict, b, "b") qdict = create_dict(qdict, c, "c") qdict = create_dict(qdict, e, "e") qdict = create_dict(qdict, inf, "i") return qdict # print(qdict) def field_query(query): global title_dic query_dict = get_fq_dict(query) qwords = list(query_dict.keys()) posting_dict = defaultdict(list) for w in qwords: fno = bsearch_fileno(w) posting = getList(w, fno) posting_dict[w] = posting # print(posting_dict[w]) ranked_list = rank_field(posting_dict, query_dict) if len(ranked_list) == 0: print("No match found") else: ranked_list_sort = sorted( ranked_list, key=ranked_list.get, reverse=True) for i in range(0, 10): if i >= len(ranked_list_sort): break fno = bsearch_titleno(ranked_list_sort[i]) #print(fno, ranked_list_sort[i]) print(get_title(fno, ranked_list_sort[i])) def main(): load_offsetfile() load_title() while True: print("\n\nEnter Query") query = input() query = query.lower() start = timeit.default_timer() if ("i:" in query or "b:" in query or "c:" in query or "t:" in query or "e:" in query): field_query(query) else: simple_query(query) stop = timeit.default_timer() print ("\ntime :- "+str(stop - start)) # print("tilte") #print(get_title(943, 59341885)) # print("bsearch") # print(bsearch_fileno('acd')) main()
0.111036
0.191914
from keras.models import Sequential, Model from keras.layers import Dense, LSTM, Bidirectional, GRU, Embedding, Dropout, Lambda from keras.layers import Input, concatenate NUM_CLASSES = 3 # Predict [space, comma, period] def blstm(hidden_units): m = Sequential() m.add(Bidirectional(LSTM(hidden_units, return_sequences=True), input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'blstm_{}'.format(hidden_units) return m def bgru(hidden_units): m = Sequential() m.add(Bidirectional(GRU(hidden_units, return_sequences=True), input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'bgru_{}'.format(hidden_units) return m def emb_bgru(hidden_units, words_vocabulary_size): m = Sequential() m.add(Embedding(words_vocabulary_size, hidden_units)) m.add(Bidirectional(GRU(hidden_units, return_sequences=True))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'emb_bgru_{}'.format(hidden_units) return m def cut_emb_bgru(hidden_units, words_vocabulary_size): m = Sequential() m.add(Embedding(words_vocabulary_size, hidden_units)) m.add(Bidirectional(GRU(hidden_units, return_sequences=True))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.add(Lambda(lambda x: x[:, :-1, :])) m.summary() m.name = 'cut_emb_bgru_{}'.format(hidden_units) return m def drop_emb_bgru(hidden_units, vocabulary_size): m = Sequential() m.add(Embedding(vocabulary_size, hidden_units)) m.add(Bidirectional(LSTM(hidden_units, return_sequences=True))) m.add(Dropout(0.4)) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'drop_emb_bgru_{}'.format(hidden_units) return m def uni_lstm(hidden_units): m = Sequential() m.add(LSTM(hidden_units, return_sequences=True, input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'lstm_{}'.format(hidden_units) return m def augmented_gru(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') # Distribute evenly emb1_out_units_cnt = hidden_units // 2 emb2_out_units_cnt = hidden_units - emb1_out_units_cnt emb1 = Embedding(words_vocabulary_size, emb1_out_units_cnt, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, emb2_out_units_cnt, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(GRU(hidden_units, name='gru_layer', return_sequences=True))(x) dense = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) m = Model(inputs=[input1, input2], outputs=[dense]) m.summary() m.name = 'augmented_gru_{}'.format(hidden_units) return m def cut_augmented_gru(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') emb1 = Embedding(words_vocabulary_size, 64, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, 64, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(GRU(hidden_units, name='gru_layer', return_sequences=True))(x) dense2 = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) # Manually drop last timestamp, because we don't care about anything after end of sentence nullf = Lambda(lambda x: x[:,:-1,:])(dense2) m = Model(inputs=[input1, input2], outputs=[nullf]) m.summary() m.name = 'cut_augmented_gru_{}'.format(hidden_units) return m def cut_augmented_lstm(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') emb1 = Embedding(words_vocabulary_size, 64, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, 64, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(LSTM(hidden_units, name='gru_layer', return_sequences=True))(x) dense2 = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) # Manually drop last timestamp, because we don't care about anything after end of sentence nullf = Lambda(lambda x: x[:,:-1,:])(dense2) m = Model(inputs=[input1, input2], outputs=[nullf]) m.summary() m.name = 'cut_augmented_lstm_{}'.format(hidden_units) return m
rupunktor/model_zoo.py
from keras.models import Sequential, Model from keras.layers import Dense, LSTM, Bidirectional, GRU, Embedding, Dropout, Lambda from keras.layers import Input, concatenate NUM_CLASSES = 3 # Predict [space, comma, period] def blstm(hidden_units): m = Sequential() m.add(Bidirectional(LSTM(hidden_units, return_sequences=True), input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'blstm_{}'.format(hidden_units) return m def bgru(hidden_units): m = Sequential() m.add(Bidirectional(GRU(hidden_units, return_sequences=True), input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'bgru_{}'.format(hidden_units) return m def emb_bgru(hidden_units, words_vocabulary_size): m = Sequential() m.add(Embedding(words_vocabulary_size, hidden_units)) m.add(Bidirectional(GRU(hidden_units, return_sequences=True))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'emb_bgru_{}'.format(hidden_units) return m def cut_emb_bgru(hidden_units, words_vocabulary_size): m = Sequential() m.add(Embedding(words_vocabulary_size, hidden_units)) m.add(Bidirectional(GRU(hidden_units, return_sequences=True))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.add(Lambda(lambda x: x[:, :-1, :])) m.summary() m.name = 'cut_emb_bgru_{}'.format(hidden_units) return m def drop_emb_bgru(hidden_units, vocabulary_size): m = Sequential() m.add(Embedding(vocabulary_size, hidden_units)) m.add(Bidirectional(LSTM(hidden_units, return_sequences=True))) m.add(Dropout(0.4)) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'drop_emb_bgru_{}'.format(hidden_units) return m def uni_lstm(hidden_units): m = Sequential() m.add(LSTM(hidden_units, return_sequences=True, input_shape=(None, 1))) m.add(Dense(NUM_CLASSES, activation='softmax')) m.summary() m.name = 'lstm_{}'.format(hidden_units) return m def augmented_gru(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') # Distribute evenly emb1_out_units_cnt = hidden_units // 2 emb2_out_units_cnt = hidden_units - emb1_out_units_cnt emb1 = Embedding(words_vocabulary_size, emb1_out_units_cnt, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, emb2_out_units_cnt, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(GRU(hidden_units, name='gru_layer', return_sequences=True))(x) dense = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) m = Model(inputs=[input1, input2], outputs=[dense]) m.summary() m.name = 'augmented_gru_{}'.format(hidden_units) return m def cut_augmented_gru(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') emb1 = Embedding(words_vocabulary_size, 64, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, 64, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(GRU(hidden_units, name='gru_layer', return_sequences=True))(x) dense2 = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) # Manually drop last timestamp, because we don't care about anything after end of sentence nullf = Lambda(lambda x: x[:,:-1,:])(dense2) m = Model(inputs=[input1, input2], outputs=[nullf]) m.summary() m.name = 'cut_augmented_gru_{}'.format(hidden_units) return m def cut_augmented_lstm(hidden_units, words_vocabulary_size, tags_vocabulary_size): input1 = Input(shape=(None,), name='word_input') input2 = Input(shape=(None,), name='pos_tags_input') emb1 = Embedding(words_vocabulary_size, 64, name='word_index_embedding')(input1) emb2 = Embedding(tags_vocabulary_size, 64, name='pos_tags_embedding')(input2) x = concatenate([emb1, emb2]) rnn = Bidirectional(LSTM(hidden_units, name='gru_layer', return_sequences=True))(x) dense2 = Dense(NUM_CLASSES, activation='softmax', name='output_tags')(rnn) # Manually drop last timestamp, because we don't care about anything after end of sentence nullf = Lambda(lambda x: x[:,:-1,:])(dense2) m = Model(inputs=[input1, input2], outputs=[nullf]) m.summary() m.name = 'cut_augmented_lstm_{}'.format(hidden_units) return m
0.910869
0.427098
PATH_NONE = "NONE" PATH_UNION = "UNION" PATH_INTER = "INTERSECT" PATH_EXCEPT = "EXCEPT" PATH_WHERE = "WHERE" PATH_HAVING = "HAVING" PATH_PAR = "PARALLEL" # To represent the multiple selection clauses in a single WHERE clause. VEC_AGGREGATORS = [ 'none', 'max', 'min', 'count', 'sum', 'avg' ] VEC_OPERATORS = [ 'none', '-', '+', "*", '/' ] VEC_CONDOPS = [ 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists' ] IDX_DESCRIPTORS = { 'asc': 0, 'desc': 1 } IDX_INV_DESCRIPTORS = { v:k for k,v in IDX_DESCRIPTORS.items() } MERGE_NONE = "NONE" MERGE_UNION = "UNION" MERGE_INTER = "INTERSECT" MERGE_EXCEPT = "EXCEPT" IDX_MERGE_OP = { MERGE_NONE: 0, MERGE_UNION: 1, MERGE_INTER: 2, MERGE_EXCEPT: 3 } IDX_PATH = { PATH_NONE: 0, PATH_UNION: 1, PATH_INTER: 2, PATH_EXCEPT: 3, PATH_WHERE: 4, PATH_HAVING: 5, PATH_PAR: 6 } # DB PROP CLASSIFICATION FEATURES. PF_PATH = "cur_path" PF_PATHIDX = "cur_path_idx" PF_MERGEOP = "merge_op" # Valid only when path == [ NONE ] PF_FROMSQL = "sql_from" # Valid only when path == [ NONE ] PF_ORDERBY = "is_orderby" PF_GROUPBY = "is_groupby" PF_LIMIT = "has_limit" PF_WHERE = "has_where" PF_HAVING = "has_having" PF_QTOKS = "question_tokens" PF_QGLOVE = "question_glove" PF_QCHAR = "question_char_idx" PF_QMATCH = "question_to_table_match_info" PF_TCOLTOKS = "table_column_tokens" PF_TCOLTBLN = "table_column_tbl_name" PF_TCOLTYPE = "table_column_types" PF_TCOLTYPEID = "table_column_type_ids" PF_TCOLGLOVE = "table_column_glove" PF_TCOLTBLGLOVE = "table_column_table_glove" PF_TMATCH = "table_to_question_match_info" PF_TPHMATCH = "table_column_exists_in_question_as_a_whole" # NOT IMPLEMENTED YET. PF_TKEYPRIMARY = "table_column_is_primary" PF_TKEYFOREIGN = "table_column_is_foreign" PF_Q = "question" PF_SQL = "sql" PF_TCOLTOKS_RAW = "table_column_tokens_raw" PF_TCOLTOKS_RAW_GLOVE = "table_column_tokens_raw_glove" PF_QMATCH_RAW = "question_to_table_match_info_raw" PF_TMATCH_RAW = "table_to_question_match_info_raw" PF_TCOLCHAR_RAW = "table_column_char_idx_raw" PF_TCOLCHAR = "table_column_char_idx" PF_TCOLTBLCHAR = "table_column_table_char_idx" # GROUP_BY CLASSIFICATION FIELDS. GF_NUMCOL = "groupby_col_num" GF_COLLIST = "groupby_col_list" # ORDER_BY CLASSSIFICATION FIELDS. OF_DESCRIPTOR = "orderby_descriptor" OF_NUMVU = "orderby_num_valueunit" OF_VU_OPERATOR = "orderby_valueunit_operator" OF_VU_AGG1 = "orderby_valueunit_agg1" OF_VU_COL1 = "orderby_valueunit_col1" OF_VU_DIST1 = "orderby_valueunit_isdist1" OF_VU_AGG2 = "orderby_valueunit_agg2" OF_VU_COL2 = "orderby_valueunit_col2" OF_VU_DIST2 = "orderby_valueunit_isdist2" # SELECT CLASSIFICATION FIELDS. SF_DISTINCT = "select_distinct" SF_NUM_VU = "select_num_valueunit" SF_VU_OPERATOR = "select_valueunit_operator" SF_VU_AGG1 = "select_valueunit_agg1" SF_VU_COL1 = "select_valueunit_col1" SF_VU_DIST1 = "select_valueunit_isdist1" SF_VU_AGG2 = "select_valueunit_agg2" SF_VU_COL2 = "select_valueunit_col2" SF_VU_DIST2 = "select_valueunit_isdist2" SF_VU_AGGALL = "select_valueunit_aggregator" # LIMIT CLASSIFICATION FIELDS. LF_ISMAX = "limit_ismax" LF_POINTERLOC = "limit_pointer_loc" # Valid only when LF_ISMAX is False. # WHERE CLASSIFICATION FIELDS. WF_NUM_CONDUNIT = "where_num_condunit" WF_CU_AGGREGATOR = "where_cu_aggregator" WF_CU_IS_NOT = "where_cu_is_not" WF_CU_COND_OP = "where_cu_condop" WF_CU_VAL1_TYPE = "where_cu_val1_type" # 0: Text span, 1: BOOLEAN, 2: SELECT statement. WF_CU_VAL1_SP = "where_cu_val1_sp" # Valid only when WF_CU_VAL1_TYPE is text span. WF_CU_VAL1_EP = "where_cu_val1_ep" # Valid only when WF_CU_VAL1_TYPE is text span. WF_CU_VAL1_LIKELY = "where_cu_val1_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. WF_CU_VAL1_BOOLVAL = "where_cu_val1_boolean" # If the condition is expected to be true or false. WF_CU_VAL2_TYPE = "where_cu_val2_type" # 0: Text span, 1: BOOLEAN. WF_CU_VAL2_SP = "where_cu_val2_sp" # Valid only when WF_CU_COND_OP == 0 (between) WF_CU_VAL2_EP = "where_cu_val2_ep" # Valid only when WF_CU_COND_OP == 0 (between) WF_CU_VAL2_LIKELY = "where_cu_val2_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. WF_CU_VAL2_BOOLVAL = "where_cu_val2_boolean" # If the condition is expected to be true or false. WF_CU_VU_OPERATOR = "where_cu_valueunit_operator" WF_CU_VU_AGG1 = "where_cu_valueunit_agg1" WF_CU_VU_COL1 = "where_cu_valueunit_col1" WF_CU_VU_DIST1 = "where_cu_valueunit_isdist1" WF_CU_VU_AGG2 = "where_cu_valueunit_agg2" WF_CU_VU_COL2 = "where_cu_valueunit_col2" WF_CU_VU_DIST2 = "where_cu_valueunit_isdist2" WF_CU_VAL1_IGNORE = "where_ignore_val1" # Answer matching failed. WF_CU_VAL2_IGNORE = "where_ignore_val2" # Answer matching failed. # HAVING CLASSIFICATION FIELDS. HV_NUM_CONDUNIT = "having_num_condunit" HV_CU_AGGREGATOR = "having_cu_aggregator" HV_CU_IS_NOT = "having_cu_is_not" HV_CU_COND_OP = "having_cu_condop" HV_CU_VAL1_TYPE = "having_cu_val1_type" # 0: Text span, 1: BOOLEAN, 2: SELECT statement. HV_CU_VAL1_SP = "having_cu_val1_sp" # Valid only when HV_CU_VAL1_TYPE is text span. HV_CU_VAL1_EP = "having_cu_val1_ep" # Valid only when HV_CU_VAL1_TYPE is text span. HV_CU_VAL1_LIKELY = "having_cu_val1_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. HV_CU_VAL1_BOOLVAL = "having_cu_val1_boolean" # If the condition is expected to be true or false. HV_CU_VAL2_TYPE = "having_cu_val2_type" # 0: Text span, 1: BOOLEAN. HV_CU_VAL2_SP = "having_cu_val2_sp" # Valid only when HV_CU_COND_OP == 0 (between) HV_CU_VAL2_EP = "having_cu_val2_ep" # Valid only when HV_CU_COND_OP == 0 (between) HV_CU_VAL2_LIKELY = "having_cu_val2_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. HV_CU_VAL2_BOOLVAL = "having_cu_val2_boolean" # If the condition is expected to be true or false. HV_CU_VU_OPERATOR = "having_cu_valueunit_operator" HV_CU_VU_AGG1 = "having_cu_valueunit_agg1" HV_CU_VU_COL1 = "having_cu_valueunit_col1" HV_CU_VU_DIST1 = "having_cu_valueunit_isdist1" HV_CU_VU_AGG2 = "having_cu_valueunit_agg2" HV_CU_VU_COL2 = "having_cu_valueunit_col2" HV_CU_VU_DIST2 = "having_cu_valueunit_isdist2" HV_CU_VAL1_IGNORE = "having_ignore_val1" # Answer matching failed. HV_CU_VAL2_IGNORE = "having_ignore_val2" # Answer matching failed. # TABLE CLASSIFICATION FEATURES. TV_TABLES_NAME = "table_name" TV_TABLES_NAME_GLOVE = "table_name_glove_idx" TV_TABLES_NAME_CHAR = "table_name_char_idx" TV_NAME_EXACT = "table_name_exact_match" # TABLE CLASSIFICATION CLASSES. TV_TABLES_NUM = "table_used_num" TV_TABLES_USED_IDX = "tables_used_idx" # DB META. META_DB = "db" # BERT_RELATED. Q_BERT_TOK = "q_bert_tok" # Question BERT Tokens. C_BERT_TOK = "c_bert_tok" # Column BERT Tokens. BERT_ID = "bert_id" # BERT IDs.
util/db_meta.py
PATH_NONE = "NONE" PATH_UNION = "UNION" PATH_INTER = "INTERSECT" PATH_EXCEPT = "EXCEPT" PATH_WHERE = "WHERE" PATH_HAVING = "HAVING" PATH_PAR = "PARALLEL" # To represent the multiple selection clauses in a single WHERE clause. VEC_AGGREGATORS = [ 'none', 'max', 'min', 'count', 'sum', 'avg' ] VEC_OPERATORS = [ 'none', '-', '+', "*", '/' ] VEC_CONDOPS = [ 'between', '=', '>', '<', '>=', '<=', '!=', 'in', 'like', 'is', 'exists' ] IDX_DESCRIPTORS = { 'asc': 0, 'desc': 1 } IDX_INV_DESCRIPTORS = { v:k for k,v in IDX_DESCRIPTORS.items() } MERGE_NONE = "NONE" MERGE_UNION = "UNION" MERGE_INTER = "INTERSECT" MERGE_EXCEPT = "EXCEPT" IDX_MERGE_OP = { MERGE_NONE: 0, MERGE_UNION: 1, MERGE_INTER: 2, MERGE_EXCEPT: 3 } IDX_PATH = { PATH_NONE: 0, PATH_UNION: 1, PATH_INTER: 2, PATH_EXCEPT: 3, PATH_WHERE: 4, PATH_HAVING: 5, PATH_PAR: 6 } # DB PROP CLASSIFICATION FEATURES. PF_PATH = "cur_path" PF_PATHIDX = "cur_path_idx" PF_MERGEOP = "merge_op" # Valid only when path == [ NONE ] PF_FROMSQL = "sql_from" # Valid only when path == [ NONE ] PF_ORDERBY = "is_orderby" PF_GROUPBY = "is_groupby" PF_LIMIT = "has_limit" PF_WHERE = "has_where" PF_HAVING = "has_having" PF_QTOKS = "question_tokens" PF_QGLOVE = "question_glove" PF_QCHAR = "question_char_idx" PF_QMATCH = "question_to_table_match_info" PF_TCOLTOKS = "table_column_tokens" PF_TCOLTBLN = "table_column_tbl_name" PF_TCOLTYPE = "table_column_types" PF_TCOLTYPEID = "table_column_type_ids" PF_TCOLGLOVE = "table_column_glove" PF_TCOLTBLGLOVE = "table_column_table_glove" PF_TMATCH = "table_to_question_match_info" PF_TPHMATCH = "table_column_exists_in_question_as_a_whole" # NOT IMPLEMENTED YET. PF_TKEYPRIMARY = "table_column_is_primary" PF_TKEYFOREIGN = "table_column_is_foreign" PF_Q = "question" PF_SQL = "sql" PF_TCOLTOKS_RAW = "table_column_tokens_raw" PF_TCOLTOKS_RAW_GLOVE = "table_column_tokens_raw_glove" PF_QMATCH_RAW = "question_to_table_match_info_raw" PF_TMATCH_RAW = "table_to_question_match_info_raw" PF_TCOLCHAR_RAW = "table_column_char_idx_raw" PF_TCOLCHAR = "table_column_char_idx" PF_TCOLTBLCHAR = "table_column_table_char_idx" # GROUP_BY CLASSIFICATION FIELDS. GF_NUMCOL = "groupby_col_num" GF_COLLIST = "groupby_col_list" # ORDER_BY CLASSSIFICATION FIELDS. OF_DESCRIPTOR = "orderby_descriptor" OF_NUMVU = "orderby_num_valueunit" OF_VU_OPERATOR = "orderby_valueunit_operator" OF_VU_AGG1 = "orderby_valueunit_agg1" OF_VU_COL1 = "orderby_valueunit_col1" OF_VU_DIST1 = "orderby_valueunit_isdist1" OF_VU_AGG2 = "orderby_valueunit_agg2" OF_VU_COL2 = "orderby_valueunit_col2" OF_VU_DIST2 = "orderby_valueunit_isdist2" # SELECT CLASSIFICATION FIELDS. SF_DISTINCT = "select_distinct" SF_NUM_VU = "select_num_valueunit" SF_VU_OPERATOR = "select_valueunit_operator" SF_VU_AGG1 = "select_valueunit_agg1" SF_VU_COL1 = "select_valueunit_col1" SF_VU_DIST1 = "select_valueunit_isdist1" SF_VU_AGG2 = "select_valueunit_agg2" SF_VU_COL2 = "select_valueunit_col2" SF_VU_DIST2 = "select_valueunit_isdist2" SF_VU_AGGALL = "select_valueunit_aggregator" # LIMIT CLASSIFICATION FIELDS. LF_ISMAX = "limit_ismax" LF_POINTERLOC = "limit_pointer_loc" # Valid only when LF_ISMAX is False. # WHERE CLASSIFICATION FIELDS. WF_NUM_CONDUNIT = "where_num_condunit" WF_CU_AGGREGATOR = "where_cu_aggregator" WF_CU_IS_NOT = "where_cu_is_not" WF_CU_COND_OP = "where_cu_condop" WF_CU_VAL1_TYPE = "where_cu_val1_type" # 0: Text span, 1: BOOLEAN, 2: SELECT statement. WF_CU_VAL1_SP = "where_cu_val1_sp" # Valid only when WF_CU_VAL1_TYPE is text span. WF_CU_VAL1_EP = "where_cu_val1_ep" # Valid only when WF_CU_VAL1_TYPE is text span. WF_CU_VAL1_LIKELY = "where_cu_val1_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. WF_CU_VAL1_BOOLVAL = "where_cu_val1_boolean" # If the condition is expected to be true or false. WF_CU_VAL2_TYPE = "where_cu_val2_type" # 0: Text span, 1: BOOLEAN. WF_CU_VAL2_SP = "where_cu_val2_sp" # Valid only when WF_CU_COND_OP == 0 (between) WF_CU_VAL2_EP = "where_cu_val2_ep" # Valid only when WF_CU_COND_OP == 0 (between) WF_CU_VAL2_LIKELY = "where_cu_val2_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. WF_CU_VAL2_BOOLVAL = "where_cu_val2_boolean" # If the condition is expected to be true or false. WF_CU_VU_OPERATOR = "where_cu_valueunit_operator" WF_CU_VU_AGG1 = "where_cu_valueunit_agg1" WF_CU_VU_COL1 = "where_cu_valueunit_col1" WF_CU_VU_DIST1 = "where_cu_valueunit_isdist1" WF_CU_VU_AGG2 = "where_cu_valueunit_agg2" WF_CU_VU_COL2 = "where_cu_valueunit_col2" WF_CU_VU_DIST2 = "where_cu_valueunit_isdist2" WF_CU_VAL1_IGNORE = "where_ignore_val1" # Answer matching failed. WF_CU_VAL2_IGNORE = "where_ignore_val2" # Answer matching failed. # HAVING CLASSIFICATION FIELDS. HV_NUM_CONDUNIT = "having_num_condunit" HV_CU_AGGREGATOR = "having_cu_aggregator" HV_CU_IS_NOT = "having_cu_is_not" HV_CU_COND_OP = "having_cu_condop" HV_CU_VAL1_TYPE = "having_cu_val1_type" # 0: Text span, 1: BOOLEAN, 2: SELECT statement. HV_CU_VAL1_SP = "having_cu_val1_sp" # Valid only when HV_CU_VAL1_TYPE is text span. HV_CU_VAL1_EP = "having_cu_val1_ep" # Valid only when HV_CU_VAL1_TYPE is text span. HV_CU_VAL1_LIKELY = "having_cu_val1_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. HV_CU_VAL1_BOOLVAL = "having_cu_val1_boolean" # If the condition is expected to be true or false. HV_CU_VAL2_TYPE = "having_cu_val2_type" # 0: Text span, 1: BOOLEAN. HV_CU_VAL2_SP = "having_cu_val2_sp" # Valid only when HV_CU_COND_OP == 0 (between) HV_CU_VAL2_EP = "having_cu_val2_ep" # Valid only when HV_CU_COND_OP == 0 (between) HV_CU_VAL2_LIKELY = "having_cu_val2_likely" # 0: Exact match. 1: Front-likely. 2: Backward-likely. 3: Both side likely. HV_CU_VAL2_BOOLVAL = "having_cu_val2_boolean" # If the condition is expected to be true or false. HV_CU_VU_OPERATOR = "having_cu_valueunit_operator" HV_CU_VU_AGG1 = "having_cu_valueunit_agg1" HV_CU_VU_COL1 = "having_cu_valueunit_col1" HV_CU_VU_DIST1 = "having_cu_valueunit_isdist1" HV_CU_VU_AGG2 = "having_cu_valueunit_agg2" HV_CU_VU_COL2 = "having_cu_valueunit_col2" HV_CU_VU_DIST2 = "having_cu_valueunit_isdist2" HV_CU_VAL1_IGNORE = "having_ignore_val1" # Answer matching failed. HV_CU_VAL2_IGNORE = "having_ignore_val2" # Answer matching failed. # TABLE CLASSIFICATION FEATURES. TV_TABLES_NAME = "table_name" TV_TABLES_NAME_GLOVE = "table_name_glove_idx" TV_TABLES_NAME_CHAR = "table_name_char_idx" TV_NAME_EXACT = "table_name_exact_match" # TABLE CLASSIFICATION CLASSES. TV_TABLES_NUM = "table_used_num" TV_TABLES_USED_IDX = "tables_used_idx" # DB META. META_DB = "db" # BERT_RELATED. Q_BERT_TOK = "q_bert_tok" # Question BERT Tokens. C_BERT_TOK = "c_bert_tok" # Column BERT Tokens. BERT_ID = "bert_id" # BERT IDs.
0.375248
0.10466
import html from telegram import ParseMode, Update from telegram.error import BadRequest from telegram.ext import CallbackContext, CommandHandler, Filters, run_async from telegram.utils.helpers import mention_html from UltronRoBo import ( DEV_USERS, LOGGER, OWNER_ID, DRAGONS, DEMONS, TIGERS, WOLVES, dispatcher, ) from UltronRoBo.modules.disable import DisableAbleCommandHandler from UltronRoBo.modules.helper_funcs.chat_status import ( bot_admin, can_restrict, connection_status, is_user_admin, is_user_ban_protected, is_user_in_chat, user_admin, user_can_ban, can_delete, ) from UltronRoBo.modules.helper_funcs.extraction import extract_user_and_text from UltronRoBo.modules.helper_funcs.string_handling import extract_time from UltronRoBo.modules.log_channel import gloggable, loggable @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot = context.bot args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("Can't seem to find this person.") return log_message if user_id == bot.id: message.reply_text("Oh yeah, ban myself, noob!") return log_message if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS: if user_id == OWNER_ID: message.reply_text("Trying to put me against a God level disaster huh?") elif user_id in DEV_USERS: message.reply_text("I can't act against our own.") elif user_id in DRAGONS: message.reply_text( "Fighting this Dragon here will put civilian lives at risk." ) elif user_id in DEMONS: message.reply_text( "Bring an order from Heroes association to fight a Demon disaster." ) elif user_id in TIGERS: message.reply_text( "Bring an order from Heroes association to fight a Tiger disaster." ) elif user_id in WOLVES: message.reply_text("Wolf abilities make them ban immune!") else: message.reply_text("This user has immunity and cannot be banned.") return log_message if message.text.startswith("/s"): silent = True if not can_delete(chat, context.bot.id): return "" else: silent = False log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#{'S' if silent else ''}BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) if silent: if message.reply_to_message: message.reply_to_message.delete() message.delete() return log # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply = ( f"<code>❕</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: reply += f"\n<code> </code><b>• Reason:</b> \n{html.escape(reason)}" bot.sendMessage(chat.id, reply, parse_mode=ParseMode.HTML, quote=False) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply if silent: return log message.reply_text("Banned!", quote=False) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Uhm...that didn't work...") return log_message @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def temp_ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy?") return log_message if is_user_ban_protected(chat, user_id, member): message.reply_text("I don't feel like it.") return log_message if not reason: message.reply_text("You haven't specified a time to ban this user for!") return log_message split_reason = reason.split(None, 1) time_val = split_reason[0].lower() reason = split_reason[1] if len(split_reason) > 1 else "" bantime = extract_time(message, time_val) if not bantime: return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" "#TEMP BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}\n" f"<b>Time:</b> {time_val}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id, until_date=bantime) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker bot.sendMessage( chat.id, f"Banned! User {mention_html(member.user.id, html.escape(member.user.first_name))} " f"will be banned for {time_val}.", parse_mode=ParseMode.HTML, ) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( f"Banned! User will be banned for {time_val}.", quote=False ) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't ban that user.") return log_message @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def kick(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("Yeahhh I'm not gonna do that.") return log_message if is_user_ban_protected(chat, user_id): message.reply_text("I really wish I could kick this user....") return log_message res = chat.unban_member(user_id) # unban on current user = kick if res: # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker bot.sendMessage( chat.id, f"Yeah, Kicked! {mention_html(member.user.id, html.escape(member.user.first_name))}.", parse_mode=ParseMode.HTML, ) log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#KICKED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += f"\n<b>Reason:</b> {reason}" return log else: message.reply_text("Well damn, I can't kick that user.") return log_message @run_async @bot_admin @can_restrict def kickme(update: Update, context: CallbackContext): user_id = update.effective_message.from_user.id if is_user_admin(update.effective_chat, user_id): update.effective_message.reply_text("I wish I could... but you're an admin.") return res = update.effective_chat.unban_member(user_id) # unban on current user = kick if res: update.effective_message.reply_text("*Kicks you out of the group*") else: update.effective_message.reply_text("Huh? I can't :/") @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def unban(update: Update, context: CallbackContext) -> str: message = update.effective_message user = update.effective_user chat = update.effective_chat log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("How would I unban myself if I wasn't here...?") return log_message if is_user_in_chat(chat, user_id): message.reply_text("Isn't this person already here??") return log_message chat.unban_member(user_id) message.reply_text("Yep, this user can join!") log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#UNBANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += f"\n<b>Reason:</b> {reason}" return log @run_async @connection_status @bot_admin @can_restrict @gloggable def selfunban(context: CallbackContext, update: Update) -> str: message = update.effective_message user = update.effective_user bot, args = context.bot, context.args if user.id not in DRAGONS or user.id not in TIGERS: return try: chat_id = int(args[0]) except: message.reply_text("Give a valid chat ID.") return chat = bot.getChat(chat_id) try: member = chat.get_member(user.id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user.") return else: raise if is_user_in_chat(chat, user.id): message.reply_text("Aren't you already in the chat??") return chat.unban_member(user.id) message.reply_text("Yep, I have unbanned you.") log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#UNBANNED\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) return log __help__ = """ ❍ /kickme*:* Kicks the user who issued the command *Admins only:* ❍ /ban <userhandle>*:* bans a user. (via handle, or reply) ❍ /sban <userhandle>*:* Silently ban a user. Deletes command, Replied message and doesn't reply. (via handle, or reply) ❍ /tban <userhandle> x(m/h/d)*:* bans a user for `x` time. (via handle, or reply). `m` = `minutes`, `h` = `hours`, `d` = `days`. ❍ /unban <userhandle>*:* unbans a user. (via handle, or reply) ❍ /kick <userhandle>*:* Kicks a user out of the group, (via handle, or reply) *Admins only:* ❍ /mute <userhandle>*:* silences a user. Can also be used as a reply, muting the replied to user. ❍ /tmute <userhandle> x(m/h/d)*:* mutes a user for x time. (via handle, or reply). `m` = `minutes`, `h` = `hours`, `d` = `days`. ❍ /unmute <userhandle>*:* unmutes a user. Can also be used as a reply, muting the replied to user. """ BAN_HANDLER = CommandHandler(["ban", "sban"], ban) TEMPBAN_HANDLER = CommandHandler(["tban"], temp_ban) KICK_HANDLER = CommandHandler("kick", kick) UNBAN_HANDLER = CommandHandler("unban", unban) ROAR_HANDLER = CommandHandler("roar", selfunban) KICKME_HANDLER = DisableAbleCommandHandler("kickme", kickme, filters=Filters.group) dispatcher.add_handler(BAN_HANDLER) dispatcher.add_handler(TEMPBAN_HANDLER) dispatcher.add_handler(KICK_HANDLER) dispatcher.add_handler(UNBAN_HANDLER) dispatcher.add_handler(ROAR_HANDLER) dispatcher.add_handler(KICKME_HANDLER) __mod_name__ = "Ban/Mute" __handlers__ = [ BAN_HANDLER, TEMPBAN_HANDLER, KICK_HANDLER, UNBAN_HANDLER, ROAR_HANDLER, KICKME_HANDLER, ]
UltronRoBo/modules/bans.py
import html from telegram import ParseMode, Update from telegram.error import BadRequest from telegram.ext import CallbackContext, CommandHandler, Filters, run_async from telegram.utils.helpers import mention_html from UltronRoBo import ( DEV_USERS, LOGGER, OWNER_ID, DRAGONS, DEMONS, TIGERS, WOLVES, dispatcher, ) from UltronRoBo.modules.disable import DisableAbleCommandHandler from UltronRoBo.modules.helper_funcs.chat_status import ( bot_admin, can_restrict, connection_status, is_user_admin, is_user_ban_protected, is_user_in_chat, user_admin, user_can_ban, can_delete, ) from UltronRoBo.modules.helper_funcs.extraction import extract_user_and_text from UltronRoBo.modules.helper_funcs.string_handling import extract_time from UltronRoBo.modules.log_channel import gloggable, loggable @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot = context.bot args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("Can't seem to find this person.") return log_message if user_id == bot.id: message.reply_text("Oh yeah, ban myself, noob!") return log_message if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS: if user_id == OWNER_ID: message.reply_text("Trying to put me against a God level disaster huh?") elif user_id in DEV_USERS: message.reply_text("I can't act against our own.") elif user_id in DRAGONS: message.reply_text( "Fighting this Dragon here will put civilian lives at risk." ) elif user_id in DEMONS: message.reply_text( "Bring an order from Heroes association to fight a Demon disaster." ) elif user_id in TIGERS: message.reply_text( "Bring an order from Heroes association to fight a Tiger disaster." ) elif user_id in WOLVES: message.reply_text("Wolf abilities make them ban immune!") else: message.reply_text("This user has immunity and cannot be banned.") return log_message if message.text.startswith("/s"): silent = True if not can_delete(chat, context.bot.id): return "" else: silent = False log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#{'S' if silent else ''}BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) if silent: if message.reply_to_message: message.reply_to_message.delete() message.delete() return log # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker reply = ( f"<code>❕</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: reply += f"\n<code> </code><b>• Reason:</b> \n{html.escape(reason)}" bot.sendMessage(chat.id, reply, parse_mode=ParseMode.HTML, quote=False) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply if silent: return log message.reply_text("Banned!", quote=False) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Uhm...that didn't work...") return log_message @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def temp_ban(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("I'm not gonna BAN myself, are you crazy?") return log_message if is_user_ban_protected(chat, user_id, member): message.reply_text("I don't feel like it.") return log_message if not reason: message.reply_text("You haven't specified a time to ban this user for!") return log_message split_reason = reason.split(None, 1) time_val = split_reason[0].lower() reason = split_reason[1] if len(split_reason) > 1 else "" bantime = extract_time(message, time_val) if not bantime: return log_message log = ( f"<b>{html.escape(chat.title)}:</b>\n" "#TEMP BANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}\n" f"<b>Time:</b> {time_val}" ) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id, until_date=bantime) # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker bot.sendMessage( chat.id, f"Banned! User {mention_html(member.user.id, html.escape(member.user.first_name))} " f"will be banned for {time_val}.", parse_mode=ParseMode.HTML, ) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( f"Banned! User will be banned for {time_val}.", quote=False ) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't ban that user.") return log_message @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def kick(update: Update, context: CallbackContext) -> str: chat = update.effective_chat user = update.effective_user message = update.effective_message log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("Yeahhh I'm not gonna do that.") return log_message if is_user_ban_protected(chat, user_id): message.reply_text("I really wish I could kick this user....") return log_message res = chat.unban_member(user_id) # unban on current user = kick if res: # bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker bot.sendMessage( chat.id, f"Yeah, Kicked! {mention_html(member.user.id, html.escape(member.user.first_name))}.", parse_mode=ParseMode.HTML, ) log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#KICKED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += f"\n<b>Reason:</b> {reason}" return log else: message.reply_text("Well damn, I can't kick that user.") return log_message @run_async @bot_admin @can_restrict def kickme(update: Update, context: CallbackContext): user_id = update.effective_message.from_user.id if is_user_admin(update.effective_chat, user_id): update.effective_message.reply_text("I wish I could... but you're an admin.") return res = update.effective_chat.unban_member(user_id) # unban on current user = kick if res: update.effective_message.reply_text("*Kicks you out of the group*") else: update.effective_message.reply_text("Huh? I can't :/") @run_async @connection_status @bot_admin @can_restrict @user_admin @user_can_ban @loggable def unban(update: Update, context: CallbackContext) -> str: message = update.effective_message user = update.effective_user chat = update.effective_chat log_message = "" bot, args = context.bot, context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("I doubt that's a user.") return log_message try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message != "User not found": raise message.reply_text("I can't seem to find this user.") return log_message if user_id == bot.id: message.reply_text("How would I unban myself if I wasn't here...?") return log_message if is_user_in_chat(chat, user_id): message.reply_text("Isn't this person already here??") return log_message chat.unban_member(user_id) message.reply_text("Yep, this user can join!") log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#UNBANNED\n" f"<b>Admin:</b> {mention_html(user.id, html.escape(user.first_name))}\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) if reason: log += f"\n<b>Reason:</b> {reason}" return log @run_async @connection_status @bot_admin @can_restrict @gloggable def selfunban(context: CallbackContext, update: Update) -> str: message = update.effective_message user = update.effective_user bot, args = context.bot, context.args if user.id not in DRAGONS or user.id not in TIGERS: return try: chat_id = int(args[0]) except: message.reply_text("Give a valid chat ID.") return chat = bot.getChat(chat_id) try: member = chat.get_member(user.id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user.") return else: raise if is_user_in_chat(chat, user.id): message.reply_text("Aren't you already in the chat??") return chat.unban_member(user.id) message.reply_text("Yep, I have unbanned you.") log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#UNBANNED\n" f"<b>User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}" ) return log __help__ = """ ❍ /kickme*:* Kicks the user who issued the command *Admins only:* ❍ /ban <userhandle>*:* bans a user. (via handle, or reply) ❍ /sban <userhandle>*:* Silently ban a user. Deletes command, Replied message and doesn't reply. (via handle, or reply) ❍ /tban <userhandle> x(m/h/d)*:* bans a user for `x` time. (via handle, or reply). `m` = `minutes`, `h` = `hours`, `d` = `days`. ❍ /unban <userhandle>*:* unbans a user. (via handle, or reply) ❍ /kick <userhandle>*:* Kicks a user out of the group, (via handle, or reply) *Admins only:* ❍ /mute <userhandle>*:* silences a user. Can also be used as a reply, muting the replied to user. ❍ /tmute <userhandle> x(m/h/d)*:* mutes a user for x time. (via handle, or reply). `m` = `minutes`, `h` = `hours`, `d` = `days`. ❍ /unmute <userhandle>*:* unmutes a user. Can also be used as a reply, muting the replied to user. """ BAN_HANDLER = CommandHandler(["ban", "sban"], ban) TEMPBAN_HANDLER = CommandHandler(["tban"], temp_ban) KICK_HANDLER = CommandHandler("kick", kick) UNBAN_HANDLER = CommandHandler("unban", unban) ROAR_HANDLER = CommandHandler("roar", selfunban) KICKME_HANDLER = DisableAbleCommandHandler("kickme", kickme, filters=Filters.group) dispatcher.add_handler(BAN_HANDLER) dispatcher.add_handler(TEMPBAN_HANDLER) dispatcher.add_handler(KICK_HANDLER) dispatcher.add_handler(UNBAN_HANDLER) dispatcher.add_handler(ROAR_HANDLER) dispatcher.add_handler(KICKME_HANDLER) __mod_name__ = "Ban/Mute" __handlers__ = [ BAN_HANDLER, TEMPBAN_HANDLER, KICK_HANDLER, UNBAN_HANDLER, ROAR_HANDLER, KICKME_HANDLER, ]
0.184841
0.06216
import sys import unittest import timeit from numpy.linalg import det import numpy as np sys.path.append("../src") sys.path.append("src/") from tools import EqualMatrices, AssertAlmostEqualMatrices from gdft import dft_matrix, random_unitary_matrix, g_matrix, gdft_matrix, two_param_gdft_matrix, permutation_matrix dft2 = np.array([[1, 1], [1, -1]], dtype=np.complex128) GDFT_MAT = np.array([[1, -1], [-1, -1]], dtype=np.complex128) class TestGDFT(unittest.TestCase): def setUp(self): pass def testDFTMatrix(self): dft = dft_matrix(2) AssertAlmostEqualMatrices(dft, dft2) self.assertAlmostEqual(det(dft), -2.0) def testRandomUnitaryMatrix(self): unitary_mat = random_unitary_matrix(4) self.assertAlmostEqual(abs(det(unitary_mat)), 1) identity = np.dot(unitary_mat, np.conjugate(unitary_mat)) AssertAlmostEqualMatrices(np.identity(4), identity) def testGDFTMatrix(self): thetas = np.array([-.5 * np.pi, .5 * np.pi]) gdft_mat = gdft_matrix(2, thetas) dft = dft_matrix(2) g2 = g_matrix(thetas) AssertAlmostEqualMatrices(gdft_mat, np.array([[-1j, 1j], [-1j, -1j]], dtype=np.complex128)) AssertAlmostEqualMatrices(dft.dot(g2), gdft_mat) def test_two_param_GDFTMatrix(self): thetas = np.array([-.5 * np.pi, .5 * np.pi]) gdft_mat = two_param_gdft_matrix(2, -3*thetas, thetas) dft = dft_matrix(2) g2 = g_matrix(-3*thetas) g1 = g_matrix(thetas) AssertAlmostEqualMatrices(gdft_mat, np.array([[-1, 1], [1, 1]], dtype=np.complex128)) AssertAlmostEqualMatrices(g1.dot(dft.dot(g2)), gdft_mat) def test_permutation_matrix(self): perm = permutation_matrix(2, orderings=[1, 0]) self.assertTrue(EqualMatrices(perm, np.array([[0, 1], [1, 0]]))) perm = permutation_matrix(4, orderings=[1, 0, 3, 2, 4]) self.assertTrue(EqualMatrices(perm, np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]))) def tearDown(self): pass if __name__ == '__main__': unittest.main()
tests/testGDFT.py
import sys import unittest import timeit from numpy.linalg import det import numpy as np sys.path.append("../src") sys.path.append("src/") from tools import EqualMatrices, AssertAlmostEqualMatrices from gdft import dft_matrix, random_unitary_matrix, g_matrix, gdft_matrix, two_param_gdft_matrix, permutation_matrix dft2 = np.array([[1, 1], [1, -1]], dtype=np.complex128) GDFT_MAT = np.array([[1, -1], [-1, -1]], dtype=np.complex128) class TestGDFT(unittest.TestCase): def setUp(self): pass def testDFTMatrix(self): dft = dft_matrix(2) AssertAlmostEqualMatrices(dft, dft2) self.assertAlmostEqual(det(dft), -2.0) def testRandomUnitaryMatrix(self): unitary_mat = random_unitary_matrix(4) self.assertAlmostEqual(abs(det(unitary_mat)), 1) identity = np.dot(unitary_mat, np.conjugate(unitary_mat)) AssertAlmostEqualMatrices(np.identity(4), identity) def testGDFTMatrix(self): thetas = np.array([-.5 * np.pi, .5 * np.pi]) gdft_mat = gdft_matrix(2, thetas) dft = dft_matrix(2) g2 = g_matrix(thetas) AssertAlmostEqualMatrices(gdft_mat, np.array([[-1j, 1j], [-1j, -1j]], dtype=np.complex128)) AssertAlmostEqualMatrices(dft.dot(g2), gdft_mat) def test_two_param_GDFTMatrix(self): thetas = np.array([-.5 * np.pi, .5 * np.pi]) gdft_mat = two_param_gdft_matrix(2, -3*thetas, thetas) dft = dft_matrix(2) g2 = g_matrix(-3*thetas) g1 = g_matrix(thetas) AssertAlmostEqualMatrices(gdft_mat, np.array([[-1, 1], [1, 1]], dtype=np.complex128)) AssertAlmostEqualMatrices(g1.dot(dft.dot(g2)), gdft_mat) def test_permutation_matrix(self): perm = permutation_matrix(2, orderings=[1, 0]) self.assertTrue(EqualMatrices(perm, np.array([[0, 1], [1, 0]]))) perm = permutation_matrix(4, orderings=[1, 0, 3, 2, 4]) self.assertTrue(EqualMatrices(perm, np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]))) def tearDown(self): pass if __name__ == '__main__': unittest.main()
0.347426
0.651937
import importlib from types import LambdaType, ModuleType from typing import Any from typing import Callable as CallableType from typing import Dict, Tuple, Union from simple_di import ( VT, Provider, _inject_args, _inject_kwargs, _SentinelClass, inject, sentinel, ) __all__ = [ "Static", "Callable", "MemoizedCallable", "Factory", "SingletonFactory", "Configuration", ] class Static(Provider[VT]): """ provider that returns static values """ STATE_FIELDS = Provider.STATE_FIELDS + ("_value",) def __init__(self, value: VT): super().__init__() self._value = value def _provide(self) -> VT: return self._value def _probe_unique_name(module: ModuleType, origin_name: str) -> str: name = "__simple_di_" + origin_name.replace(".", "_").replace("<lambda>", "lambda") num = 0 while hasattr(module, f"{name}{num or ''}"): num += 1 return f"{name}{num or ''}" def _patch_anonymous(func: Any) -> None: module_name = func.__module__ origin_name = func.__qualname__ module = importlib.import_module(module_name) name = _probe_unique_name(module, origin_name) func.__qualname__ = name func.__name__ = name setattr(module, name, func) class Factory(Provider[VT]): """ provider that returns the result of a callable """ STATE_FIELDS = Provider.STATE_FIELDS + ( "_args", "_kwargs", "_func", "_chain_inject", ) def __init__(self, func: CallableType[..., VT], *args: Any, **kwargs: Any) -> None: super().__init__() self._args = args self._kwargs = kwargs self._chain_inject = False if isinstance(func, classmethod): raise TypeError("Factory as decorator only supports static methods") if isinstance(func, LambdaType): _patch_anonymous(func) if isinstance(func, staticmethod): self._chain_inject = True func = func.__func__ _patch_anonymous(func) self._func = func def _provide(self) -> VT: if self._chain_inject: return inject(self._func)( *_inject_args(self._args), **_inject_kwargs(self._kwargs) ) else: return self._func(*_inject_args(self._args), **_inject_kwargs(self._kwargs)) class SingletonFactory(Factory[VT]): """ provider that returns the result of a callable, but memorize the returns. """ STATE_FIELDS = Factory.STATE_FIELDS + ("_cache",) def __init__(self, func: CallableType[..., VT], *args: Any, **kwargs: Any) -> None: super().__init__(func, *args, **kwargs) self._cache: Union[_SentinelClass, VT] = sentinel def _provide(self) -> VT: if not isinstance(self._cache, _SentinelClass): return self._cache value = super()._provide() self._cache = value return value Callable = Factory MemoizedCallable = SingletonFactory ConfigDictType = Dict[Union[str, int], Any] PathItemType = Union[int, str, Provider[int], Provider[str]] class Configuration(Provider[ConfigDictType]): """ special provider that reflects the structure of a configuration dictionary. """ STATE_FIELDS = Provider.STATE_FIELDS + ("_data", "fallback") def __init__( self, data: Union[_SentinelClass, ConfigDictType] = sentinel, fallback: Any = sentinel, ) -> None: super().__init__() self._data = data self.fallback = fallback def set(self, value: Union[_SentinelClass, ConfigDictType]) -> None: if isinstance(value, _SentinelClass): return self._data = value def get(self) -> Union[ConfigDictType, Any]: if isinstance(self._data, _SentinelClass): if isinstance(self.fallback, _SentinelClass): raise ValueError("Configuration Provider not initialized") return self.fallback return self._data def reset(self) -> None: raise NotImplementedError() def __getattr__(self, name: str) -> "_ConfigurationItem": if name in ("_data", "_override", "fallback"): raise AttributeError() return _ConfigurationItem(config=self, path=(name,)) def __getitem__(self, key: PathItemType) -> "_ConfigurationItem": return _ConfigurationItem(config=self, path=(key,)) def __repr__(self) -> str: return f"Configuration(data={self._data}, fallback={self.fallback})" class _ConfigurationItem(Provider[Any]): STATE_FIELDS = Provider.STATE_FIELDS + ("_config", "_path") def __init__(self, config: Configuration, path: Tuple[PathItemType, ...],) -> None: super().__init__() self._config = config self._path = path def set(self, value: Any) -> None: if isinstance(value, _SentinelClass): return _cursor = self._config.get() for i in self._path[:-1]: if isinstance(i, Provider): i = i.get() _next: Union[_SentinelClass, Dict[Any, Any]] = _cursor.get(i, sentinel) if isinstance(_next, _SentinelClass): _next = dict() _cursor[i] = _next _cursor = _next last_i = self._path[-1] if isinstance(last_i, Provider): last_i = last_i.get() _cursor[last_i] = value def get(self) -> Any: _cursor = self._config.get() if ( not isinstance(self._config.fallback, _SentinelClass) and _cursor is self._config.fallback ): return self._config.fallback for i in self._path: if isinstance(i, Provider): i = i.get() _cursor = _cursor[i] return _cursor def reset(self) -> None: raise NotImplementedError() def __getattr__(self, name: str) -> "_ConfigurationItem": if name in ("_config", "_path", "_override"): raise AttributeError() return type(self)(config=self._config, path=self._path + (name,)) def __getitem__(self, key: PathItemType) -> "_ConfigurationItem": return type(self)(config=self._config, path=self._path + (key,)) def __repr__(self) -> str: return f"_ConfigurationItem(_config={self._config._data}, _path={self._path})"
simple_di/providers.py
import importlib from types import LambdaType, ModuleType from typing import Any from typing import Callable as CallableType from typing import Dict, Tuple, Union from simple_di import ( VT, Provider, _inject_args, _inject_kwargs, _SentinelClass, inject, sentinel, ) __all__ = [ "Static", "Callable", "MemoizedCallable", "Factory", "SingletonFactory", "Configuration", ] class Static(Provider[VT]): """ provider that returns static values """ STATE_FIELDS = Provider.STATE_FIELDS + ("_value",) def __init__(self, value: VT): super().__init__() self._value = value def _provide(self) -> VT: return self._value def _probe_unique_name(module: ModuleType, origin_name: str) -> str: name = "__simple_di_" + origin_name.replace(".", "_").replace("<lambda>", "lambda") num = 0 while hasattr(module, f"{name}{num or ''}"): num += 1 return f"{name}{num or ''}" def _patch_anonymous(func: Any) -> None: module_name = func.__module__ origin_name = func.__qualname__ module = importlib.import_module(module_name) name = _probe_unique_name(module, origin_name) func.__qualname__ = name func.__name__ = name setattr(module, name, func) class Factory(Provider[VT]): """ provider that returns the result of a callable """ STATE_FIELDS = Provider.STATE_FIELDS + ( "_args", "_kwargs", "_func", "_chain_inject", ) def __init__(self, func: CallableType[..., VT], *args: Any, **kwargs: Any) -> None: super().__init__() self._args = args self._kwargs = kwargs self._chain_inject = False if isinstance(func, classmethod): raise TypeError("Factory as decorator only supports static methods") if isinstance(func, LambdaType): _patch_anonymous(func) if isinstance(func, staticmethod): self._chain_inject = True func = func.__func__ _patch_anonymous(func) self._func = func def _provide(self) -> VT: if self._chain_inject: return inject(self._func)( *_inject_args(self._args), **_inject_kwargs(self._kwargs) ) else: return self._func(*_inject_args(self._args), **_inject_kwargs(self._kwargs)) class SingletonFactory(Factory[VT]): """ provider that returns the result of a callable, but memorize the returns. """ STATE_FIELDS = Factory.STATE_FIELDS + ("_cache",) def __init__(self, func: CallableType[..., VT], *args: Any, **kwargs: Any) -> None: super().__init__(func, *args, **kwargs) self._cache: Union[_SentinelClass, VT] = sentinel def _provide(self) -> VT: if not isinstance(self._cache, _SentinelClass): return self._cache value = super()._provide() self._cache = value return value Callable = Factory MemoizedCallable = SingletonFactory ConfigDictType = Dict[Union[str, int], Any] PathItemType = Union[int, str, Provider[int], Provider[str]] class Configuration(Provider[ConfigDictType]): """ special provider that reflects the structure of a configuration dictionary. """ STATE_FIELDS = Provider.STATE_FIELDS + ("_data", "fallback") def __init__( self, data: Union[_SentinelClass, ConfigDictType] = sentinel, fallback: Any = sentinel, ) -> None: super().__init__() self._data = data self.fallback = fallback def set(self, value: Union[_SentinelClass, ConfigDictType]) -> None: if isinstance(value, _SentinelClass): return self._data = value def get(self) -> Union[ConfigDictType, Any]: if isinstance(self._data, _SentinelClass): if isinstance(self.fallback, _SentinelClass): raise ValueError("Configuration Provider not initialized") return self.fallback return self._data def reset(self) -> None: raise NotImplementedError() def __getattr__(self, name: str) -> "_ConfigurationItem": if name in ("_data", "_override", "fallback"): raise AttributeError() return _ConfigurationItem(config=self, path=(name,)) def __getitem__(self, key: PathItemType) -> "_ConfigurationItem": return _ConfigurationItem(config=self, path=(key,)) def __repr__(self) -> str: return f"Configuration(data={self._data}, fallback={self.fallback})" class _ConfigurationItem(Provider[Any]): STATE_FIELDS = Provider.STATE_FIELDS + ("_config", "_path") def __init__(self, config: Configuration, path: Tuple[PathItemType, ...],) -> None: super().__init__() self._config = config self._path = path def set(self, value: Any) -> None: if isinstance(value, _SentinelClass): return _cursor = self._config.get() for i in self._path[:-1]: if isinstance(i, Provider): i = i.get() _next: Union[_SentinelClass, Dict[Any, Any]] = _cursor.get(i, sentinel) if isinstance(_next, _SentinelClass): _next = dict() _cursor[i] = _next _cursor = _next last_i = self._path[-1] if isinstance(last_i, Provider): last_i = last_i.get() _cursor[last_i] = value def get(self) -> Any: _cursor = self._config.get() if ( not isinstance(self._config.fallback, _SentinelClass) and _cursor is self._config.fallback ): return self._config.fallback for i in self._path: if isinstance(i, Provider): i = i.get() _cursor = _cursor[i] return _cursor def reset(self) -> None: raise NotImplementedError() def __getattr__(self, name: str) -> "_ConfigurationItem": if name in ("_config", "_path", "_override"): raise AttributeError() return type(self)(config=self._config, path=self._path + (name,)) def __getitem__(self, key: PathItemType) -> "_ConfigurationItem": return type(self)(config=self._config, path=self._path + (key,)) def __repr__(self) -> str: return f"_ConfigurationItem(_config={self._config._data}, _path={self._path})"
0.813794
0.208803
import numpy as np import vel.api.base as base import vel.util.intepolate as interp from vel.api import BatchInfo, EpochInfo, TrainingInfo class CycleCallback(base.Callback): """ A callback that manages setting the proper learning rate """ def __init__(self, optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, init_iter=0, init_lr=0, interpolate='linear'): self.max_lr = max_lr self.min_lr = min_lr self.cycles = cycles self.cycle_len = cycle_len self.cycle_mult = cycle_mult self.init_iter = init_iter self.init_lr = init_lr if cycle_mult > 1: self.epochs = self.cycle_len * (self.cycle_mult ** self.cycles - 1) // (self.cycle_mult - 1) else: self.epochs = self.cycle_mult * self.cycles self.optimizer = optimizer self.interpolate = interpolate # self.current_cycle = None self.cycle_dict, self.cycle_lengths, self.cycle_starts = self._init_cycle_dict() def _init_cycle_dict(self): """ Populate a cycle dict """ dict_arr = np.zeros(self.epochs, dtype=int) length_arr = np.zeros(self.epochs, dtype=int) start_arr = np.zeros(self.epochs, dtype=int) c_len = self.cycle_len idx = 0 for i in range(self.cycles): current_start = idx for j in range(c_len): dict_arr[idx] = i length_arr[idx] = c_len start_arr[idx] = current_start idx += 1 c_len *= self.cycle_mult return dict_arr, length_arr, start_arr def on_batch_begin(self, batch_info: BatchInfo): """ Set proper learning rate """ cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1] cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1] numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number denominator = cycle_length * batch_info.batches_per_epoch interpolation_number = numerator / denominator if cycle_start == 0 and numerator < self.init_iter: lr = self.init_lr else: if isinstance(self.max_lr, list): lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)] else: lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate) self.set_lr(lr) def set_lr(self, lr): """ Set a learning rate for the optimizer """ if isinstance(lr, list): for group_lr, param_group in zip(lr, self.optimizer.param_groups): param_group['lr'] = group_lr else: for param_group in self.optimizer.param_groups: param_group['lr'] = lr class CyclePhase(base.TrainPhase): """ Most generic phase of training """ def __init__(self, optimizer_factory, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, interpolate='linear', init_lr=0, init_iter=0, freeze=False): self.max_lr = max_lr self.min_lr = min_lr self.cycles = cycles self.cycle_len = cycle_len self.cycle_mult = cycle_mult if cycle_mult > 1: self.epochs = self.cycle_len * (self.cycle_mult ** self.cycles - 1) // (self.cycle_mult - 1) else: self.epochs = self.cycle_mult * self.cycles self.interpolate = interpolate self.init_iter = init_iter self.init_lr = init_lr self.optimizer_factory = optimizer_factory self.freeze = freeze self._optimizer_instance = None self._source = None self.special_callback = None @property def number_of_epochs(self) -> int: return self.epochs def set_up_phase(self, training_info, model, source): """ Prepare the phase for learning """ # To parameter groups handles properly filtering parameters that don't require gradient self._optimizer_instance = self.optimizer_factory.instantiate(model) self._source = source self.special_callback = CycleCallback( self._optimizer_instance, max_lr=self.max_lr, min_lr=self.min_lr, cycles=self.cycles, cycle_len=self.cycle_len, cycle_mult=self.cycle_mult, interpolate=self.interpolate, init_iter=self.init_iter, init_lr=self.init_lr ) return self._optimizer_instance def epoch_info(self, training_info: TrainingInfo, global_idx: int, local_idx: int) -> EpochInfo: """ Create Epoch info """ return EpochInfo( training_info=training_info, global_epoch_idx=global_idx, local_epoch_idx=local_idx, batches_per_epoch=self._source.train_iterations_per_epoch(), optimizer=self._optimizer_instance, # Add special callback for this epoch callbacks=[self.special_callback] + training_info.callbacks ) def execute_epoch(self, epoch_info, learner): """ Prepare the phase for learning """ learner.run_epoch(epoch_info, self._source) def create(optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, interpolate='linear', init_lr=0, init_iter=0): """ Vel creation function """ return CyclePhase( max_lr=max_lr, min_lr=min_lr, cycles=cycles, cycle_len=cycle_len, cycle_mult=cycle_mult, interpolate=interpolate, optimizer_factory=optimizer, init_lr=init_lr, init_iter=init_iter, )
vel/phase/cycle.py
import numpy as np import vel.api.base as base import vel.util.intepolate as interp from vel.api import BatchInfo, EpochInfo, TrainingInfo class CycleCallback(base.Callback): """ A callback that manages setting the proper learning rate """ def __init__(self, optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, init_iter=0, init_lr=0, interpolate='linear'): self.max_lr = max_lr self.min_lr = min_lr self.cycles = cycles self.cycle_len = cycle_len self.cycle_mult = cycle_mult self.init_iter = init_iter self.init_lr = init_lr if cycle_mult > 1: self.epochs = self.cycle_len * (self.cycle_mult ** self.cycles - 1) // (self.cycle_mult - 1) else: self.epochs = self.cycle_mult * self.cycles self.optimizer = optimizer self.interpolate = interpolate # self.current_cycle = None self.cycle_dict, self.cycle_lengths, self.cycle_starts = self._init_cycle_dict() def _init_cycle_dict(self): """ Populate a cycle dict """ dict_arr = np.zeros(self.epochs, dtype=int) length_arr = np.zeros(self.epochs, dtype=int) start_arr = np.zeros(self.epochs, dtype=int) c_len = self.cycle_len idx = 0 for i in range(self.cycles): current_start = idx for j in range(c_len): dict_arr[idx] = i length_arr[idx] = c_len start_arr[idx] = current_start idx += 1 c_len *= self.cycle_mult return dict_arr, length_arr, start_arr def on_batch_begin(self, batch_info: BatchInfo): """ Set proper learning rate """ cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1] cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1] numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number denominator = cycle_length * batch_info.batches_per_epoch interpolation_number = numerator / denominator if cycle_start == 0 and numerator < self.init_iter: lr = self.init_lr else: if isinstance(self.max_lr, list): lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)] else: lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate) self.set_lr(lr) def set_lr(self, lr): """ Set a learning rate for the optimizer """ if isinstance(lr, list): for group_lr, param_group in zip(lr, self.optimizer.param_groups): param_group['lr'] = group_lr else: for param_group in self.optimizer.param_groups: param_group['lr'] = lr class CyclePhase(base.TrainPhase): """ Most generic phase of training """ def __init__(self, optimizer_factory, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, interpolate='linear', init_lr=0, init_iter=0, freeze=False): self.max_lr = max_lr self.min_lr = min_lr self.cycles = cycles self.cycle_len = cycle_len self.cycle_mult = cycle_mult if cycle_mult > 1: self.epochs = self.cycle_len * (self.cycle_mult ** self.cycles - 1) // (self.cycle_mult - 1) else: self.epochs = self.cycle_mult * self.cycles self.interpolate = interpolate self.init_iter = init_iter self.init_lr = init_lr self.optimizer_factory = optimizer_factory self.freeze = freeze self._optimizer_instance = None self._source = None self.special_callback = None @property def number_of_epochs(self) -> int: return self.epochs def set_up_phase(self, training_info, model, source): """ Prepare the phase for learning """ # To parameter groups handles properly filtering parameters that don't require gradient self._optimizer_instance = self.optimizer_factory.instantiate(model) self._source = source self.special_callback = CycleCallback( self._optimizer_instance, max_lr=self.max_lr, min_lr=self.min_lr, cycles=self.cycles, cycle_len=self.cycle_len, cycle_mult=self.cycle_mult, interpolate=self.interpolate, init_iter=self.init_iter, init_lr=self.init_lr ) return self._optimizer_instance def epoch_info(self, training_info: TrainingInfo, global_idx: int, local_idx: int) -> EpochInfo: """ Create Epoch info """ return EpochInfo( training_info=training_info, global_epoch_idx=global_idx, local_epoch_idx=local_idx, batches_per_epoch=self._source.train_iterations_per_epoch(), optimizer=self._optimizer_instance, # Add special callback for this epoch callbacks=[self.special_callback] + training_info.callbacks ) def execute_epoch(self, epoch_info, learner): """ Prepare the phase for learning """ learner.run_epoch(epoch_info, self._source) def create(optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, interpolate='linear', init_lr=0, init_iter=0): """ Vel creation function """ return CyclePhase( max_lr=max_lr, min_lr=min_lr, cycles=cycles, cycle_len=cycle_len, cycle_mult=cycle_mult, interpolate=interpolate, optimizer_factory=optimizer, init_lr=init_lr, init_iter=init_iter, )
0.775902
0.150216
import sys, os import importlib import re import logging import requests from os import listdir from subprocess import Popen from urllib.parse import urljoin from threading import Thread, Lock from distutils.version import LooseVersion from bs4 import BeautifulSoup from artifactory import ArtifactoryPath __version__ = "0.1.2" class ArtifactoryParser: """ The class that implements searching, downloading and versioning of packages in a remote Artifactory repository. Supports the following types of artifacts: .py, .whl. It is also capable at parsing original PyPI repositories when html parser is used, really don't recommend to do it though, due to it's slowness :) """ def __init__(self, max_nesting_level = 8, max_threads_num = 16): # Define limiters self.max_nesting_level = max_nesting_level self.max_threads_num = max_threads_num # Pre-compile most used regexp self.re_find_folder = re.compile(r'.*/$') self.re_find_backs = re.compile(r'^(../.*|/*|\?.*|#.*)$') self.re_find_version = re.compile(r'.+?[>=<_-]{1,2}(?P<version>(\d+)\.?(\d+)\.?(\d+)?).*') self.lock = Lock() self.module = '' self.login = '' self.password = '' self.opener = None def get_module(self, req_module, url, tags=[], login='', password='', searcher='dohq'): """ This huge method checks whether your package is already insatlled and initiates remote reposytory parsing otherwise. After that it validates the results, downloads and imports your package. :param req_module (str): exact name of the required module, it also may contain a few version checks in standart python requirements format :param url (str): repository address where the module will be searched for :param tags (list): to avoid collision you can pass this attribute, whether it is a folder name or platform tags, anything will be useful :param login (str): repository login :param password (str): repository password :param searcher (str): defaul searcher to be used (supports 'dohq'(default) and 'html') :return loaded module """ #=============================================================== # Some setting up actions #=============================================================== # Check for empty module name if not req_module: logging.error('Module name is missing') return # Check for empty urls if not url: logging.error('Empty url is not acceptable') return # Make sure that our link ends with trailing slash if not url.endswith('/'): url += '/' # Define the searcher if searcher == 'html': self.searcher = _html_search(Base=self) elif searcher == 'dohq': self.searcher = _dohq_search(Base=self) else: logging.warn(f'Unknown searcher {searcher}, setting to dohq by default') self.searcher = _dohq_search(Base=self) # Extract info from 'req_module' match = [x for x in re.split('([>=<]+)', req_module) if x] if match[0]: self.module = match[0] else: logging.error('Module name parsing error') return self.conditions = [] self.target_versions = [] for i in range(1, len(match), 2): self.conditions.append(match[i]) if len(match) > i+1: self.target_versions.append(match[i+1]) # Check if requested module is not installed on the system is_not_installed = importlib.util.find_spec(self.module) is None #=============================================================== # In case module is not installed, scan PWD #=============================================================== if is_not_installed: # Check if a file with module's name exists in PWD valid_packages = self.__check_for_requested_packages( { i: f for i, f in enumerate(listdir('.')) if f.endswith('.py')} ) if valid_packages: package_name = valid_packages[-1][1] package_version = valid_packages[-1][2] is_not_installed = False #=============================================================== # In case if file with given module name doesn't exist #=============================================================== if is_not_installed: # Receive packages list packages = {} packages = self.searcher.search(url, login=login, password=password) if not packages: logging.error('No packages found, check if URL and credentials are valid') return #=============================================================== # Getting the exact module name and version #=============================================================== # Iterate through the packages valid_packages = self.__check_for_requested_packages(packages) # Collision check if there are any if len(valid_packages) > 1: logging.warn('More then one package satisfies your requirements') if tags: valid_packages = [pkg for pkg in valid_packages if all(tag in pkg[0] for tag in tags)] else: logging.error("We couldn't resolve the collision, please, provide some tags") # Get package's name and link for last valid match if valid_packages: package_url = valid_packages[-1][0] package_name = valid_packages[-1][1] package_version = valid_packages[-1][2] else: logging.error('Required package is not found') return #=============================================================== # Installation process #=============================================================== # Retrieve the package file (whether .py or .whl) try: response = requests.get(package_url, auth=(login, password)) if response.status_code == 200: with open(package_name, 'wb') as out: out.write(response.content) response.close() else: logging.error(f'Server response code: {response.status_code}') response.close() return None except Exception: logging.error('Unable to download package') return None # Install and load pip packages if any if package_name.endswith('.whl'): pipe = Popen([sys.executable, '-m', 'pip', 'install', package_name]) out = pipe.communicate() # Remove package installer os.remove(package_name) if pipe.returncode == 0: try: # Load module by self.module # Potentially naming error can appear <<<----------------- new_module = importlib.import_module(self.module) return new_module except Exception: logging.error('Module was successfully installed but cannot be loaded') return None else: logging.error("Module installation didn't succeed") return #=============================================================== # Load module from specs #=============================================================== # Change module name in order to avoid naming errors self.module = re.split(f'[_-]{package_version}|\.', package_name)[0] # If we are loading a protobuf file, rename the module to avoid errors during sequential import if package_name.endswith('pb2.py') and not self.module.endswith('_pb2'): self.module += '_pb2' spec = importlib.util.spec_from_file_location(self.module, package_name) new_module = importlib.util.module_from_spec(spec) sys.modules[self.module] = new_module new_module.__version__ = package_version try: spec.loader.exec_module(new_module) except Exception: del sys.modules[self.module] new_module = None logging.error('Failed to load module from file') else: try: new_module = importlib.import_module(self.module) except Exception: logging.error('Failed to load existing module') return None return new_module def __check_for_requested_packages(self, packages): """ This method separates module names from module versions and returns only those modules that are matching user requirements :param packages (dict): must satisfy the model {'module link': 'module name')} :return list of packages formatted like [('link', 'name', 'version')] """ valid_packages = [] for (key, value) in packages.items(): # If package is found, get it's link and name if self.module in value: # Extract package version match = self.re_find_version.match(value) # In case if version is in a package name if match: version = match.group('version') else: version = None __satisfy = True # Check if we satisfy all given requirements for __cond, __vers in zip(self.conditions, self.target_versions): if not eval( f'v1{__cond}v2', {'__builtins__': {},'v1': LooseVersion(version if version else '0'), 'v2': LooseVersion(__vers)}, {} ): __satisfy = False if __satisfy: valid_packages.append((key, value, version)) return valid_packages def search_packages_dohq(self, url, dictionary={}, **kwargs): """ This method parses the remote artifactory repository structure and chooses those files that are having the extension .py or .whl. Uses dohq-artifactory API. :param url (str): remote artifactory repository address :param dictionary (dict): dict where will be passed the result :**kwargs may contain 'login', 'password' :return dict formatted like {'module link', 'module name'} """ if 'login' in kwargs and 'password' in kwargs: path = ArtifactoryPath(url, auth=(kwargs['login'], kwargs['password'])) else: path = ArtifactoryPath(url, auth=(self.login, self.password)) for p in path.glob('**/*.*'): link = str(p) if link.endswith('.py') or link.endswith('.whl'): dictionary.update({link: link.split('/')[-1]}) return dictionary def __parse_html_from_string(self, url): """ Parses the html of given link with BeautifulSoup, in case of exceptions returns empty BS. :param url (str): link to be parsed :return BeautifulSoup of downloaded html page """ # Request the page and wrap it with BeautifulSoup response = requests.get(url, auth=(self.login, self.password)) if response.status_code == 200: page = str(response.content) else: logging.error(f'HTTP request error: status code {response.status_code}') page = '' response.close() content = BeautifulSoup(page, 'html.parser') return content def search_packages_html(self, url, dictionary={}, **kwargs): """ Similarly to previous method, this one parses remote artifactory repository structure and chooses those files that are having the extension .py or .whl. Uses html parser, multi-threading and regexp :param url (str): remote artifactory repository address :param dictionary (dict): dict where will be passed the result :**kwargs may contain 'login' (str), 'password' (str) :return dict formatted like {'module link', 'module name'} """ #=============================================================== # Retrieving the information from kwargs #=============================================================== # Update nesting level if given if 'nesting_level' in kwargs: kwargs['nesting_level'] += 1 else: # If nesting level is not defined, define it kwargs.update({'nesting_level': 0}) # Retrieve login and password from kwargs if any were given if 'login' in kwargs and 'password' in kwargs: self.login = kwargs['login'] self.password = kwargs['password'] del kwargs['login'] del kwargs['password'] soup = self.__parse_html_from_string(url) #=============================================================== # Walking through all the links on the page #=============================================================== # Define array of scan-threads threads = [] for link in soup.find_all('a', href=True): if not self.re_find_backs.match(link['href']): # Next line is debug only<<<---------------------------- #print(link.text)#, link['href']) # Check if this is a folder link if self.re_find_folder.match(link['href']): #=============================================================== # In case if link is a folder #=============================================================== # Make sure that nesting level is lesser then max if kwargs['nesting_level'] < self.max_nesting_level: # If link is absolute, do not concat it with url if link['href'].startswith('http'): threads.append(Thread( target=self.search_packages_html, args=[link['href'], dictionary], kwargs=kwargs )) else: threads.append(Thread( target=self.search_packages_html, args=[urljoin(url, link['href']), dictionary], kwargs=kwargs )) # Make sure we didn't exceed max number of threads if len(threads) > self.max_threads_num: [t.start() for t in threads] [t.join() for t in threads] threads = [] #=============================================================== # In case if link is a file #=============================================================== else: # Make sure that we are only searching for .py and .whl files if link.text.endswith('.py') or link.text.endswith('.whl'): # If link is absolute, do not concat it with url self.lock.acquire() if link['href'].startswith('http://') or link['href'].startswith('https://'): dictionary.update({link['href'] : link.text}) else: dictionary.update({urljoin(url, link['href']) : link.text}) self.lock.release() #=============================================================== # Process finishing #=============================================================== # Await till all sub-directories scans are finished [t.start() for t in threads] [t.join() for t in threads] return dictionary class _dohq_search(): """ Supporting class that standartizes the call to dohq search of a Base class :param Base (ArtifactoryParser): object that has search_packages_dohq method """ def __init__(self, Base): self.Base = Base def search(self, url, dictionary={}, **kwargs): return self.Base.search_packages_dohq(url, dictionary, **kwargs) class _html_search(): """ Supporting class that standartizes the call to html search of a Base class :param Base (ArtifactoryParser): object that has search_packages_html method """ def __init__(self, Base): self.Base = Base def search(self, url, dictionary={}, **kwargs): return self.Base.search_packages_html(url, dictionary, **kwargs)
jfrog2pypi.py
import sys, os import importlib import re import logging import requests from os import listdir from subprocess import Popen from urllib.parse import urljoin from threading import Thread, Lock from distutils.version import LooseVersion from bs4 import BeautifulSoup from artifactory import ArtifactoryPath __version__ = "0.1.2" class ArtifactoryParser: """ The class that implements searching, downloading and versioning of packages in a remote Artifactory repository. Supports the following types of artifacts: .py, .whl. It is also capable at parsing original PyPI repositories when html parser is used, really don't recommend to do it though, due to it's slowness :) """ def __init__(self, max_nesting_level = 8, max_threads_num = 16): # Define limiters self.max_nesting_level = max_nesting_level self.max_threads_num = max_threads_num # Pre-compile most used regexp self.re_find_folder = re.compile(r'.*/$') self.re_find_backs = re.compile(r'^(../.*|/*|\?.*|#.*)$') self.re_find_version = re.compile(r'.+?[>=<_-]{1,2}(?P<version>(\d+)\.?(\d+)\.?(\d+)?).*') self.lock = Lock() self.module = '' self.login = '' self.password = '' self.opener = None def get_module(self, req_module, url, tags=[], login='', password='', searcher='dohq'): """ This huge method checks whether your package is already insatlled and initiates remote reposytory parsing otherwise. After that it validates the results, downloads and imports your package. :param req_module (str): exact name of the required module, it also may contain a few version checks in standart python requirements format :param url (str): repository address where the module will be searched for :param tags (list): to avoid collision you can pass this attribute, whether it is a folder name or platform tags, anything will be useful :param login (str): repository login :param password (str): repository password :param searcher (str): defaul searcher to be used (supports 'dohq'(default) and 'html') :return loaded module """ #=============================================================== # Some setting up actions #=============================================================== # Check for empty module name if not req_module: logging.error('Module name is missing') return # Check for empty urls if not url: logging.error('Empty url is not acceptable') return # Make sure that our link ends with trailing slash if not url.endswith('/'): url += '/' # Define the searcher if searcher == 'html': self.searcher = _html_search(Base=self) elif searcher == 'dohq': self.searcher = _dohq_search(Base=self) else: logging.warn(f'Unknown searcher {searcher}, setting to dohq by default') self.searcher = _dohq_search(Base=self) # Extract info from 'req_module' match = [x for x in re.split('([>=<]+)', req_module) if x] if match[0]: self.module = match[0] else: logging.error('Module name parsing error') return self.conditions = [] self.target_versions = [] for i in range(1, len(match), 2): self.conditions.append(match[i]) if len(match) > i+1: self.target_versions.append(match[i+1]) # Check if requested module is not installed on the system is_not_installed = importlib.util.find_spec(self.module) is None #=============================================================== # In case module is not installed, scan PWD #=============================================================== if is_not_installed: # Check if a file with module's name exists in PWD valid_packages = self.__check_for_requested_packages( { i: f for i, f in enumerate(listdir('.')) if f.endswith('.py')} ) if valid_packages: package_name = valid_packages[-1][1] package_version = valid_packages[-1][2] is_not_installed = False #=============================================================== # In case if file with given module name doesn't exist #=============================================================== if is_not_installed: # Receive packages list packages = {} packages = self.searcher.search(url, login=login, password=password) if not packages: logging.error('No packages found, check if URL and credentials are valid') return #=============================================================== # Getting the exact module name and version #=============================================================== # Iterate through the packages valid_packages = self.__check_for_requested_packages(packages) # Collision check if there are any if len(valid_packages) > 1: logging.warn('More then one package satisfies your requirements') if tags: valid_packages = [pkg for pkg in valid_packages if all(tag in pkg[0] for tag in tags)] else: logging.error("We couldn't resolve the collision, please, provide some tags") # Get package's name and link for last valid match if valid_packages: package_url = valid_packages[-1][0] package_name = valid_packages[-1][1] package_version = valid_packages[-1][2] else: logging.error('Required package is not found') return #=============================================================== # Installation process #=============================================================== # Retrieve the package file (whether .py or .whl) try: response = requests.get(package_url, auth=(login, password)) if response.status_code == 200: with open(package_name, 'wb') as out: out.write(response.content) response.close() else: logging.error(f'Server response code: {response.status_code}') response.close() return None except Exception: logging.error('Unable to download package') return None # Install and load pip packages if any if package_name.endswith('.whl'): pipe = Popen([sys.executable, '-m', 'pip', 'install', package_name]) out = pipe.communicate() # Remove package installer os.remove(package_name) if pipe.returncode == 0: try: # Load module by self.module # Potentially naming error can appear <<<----------------- new_module = importlib.import_module(self.module) return new_module except Exception: logging.error('Module was successfully installed but cannot be loaded') return None else: logging.error("Module installation didn't succeed") return #=============================================================== # Load module from specs #=============================================================== # Change module name in order to avoid naming errors self.module = re.split(f'[_-]{package_version}|\.', package_name)[0] # If we are loading a protobuf file, rename the module to avoid errors during sequential import if package_name.endswith('pb2.py') and not self.module.endswith('_pb2'): self.module += '_pb2' spec = importlib.util.spec_from_file_location(self.module, package_name) new_module = importlib.util.module_from_spec(spec) sys.modules[self.module] = new_module new_module.__version__ = package_version try: spec.loader.exec_module(new_module) except Exception: del sys.modules[self.module] new_module = None logging.error('Failed to load module from file') else: try: new_module = importlib.import_module(self.module) except Exception: logging.error('Failed to load existing module') return None return new_module def __check_for_requested_packages(self, packages): """ This method separates module names from module versions and returns only those modules that are matching user requirements :param packages (dict): must satisfy the model {'module link': 'module name')} :return list of packages formatted like [('link', 'name', 'version')] """ valid_packages = [] for (key, value) in packages.items(): # If package is found, get it's link and name if self.module in value: # Extract package version match = self.re_find_version.match(value) # In case if version is in a package name if match: version = match.group('version') else: version = None __satisfy = True # Check if we satisfy all given requirements for __cond, __vers in zip(self.conditions, self.target_versions): if not eval( f'v1{__cond}v2', {'__builtins__': {},'v1': LooseVersion(version if version else '0'), 'v2': LooseVersion(__vers)}, {} ): __satisfy = False if __satisfy: valid_packages.append((key, value, version)) return valid_packages def search_packages_dohq(self, url, dictionary={}, **kwargs): """ This method parses the remote artifactory repository structure and chooses those files that are having the extension .py or .whl. Uses dohq-artifactory API. :param url (str): remote artifactory repository address :param dictionary (dict): dict where will be passed the result :**kwargs may contain 'login', 'password' :return dict formatted like {'module link', 'module name'} """ if 'login' in kwargs and 'password' in kwargs: path = ArtifactoryPath(url, auth=(kwargs['login'], kwargs['password'])) else: path = ArtifactoryPath(url, auth=(self.login, self.password)) for p in path.glob('**/*.*'): link = str(p) if link.endswith('.py') or link.endswith('.whl'): dictionary.update({link: link.split('/')[-1]}) return dictionary def __parse_html_from_string(self, url): """ Parses the html of given link with BeautifulSoup, in case of exceptions returns empty BS. :param url (str): link to be parsed :return BeautifulSoup of downloaded html page """ # Request the page and wrap it with BeautifulSoup response = requests.get(url, auth=(self.login, self.password)) if response.status_code == 200: page = str(response.content) else: logging.error(f'HTTP request error: status code {response.status_code}') page = '' response.close() content = BeautifulSoup(page, 'html.parser') return content def search_packages_html(self, url, dictionary={}, **kwargs): """ Similarly to previous method, this one parses remote artifactory repository structure and chooses those files that are having the extension .py or .whl. Uses html parser, multi-threading and regexp :param url (str): remote artifactory repository address :param dictionary (dict): dict where will be passed the result :**kwargs may contain 'login' (str), 'password' (str) :return dict formatted like {'module link', 'module name'} """ #=============================================================== # Retrieving the information from kwargs #=============================================================== # Update nesting level if given if 'nesting_level' in kwargs: kwargs['nesting_level'] += 1 else: # If nesting level is not defined, define it kwargs.update({'nesting_level': 0}) # Retrieve login and password from kwargs if any were given if 'login' in kwargs and 'password' in kwargs: self.login = kwargs['login'] self.password = kwargs['password'] del kwargs['login'] del kwargs['password'] soup = self.__parse_html_from_string(url) #=============================================================== # Walking through all the links on the page #=============================================================== # Define array of scan-threads threads = [] for link in soup.find_all('a', href=True): if not self.re_find_backs.match(link['href']): # Next line is debug only<<<---------------------------- #print(link.text)#, link['href']) # Check if this is a folder link if self.re_find_folder.match(link['href']): #=============================================================== # In case if link is a folder #=============================================================== # Make sure that nesting level is lesser then max if kwargs['nesting_level'] < self.max_nesting_level: # If link is absolute, do not concat it with url if link['href'].startswith('http'): threads.append(Thread( target=self.search_packages_html, args=[link['href'], dictionary], kwargs=kwargs )) else: threads.append(Thread( target=self.search_packages_html, args=[urljoin(url, link['href']), dictionary], kwargs=kwargs )) # Make sure we didn't exceed max number of threads if len(threads) > self.max_threads_num: [t.start() for t in threads] [t.join() for t in threads] threads = [] #=============================================================== # In case if link is a file #=============================================================== else: # Make sure that we are only searching for .py and .whl files if link.text.endswith('.py') or link.text.endswith('.whl'): # If link is absolute, do not concat it with url self.lock.acquire() if link['href'].startswith('http://') or link['href'].startswith('https://'): dictionary.update({link['href'] : link.text}) else: dictionary.update({urljoin(url, link['href']) : link.text}) self.lock.release() #=============================================================== # Process finishing #=============================================================== # Await till all sub-directories scans are finished [t.start() for t in threads] [t.join() for t in threads] return dictionary class _dohq_search(): """ Supporting class that standartizes the call to dohq search of a Base class :param Base (ArtifactoryParser): object that has search_packages_dohq method """ def __init__(self, Base): self.Base = Base def search(self, url, dictionary={}, **kwargs): return self.Base.search_packages_dohq(url, dictionary, **kwargs) class _html_search(): """ Supporting class that standartizes the call to html search of a Base class :param Base (ArtifactoryParser): object that has search_packages_html method """ def __init__(self, Base): self.Base = Base def search(self, url, dictionary={}, **kwargs): return self.Base.search_packages_html(url, dictionary, **kwargs)
0.283285
0.09947
from tempest.api.identity import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators class PoliciesTestJSON(base.BaseIdentityV3AdminTest): def _delete_policy(self, policy_id): self.policies_client.delete_policy(policy_id) @decorators.idempotent_id('1a0ad286-2d06-4123-ab0d-728893a76201') def test_list_policies(self): # Test to list policies policy_ids = list() fetched_ids = list() for _ in range(3): blob = data_utils.rand_name('BlobName') policy_type = data_utils.rand_name('PolicyType') policy = self.policies_client.create_policy( blob=blob, type=policy_type)['policy'] # Delete the Policy at the end of this method self.addCleanup(self._delete_policy, policy['id']) policy_ids.append(policy['id']) # List and Verify Policies body = self.policies_client.list_policies()['policies'] for p in body: fetched_ids.append(p['id']) missing_pols = [p for p in policy_ids if p not in fetched_ids] self.assertEmpty(missing_pols) @decorators.attr(type='smoke') @decorators.idempotent_id('e544703a-2f03-4cf2-9b0f-350782fdb0d3') def test_create_update_delete_policy(self): # Test to update policy blob = data_utils.rand_name('BlobName') policy_type = data_utils.rand_name('PolicyType') policy = self.policies_client.create_policy(blob=blob, type=policy_type)['policy'] self.addCleanup(self._delete_policy, policy['id']) self.assertIn('type', policy) self.assertIn('blob', policy) self.assertIsNotNone(policy['id']) self.assertEqual(blob, policy['blob']) self.assertEqual(policy_type, policy['type']) # Update policy update_type = data_utils.rand_name('UpdatedPolicyType') data = self.policies_client.update_policy( policy['id'], type=update_type)['policy'] self.assertIn('type', data) # Assertion for updated value with fetched value fetched_policy = self.policies_client.show_policy( policy['id'])['policy'] self.assertIn('id', fetched_policy) self.assertIn('blob', fetched_policy) self.assertIn('type', fetched_policy) self.assertEqual(fetched_policy['id'], policy['id']) self.assertEqual(fetched_policy['blob'], policy['blob']) self.assertEqual(update_type, fetched_policy['type'])
tempest/api/identity/admin/v3/test_policies.py
from tempest.api.identity import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators class PoliciesTestJSON(base.BaseIdentityV3AdminTest): def _delete_policy(self, policy_id): self.policies_client.delete_policy(policy_id) @decorators.idempotent_id('1a0ad286-2d06-4123-ab0d-728893a76201') def test_list_policies(self): # Test to list policies policy_ids = list() fetched_ids = list() for _ in range(3): blob = data_utils.rand_name('BlobName') policy_type = data_utils.rand_name('PolicyType') policy = self.policies_client.create_policy( blob=blob, type=policy_type)['policy'] # Delete the Policy at the end of this method self.addCleanup(self._delete_policy, policy['id']) policy_ids.append(policy['id']) # List and Verify Policies body = self.policies_client.list_policies()['policies'] for p in body: fetched_ids.append(p['id']) missing_pols = [p for p in policy_ids if p not in fetched_ids] self.assertEmpty(missing_pols) @decorators.attr(type='smoke') @decorators.idempotent_id('e544703a-2f03-4cf2-9b0f-350782fdb0d3') def test_create_update_delete_policy(self): # Test to update policy blob = data_utils.rand_name('BlobName') policy_type = data_utils.rand_name('PolicyType') policy = self.policies_client.create_policy(blob=blob, type=policy_type)['policy'] self.addCleanup(self._delete_policy, policy['id']) self.assertIn('type', policy) self.assertIn('blob', policy) self.assertIsNotNone(policy['id']) self.assertEqual(blob, policy['blob']) self.assertEqual(policy_type, policy['type']) # Update policy update_type = data_utils.rand_name('UpdatedPolicyType') data = self.policies_client.update_policy( policy['id'], type=update_type)['policy'] self.assertIn('type', data) # Assertion for updated value with fetched value fetched_policy = self.policies_client.show_policy( policy['id'])['policy'] self.assertIn('id', fetched_policy) self.assertIn('blob', fetched_policy) self.assertIn('type', fetched_policy) self.assertEqual(fetched_policy['id'], policy['id']) self.assertEqual(fetched_policy['blob'], policy['blob']) self.assertEqual(update_type, fetched_policy['type'])
0.489015
0.338023
import time from typing import Callable, List, Optional, Sequence, cast import hydra import numpy as np import omegaconf import torch import torch.distributions import mbrl.models import mbrl.types import mbrl.util.math from .core import Agent, complete_agent_cfg class Optimizer: def __init__(self): pass def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: """Runs optimization. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): initial solution, if necessary. Returns: (torch.Tensor): the best solution found. """ pass class CEMOptimizer(Optimizer): """Implements the Cross-Entropy Method optimization algorithm. A good description of CEM [1] can be found at https://arxiv.org/pdf/2008.06389.pdf. This code implements the version described in Section 2.1, labeled CEM_PETS (but note that the shift-initialization between planning time steps is handled outside of this class by TrajectoryOptimizer). This implementation also returns the best solution found as opposed to the mean of the last generation. Args: num_iterations (int): the number of iterations (generations) to perform. elite_ratio (float): the proportion of the population that will be kept as elite (rounds up). population_size (int): the size of the population. lower_bound (sequence of floats): the lower bound for the optimization variables. upper_bound (sequence of floats): the upper bound for the optimization variables. alpha (float): momentum term. device (torch.device): device where computations will be performed. return_mean_elites (bool): if ``True`` returns the mean of the elites of the last iteration. Otherwise, it returns the max solution found over all iterations. [1] <NAME> and <NAME>. "The cross-entropy method for combinatorial and continuous optimization". Methodology and Computing in Applied Probability, 1999. """ def __init__( self, num_iterations: int, elite_ratio: float, population_size: int, lower_bound: Sequence[Sequence[float]], upper_bound: Sequence[Sequence[float]], alpha: float, device: torch.device, return_mean_elites: bool = False, ): super().__init__() self.num_iterations = num_iterations self.elite_ratio = elite_ratio self.population_size = population_size self.elite_num = np.ceil(self.population_size * self.elite_ratio).astype( np.int32 ) self.lower_bound = torch.tensor(lower_bound, device=device, dtype=torch.float32) self.upper_bound = torch.tensor(upper_bound, device=device, dtype=torch.float32) self.initial_var = ((self.upper_bound - self.lower_bound) ** 2) / 16 self.alpha = alpha self.return_mean_elites = return_mean_elites self.device = device def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, callback: Optional[Callable[[torch.Tensor, torch.Tensor, int], None]] = None, **kwargs, ) -> torch.Tensor: """Runs the optimization using CEM. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): initial mean for the population. Must be consistent with lower/upper bounds. callback (callable(tensor, tensor, int) -> any, optional): if given, this function will be called after every iteration, passing it as input the full population tensor, its corresponding objective function values, and the index of the current iteration. This can be used for logging and plotting purposes. Returns: (torch.Tensor): the best solution found. """ mu = x0.clone() var = self.initial_var.clone() best_solution = torch.empty_like(mu) best_value = -np.inf population = torch.zeros((self.population_size,) + x0.shape).to( device=self.device ) for i in range(self.num_iterations): lb_dist = mu - self.lower_bound ub_dist = self.upper_bound - mu mv = torch.min(torch.square(lb_dist / 2), torch.square(ub_dist / 2)) constrained_var = torch.min(mv, var) population = mbrl.util.math.truncated_normal_(population) population = population * torch.sqrt(constrained_var) + mu values = obj_fun(population) if callback is not None: callback(population, values, i) # filter out NaN values values[values.isnan()] = -1e-10 best_values, elite_idx = values.topk(self.elite_num) elite = population[elite_idx] new_mu = torch.mean(elite, dim=0) new_var = torch.var(elite, unbiased=False, dim=0) mu = self.alpha * mu + (1 - self.alpha) * new_mu var = self.alpha * var + (1 - self.alpha) * new_var if best_values[0] > best_value: best_value = best_values[0] best_solution = population[elite_idx[0]].clone() return mu if self.return_mean_elites else best_solution class MPPIOptimizer(Optimizer): """Implements the Model Predictive Path Integral optimization algorithm. A derivation of MPPI can be found at https://arxiv.org/abs/2102.09027 This version is closely related to the original TF implementation used in PDDM with some noise sampling modifications and the addition of refinement steps. Args: num_iterations (int): the number of iterations (generations) to perform. population_size (int): the size of the population. gamma (float): reward scaling term. sigma (float): noise scaling term used in action sampling. beta (float): correlation term between time steps. lower_bound (sequence of floats): the lower bound for the optimization variables. upper_bound (sequence of floats): the upper bound for the optimization variables. device (torch.device): device where computations will be performed. """ def __init__( self, num_iterations: int, population_size: int, gamma: float, sigma: float, beta: float, lower_bound: Sequence[Sequence[float]], upper_bound: Sequence[Sequence[float]], device: torch.device, ): super().__init__() self.planning_horizon = len(lower_bound) self.population_size = population_size self.action_dimension = len(lower_bound[0]) self.mean = torch.zeros( (self.planning_horizon, self.action_dimension), device=device, dtype=torch.float32, ) self.lower_bound = torch.tensor(lower_bound, device=device, dtype=torch.float32) self.upper_bound = torch.tensor(upper_bound, device=device, dtype=torch.float32) self.var = sigma ** 2 * torch.ones_like(self.lower_bound) self.beta = beta self.gamma = gamma self.refinements = num_iterations self.device = device def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, callback: Optional[Callable[[torch.Tensor, torch.Tensor, int], None]] = None, **kwargs, ) -> torch.Tensor: """Implementation of MPPI planner. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): Not required callback (callable(tensor, tensor, int) -> any, optional): if given, this function will be called after every iteration, passing it as input the full population tensor, its corresponding objective function values, and the index of the current iteration. This can be used for logging and plotting purposes. Returns: (torch.Tensor): the best solution found. """ past_action = self.mean[0] self.mean[:-1] = self.mean[1:].clone() for k in range(self.refinements): # sample noise and update constrained variances noise = torch.empty( size=( self.population_size, self.planning_horizon, self.action_dimension, ), device=self.device, ) noise = mbrl.util.math.truncated_normal_(noise) lb_dist = self.mean - self.lower_bound ub_dist = self.upper_bound - self.mean mv = torch.minimum(torch.square(lb_dist / 2), torch.square(ub_dist / 2)) constrained_var = torch.minimum(mv, self.var) population = noise.clone() * torch.sqrt(constrained_var) # smoothed actions with noise population[:, 0, :] = ( self.beta * (self.mean[0, :] + noise[:, 0, :]) + (1 - self.beta) * past_action ) for i in range(max(self.planning_horizon - 1, 0)): population[:, i + 1, :] = ( self.beta * (self.mean[i + 1] + noise[:, i + 1, :]) + (1 - self.beta) * population[:, i, :] ) # clipping actions # This should still work if the bounds between dimensions are different. population = torch.where( population > self.upper_bound, self.upper_bound, population ) population = torch.where( population < self.lower_bound, self.lower_bound, population ) values = obj_fun(population) values[values.isnan()] = -1e-10 if callback is not None: callback(population, values, k) # weight actions weights = torch.reshape( torch.exp(self.gamma * (values - values.max())), (self.population_size, 1, 1), ) norm = torch.sum(weights) + 1e-10 weighted_actions = population * weights self.mean = torch.sum(weighted_actions, dim=0) / norm return self.mean.clone() class TrajectoryOptimizer: """Class for using generic optimizers on trajectory optimization problems. This is a convenience class that sets up optimization problem for trajectories, given only action bounds and the length of the horizon. Using this class, the concern of handling appropriate tensor shapes for the optimization problem is hidden from the users, which only need to provide a function that is capable of evaluating trajectories of actions. It also takes care of shifting previous solution for the next optimization call, if the user desires. The optimization variables for the problem will have shape ``H x A``, where ``H`` and ``A`` represent planning horizon and action dimension, respectively. The initial solution for the optimizer will be computed as (action_ub - action_lb) / 2, for each time step. Args: optimizer_cfg (omegaconf.DictConfig): the configuration of the optimizer to use. action_lb (np.ndarray): the lower bound for actions. action_ub (np.ndarray): the upper bound for actions. planning_horizon (int): the length of the trajectories that will be optimized. replan_freq (int): the frequency of re-planning. This is used for shifting the previous solution for the next time step, when ``keep_last_solution == True``. Defaults to 1. keep_last_solution (bool): if ``True``, the last solution found by a call to :meth:`optimize` is kept as the initial solution for the next step. This solution is shifted ``replan_freq`` time steps, and the new entries are filled using th3 initial solution. Defaults to ``True``. """ def __init__( self, optimizer_cfg: omegaconf.DictConfig, action_lb: np.ndarray, action_ub: np.ndarray, planning_horizon: int, replan_freq: int = 1, keep_last_solution: bool = True, ): optimizer_cfg.lower_bound = np.tile(action_lb, (planning_horizon, 1)).tolist() optimizer_cfg.upper_bound = np.tile(action_ub, (planning_horizon, 1)).tolist() self.optimizer: Optimizer = hydra.utils.instantiate(optimizer_cfg) self.initial_solution = ( ((torch.tensor(action_lb) + torch.tensor(action_ub)) / 2) .float() .to(optimizer_cfg.device) ) self.initial_solution = self.initial_solution.repeat((planning_horizon, 1)) self.previous_solution = self.initial_solution.clone() self.replan_freq = replan_freq self.keep_last_solution = keep_last_solution self.horizon = planning_horizon def optimize( self, trajectory_eval_fn: Callable[[torch.Tensor], torch.Tensor], callback: Optional[Callable] = None, ) -> np.ndarray: """Runs the trajectory optimization. Args: trajectory_eval_fn (callable(tensor) -> tensor): A function that receives a batch of action sequences and returns a batch of objective function values (e.g., accumulated reward for each sequence). The shape of the action sequence tensor will be ``B x H x A``, where ``B``, ``H``, and ``A`` represent batch size, planning horizon, and action dimension, respectively. callback (callable, optional): a callback function to pass to the optimizer. Returns: (tuple of np.ndarray and float): the best action sequence. """ best_solution = self.optimizer.optimize( trajectory_eval_fn, x0=self.previous_solution, callback=callback, ) if self.keep_last_solution: self.previous_solution = best_solution.roll(-self.replan_freq, dims=0) # Note that initial_solution[i] is the same for all values of [i], # so just pick i = 0 self.previous_solution[-self.replan_freq :] = self.initial_solution[0] return best_solution.cpu().numpy() def reset(self): """Resets the previous solution cache to the initial solution.""" self.previous_solution = self.initial_solution.clone() class TrajectoryOptimizerAgent(Agent): """Agent that performs trajectory optimization on a given objective function for each action. This class uses an internal :class:`TrajectoryOptimizer` object to generate sequence of actions, given a user-defined trajectory optimization function. Args: optimizer_cfg (omegaconf.DictConfig): the configuration of the base optimizer to pass to the trajectory optimizer. action_lb (sequence of floats): the lower bound of the action space. action_ub (sequence of floats): the upper bound of the action space. planning_horizon (int): the length of action sequences to evaluate. Defaults to 1. replan_freq (int): the frequency of re-planning. The agent will keep a cache of the generated sequences an use it for ``replan_freq`` number of :meth:`act` calls. Defaults to 1. verbose (bool): if ``True``, prints the planning time on the console. Note: After constructing an agent of this type, the user must call :meth:`set_trajectory_eval_fn`. This is not passed to the constructor so that the agent can be automatically instantiated with Hydra (which in turn makes it easy to replace this agent with an agent of another type via config-only changes). """ def __init__( self, optimizer_cfg: omegaconf.DictConfig, action_lb: Sequence[float], action_ub: Sequence[float], planning_horizon: int = 1, replan_freq: int = 1, verbose: bool = False, ): self.optimizer = TrajectoryOptimizer( optimizer_cfg, np.array(action_lb), np.array(action_ub), planning_horizon=planning_horizon, replan_freq=replan_freq, ) self.optimizer_args = { "optimizer_cfg": optimizer_cfg, "action_lb": np.array(action_lb), "action_ub": np.array(action_ub), } self.trajectory_eval_fn: mbrl.types.TrajectoryEvalFnType = None self.actions_to_use: List[np.ndarray] = [] self.replan_freq = replan_freq self.verbose = verbose def set_trajectory_eval_fn( self, trajectory_eval_fn: mbrl.types.TrajectoryEvalFnType ): """Sets the trajectory evaluation function. Args: trajectory_eval_fn (callable): a trajectory evaluation function, as described in :class:`TrajectoryOptimizer`. """ self.trajectory_eval_fn = trajectory_eval_fn def reset(self, planning_horizon: Optional[int] = None): """Resets the underlying trajectory optimizer.""" if planning_horizon: self.optimizer = TrajectoryOptimizer( cast(omegaconf.DictConfig, self.optimizer_args["optimizer_cfg"]), cast(np.ndarray, self.optimizer_args["action_lb"]), cast(np.ndarray, self.optimizer_args["action_ub"]), planning_horizon=planning_horizon, replan_freq=self.replan_freq, ) self.optimizer.reset() def act(self, obs: np.ndarray, **_kwargs) -> np.ndarray: """Issues an action given an observation. This method optimizes a full sequence of length ``self.planning_horizon`` and returns the first action in the sequence. If ``self.replan_freq > 1``, future calls will use subsequent actions in the sequence, for ``self.replan_freq`` number of steps. After that, the method will plan again, and repeat this process. Args: obs (np.ndarray): the observation for which the action is needed. Returns: (np.ndarray): the action. """ if self.trajectory_eval_fn is None: raise RuntimeError( "Please call `set_trajectory_eval_fn()` before using TrajectoryOptimizerAgent" ) plan_time = 0.0 if not self.actions_to_use: # re-plan is necessary def trajectory_eval_fn(action_sequences): return self.trajectory_eval_fn(obs, action_sequences) start_time = time.time() plan = self.optimizer.optimize(trajectory_eval_fn) plan_time = time.time() - start_time self.actions_to_use.extend([a for a in plan[: self.replan_freq]]) action = self.actions_to_use.pop(0) if self.verbose: print(f"Planning time: {plan_time:.3f}") return action def plan(self, obs: np.ndarray, **_kwargs) -> np.ndarray: """Issues a sequence of actions given an observation. Returns s sequence of length self.planning_horizon. Args: obs (np.ndarray): the observation for which the sequence is needed. Returns: (np.ndarray): a sequence of actions. """ if self.trajectory_eval_fn is None: raise RuntimeError( "Please call `set_trajectory_eval_fn()` before using TrajectoryOptimizerAgent" ) def trajectory_eval_fn(action_sequences): return self.trajectory_eval_fn(obs, action_sequences) plan = self.optimizer.optimize(trajectory_eval_fn) return plan def create_trajectory_optim_agent_for_model( model_env: mbrl.models.ModelEnv, agent_cfg: omegaconf.DictConfig, num_particles: int = 1, ) -> TrajectoryOptimizerAgent: """Utility function for creating a trajectory optimizer agent for a model environment. This is a convenience function for creating a :class:`TrajectoryOptimizerAgent`, using :meth:`mbrl.models.ModelEnv.evaluate_action_sequences` as its objective function. Args: model_env (mbrl.models.ModelEnv): the model environment. agent_cfg (omegaconf.DictConfig): the agent's configuration. num_particles (int): the number of particles for taking averages of action sequences' total rewards. Returns: (:class:`TrajectoryOptimizerAgent`): the agent. """ complete_agent_cfg(model_env, agent_cfg) agent = hydra.utils.instantiate(agent_cfg) def trajectory_eval_fn(initial_state, action_sequences): return model_env.evaluate_action_sequences( action_sequences, initial_state=initial_state, num_particles=num_particles ) agent.set_trajectory_eval_fn(trajectory_eval_fn) return agent
mbrl/planning/trajectory_opt.py
import time from typing import Callable, List, Optional, Sequence, cast import hydra import numpy as np import omegaconf import torch import torch.distributions import mbrl.models import mbrl.types import mbrl.util.math from .core import Agent, complete_agent_cfg class Optimizer: def __init__(self): pass def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: """Runs optimization. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): initial solution, if necessary. Returns: (torch.Tensor): the best solution found. """ pass class CEMOptimizer(Optimizer): """Implements the Cross-Entropy Method optimization algorithm. A good description of CEM [1] can be found at https://arxiv.org/pdf/2008.06389.pdf. This code implements the version described in Section 2.1, labeled CEM_PETS (but note that the shift-initialization between planning time steps is handled outside of this class by TrajectoryOptimizer). This implementation also returns the best solution found as opposed to the mean of the last generation. Args: num_iterations (int): the number of iterations (generations) to perform. elite_ratio (float): the proportion of the population that will be kept as elite (rounds up). population_size (int): the size of the population. lower_bound (sequence of floats): the lower bound for the optimization variables. upper_bound (sequence of floats): the upper bound for the optimization variables. alpha (float): momentum term. device (torch.device): device where computations will be performed. return_mean_elites (bool): if ``True`` returns the mean of the elites of the last iteration. Otherwise, it returns the max solution found over all iterations. [1] <NAME> and <NAME>. "The cross-entropy method for combinatorial and continuous optimization". Methodology and Computing in Applied Probability, 1999. """ def __init__( self, num_iterations: int, elite_ratio: float, population_size: int, lower_bound: Sequence[Sequence[float]], upper_bound: Sequence[Sequence[float]], alpha: float, device: torch.device, return_mean_elites: bool = False, ): super().__init__() self.num_iterations = num_iterations self.elite_ratio = elite_ratio self.population_size = population_size self.elite_num = np.ceil(self.population_size * self.elite_ratio).astype( np.int32 ) self.lower_bound = torch.tensor(lower_bound, device=device, dtype=torch.float32) self.upper_bound = torch.tensor(upper_bound, device=device, dtype=torch.float32) self.initial_var = ((self.upper_bound - self.lower_bound) ** 2) / 16 self.alpha = alpha self.return_mean_elites = return_mean_elites self.device = device def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, callback: Optional[Callable[[torch.Tensor, torch.Tensor, int], None]] = None, **kwargs, ) -> torch.Tensor: """Runs the optimization using CEM. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): initial mean for the population. Must be consistent with lower/upper bounds. callback (callable(tensor, tensor, int) -> any, optional): if given, this function will be called after every iteration, passing it as input the full population tensor, its corresponding objective function values, and the index of the current iteration. This can be used for logging and plotting purposes. Returns: (torch.Tensor): the best solution found. """ mu = x0.clone() var = self.initial_var.clone() best_solution = torch.empty_like(mu) best_value = -np.inf population = torch.zeros((self.population_size,) + x0.shape).to( device=self.device ) for i in range(self.num_iterations): lb_dist = mu - self.lower_bound ub_dist = self.upper_bound - mu mv = torch.min(torch.square(lb_dist / 2), torch.square(ub_dist / 2)) constrained_var = torch.min(mv, var) population = mbrl.util.math.truncated_normal_(population) population = population * torch.sqrt(constrained_var) + mu values = obj_fun(population) if callback is not None: callback(population, values, i) # filter out NaN values values[values.isnan()] = -1e-10 best_values, elite_idx = values.topk(self.elite_num) elite = population[elite_idx] new_mu = torch.mean(elite, dim=0) new_var = torch.var(elite, unbiased=False, dim=0) mu = self.alpha * mu + (1 - self.alpha) * new_mu var = self.alpha * var + (1 - self.alpha) * new_var if best_values[0] > best_value: best_value = best_values[0] best_solution = population[elite_idx[0]].clone() return mu if self.return_mean_elites else best_solution class MPPIOptimizer(Optimizer): """Implements the Model Predictive Path Integral optimization algorithm. A derivation of MPPI can be found at https://arxiv.org/abs/2102.09027 This version is closely related to the original TF implementation used in PDDM with some noise sampling modifications and the addition of refinement steps. Args: num_iterations (int): the number of iterations (generations) to perform. population_size (int): the size of the population. gamma (float): reward scaling term. sigma (float): noise scaling term used in action sampling. beta (float): correlation term between time steps. lower_bound (sequence of floats): the lower bound for the optimization variables. upper_bound (sequence of floats): the upper bound for the optimization variables. device (torch.device): device where computations will be performed. """ def __init__( self, num_iterations: int, population_size: int, gamma: float, sigma: float, beta: float, lower_bound: Sequence[Sequence[float]], upper_bound: Sequence[Sequence[float]], device: torch.device, ): super().__init__() self.planning_horizon = len(lower_bound) self.population_size = population_size self.action_dimension = len(lower_bound[0]) self.mean = torch.zeros( (self.planning_horizon, self.action_dimension), device=device, dtype=torch.float32, ) self.lower_bound = torch.tensor(lower_bound, device=device, dtype=torch.float32) self.upper_bound = torch.tensor(upper_bound, device=device, dtype=torch.float32) self.var = sigma ** 2 * torch.ones_like(self.lower_bound) self.beta = beta self.gamma = gamma self.refinements = num_iterations self.device = device def optimize( self, obj_fun: Callable[[torch.Tensor], torch.Tensor], x0: Optional[torch.Tensor] = None, callback: Optional[Callable[[torch.Tensor, torch.Tensor, int], None]] = None, **kwargs, ) -> torch.Tensor: """Implementation of MPPI planner. Args: obj_fun (callable(tensor) -> tensor): objective function to maximize. x0 (tensor, optional): Not required callback (callable(tensor, tensor, int) -> any, optional): if given, this function will be called after every iteration, passing it as input the full population tensor, its corresponding objective function values, and the index of the current iteration. This can be used for logging and plotting purposes. Returns: (torch.Tensor): the best solution found. """ past_action = self.mean[0] self.mean[:-1] = self.mean[1:].clone() for k in range(self.refinements): # sample noise and update constrained variances noise = torch.empty( size=( self.population_size, self.planning_horizon, self.action_dimension, ), device=self.device, ) noise = mbrl.util.math.truncated_normal_(noise) lb_dist = self.mean - self.lower_bound ub_dist = self.upper_bound - self.mean mv = torch.minimum(torch.square(lb_dist / 2), torch.square(ub_dist / 2)) constrained_var = torch.minimum(mv, self.var) population = noise.clone() * torch.sqrt(constrained_var) # smoothed actions with noise population[:, 0, :] = ( self.beta * (self.mean[0, :] + noise[:, 0, :]) + (1 - self.beta) * past_action ) for i in range(max(self.planning_horizon - 1, 0)): population[:, i + 1, :] = ( self.beta * (self.mean[i + 1] + noise[:, i + 1, :]) + (1 - self.beta) * population[:, i, :] ) # clipping actions # This should still work if the bounds between dimensions are different. population = torch.where( population > self.upper_bound, self.upper_bound, population ) population = torch.where( population < self.lower_bound, self.lower_bound, population ) values = obj_fun(population) values[values.isnan()] = -1e-10 if callback is not None: callback(population, values, k) # weight actions weights = torch.reshape( torch.exp(self.gamma * (values - values.max())), (self.population_size, 1, 1), ) norm = torch.sum(weights) + 1e-10 weighted_actions = population * weights self.mean = torch.sum(weighted_actions, dim=0) / norm return self.mean.clone() class TrajectoryOptimizer: """Class for using generic optimizers on trajectory optimization problems. This is a convenience class that sets up optimization problem for trajectories, given only action bounds and the length of the horizon. Using this class, the concern of handling appropriate tensor shapes for the optimization problem is hidden from the users, which only need to provide a function that is capable of evaluating trajectories of actions. It also takes care of shifting previous solution for the next optimization call, if the user desires. The optimization variables for the problem will have shape ``H x A``, where ``H`` and ``A`` represent planning horizon and action dimension, respectively. The initial solution for the optimizer will be computed as (action_ub - action_lb) / 2, for each time step. Args: optimizer_cfg (omegaconf.DictConfig): the configuration of the optimizer to use. action_lb (np.ndarray): the lower bound for actions. action_ub (np.ndarray): the upper bound for actions. planning_horizon (int): the length of the trajectories that will be optimized. replan_freq (int): the frequency of re-planning. This is used for shifting the previous solution for the next time step, when ``keep_last_solution == True``. Defaults to 1. keep_last_solution (bool): if ``True``, the last solution found by a call to :meth:`optimize` is kept as the initial solution for the next step. This solution is shifted ``replan_freq`` time steps, and the new entries are filled using th3 initial solution. Defaults to ``True``. """ def __init__( self, optimizer_cfg: omegaconf.DictConfig, action_lb: np.ndarray, action_ub: np.ndarray, planning_horizon: int, replan_freq: int = 1, keep_last_solution: bool = True, ): optimizer_cfg.lower_bound = np.tile(action_lb, (planning_horizon, 1)).tolist() optimizer_cfg.upper_bound = np.tile(action_ub, (planning_horizon, 1)).tolist() self.optimizer: Optimizer = hydra.utils.instantiate(optimizer_cfg) self.initial_solution = ( ((torch.tensor(action_lb) + torch.tensor(action_ub)) / 2) .float() .to(optimizer_cfg.device) ) self.initial_solution = self.initial_solution.repeat((planning_horizon, 1)) self.previous_solution = self.initial_solution.clone() self.replan_freq = replan_freq self.keep_last_solution = keep_last_solution self.horizon = planning_horizon def optimize( self, trajectory_eval_fn: Callable[[torch.Tensor], torch.Tensor], callback: Optional[Callable] = None, ) -> np.ndarray: """Runs the trajectory optimization. Args: trajectory_eval_fn (callable(tensor) -> tensor): A function that receives a batch of action sequences and returns a batch of objective function values (e.g., accumulated reward for each sequence). The shape of the action sequence tensor will be ``B x H x A``, where ``B``, ``H``, and ``A`` represent batch size, planning horizon, and action dimension, respectively. callback (callable, optional): a callback function to pass to the optimizer. Returns: (tuple of np.ndarray and float): the best action sequence. """ best_solution = self.optimizer.optimize( trajectory_eval_fn, x0=self.previous_solution, callback=callback, ) if self.keep_last_solution: self.previous_solution = best_solution.roll(-self.replan_freq, dims=0) # Note that initial_solution[i] is the same for all values of [i], # so just pick i = 0 self.previous_solution[-self.replan_freq :] = self.initial_solution[0] return best_solution.cpu().numpy() def reset(self): """Resets the previous solution cache to the initial solution.""" self.previous_solution = self.initial_solution.clone() class TrajectoryOptimizerAgent(Agent): """Agent that performs trajectory optimization on a given objective function for each action. This class uses an internal :class:`TrajectoryOptimizer` object to generate sequence of actions, given a user-defined trajectory optimization function. Args: optimizer_cfg (omegaconf.DictConfig): the configuration of the base optimizer to pass to the trajectory optimizer. action_lb (sequence of floats): the lower bound of the action space. action_ub (sequence of floats): the upper bound of the action space. planning_horizon (int): the length of action sequences to evaluate. Defaults to 1. replan_freq (int): the frequency of re-planning. The agent will keep a cache of the generated sequences an use it for ``replan_freq`` number of :meth:`act` calls. Defaults to 1. verbose (bool): if ``True``, prints the planning time on the console. Note: After constructing an agent of this type, the user must call :meth:`set_trajectory_eval_fn`. This is not passed to the constructor so that the agent can be automatically instantiated with Hydra (which in turn makes it easy to replace this agent with an agent of another type via config-only changes). """ def __init__( self, optimizer_cfg: omegaconf.DictConfig, action_lb: Sequence[float], action_ub: Sequence[float], planning_horizon: int = 1, replan_freq: int = 1, verbose: bool = False, ): self.optimizer = TrajectoryOptimizer( optimizer_cfg, np.array(action_lb), np.array(action_ub), planning_horizon=planning_horizon, replan_freq=replan_freq, ) self.optimizer_args = { "optimizer_cfg": optimizer_cfg, "action_lb": np.array(action_lb), "action_ub": np.array(action_ub), } self.trajectory_eval_fn: mbrl.types.TrajectoryEvalFnType = None self.actions_to_use: List[np.ndarray] = [] self.replan_freq = replan_freq self.verbose = verbose def set_trajectory_eval_fn( self, trajectory_eval_fn: mbrl.types.TrajectoryEvalFnType ): """Sets the trajectory evaluation function. Args: trajectory_eval_fn (callable): a trajectory evaluation function, as described in :class:`TrajectoryOptimizer`. """ self.trajectory_eval_fn = trajectory_eval_fn def reset(self, planning_horizon: Optional[int] = None): """Resets the underlying trajectory optimizer.""" if planning_horizon: self.optimizer = TrajectoryOptimizer( cast(omegaconf.DictConfig, self.optimizer_args["optimizer_cfg"]), cast(np.ndarray, self.optimizer_args["action_lb"]), cast(np.ndarray, self.optimizer_args["action_ub"]), planning_horizon=planning_horizon, replan_freq=self.replan_freq, ) self.optimizer.reset() def act(self, obs: np.ndarray, **_kwargs) -> np.ndarray: """Issues an action given an observation. This method optimizes a full sequence of length ``self.planning_horizon`` and returns the first action in the sequence. If ``self.replan_freq > 1``, future calls will use subsequent actions in the sequence, for ``self.replan_freq`` number of steps. After that, the method will plan again, and repeat this process. Args: obs (np.ndarray): the observation for which the action is needed. Returns: (np.ndarray): the action. """ if self.trajectory_eval_fn is None: raise RuntimeError( "Please call `set_trajectory_eval_fn()` before using TrajectoryOptimizerAgent" ) plan_time = 0.0 if not self.actions_to_use: # re-plan is necessary def trajectory_eval_fn(action_sequences): return self.trajectory_eval_fn(obs, action_sequences) start_time = time.time() plan = self.optimizer.optimize(trajectory_eval_fn) plan_time = time.time() - start_time self.actions_to_use.extend([a for a in plan[: self.replan_freq]]) action = self.actions_to_use.pop(0) if self.verbose: print(f"Planning time: {plan_time:.3f}") return action def plan(self, obs: np.ndarray, **_kwargs) -> np.ndarray: """Issues a sequence of actions given an observation. Returns s sequence of length self.planning_horizon. Args: obs (np.ndarray): the observation for which the sequence is needed. Returns: (np.ndarray): a sequence of actions. """ if self.trajectory_eval_fn is None: raise RuntimeError( "Please call `set_trajectory_eval_fn()` before using TrajectoryOptimizerAgent" ) def trajectory_eval_fn(action_sequences): return self.trajectory_eval_fn(obs, action_sequences) plan = self.optimizer.optimize(trajectory_eval_fn) return plan def create_trajectory_optim_agent_for_model( model_env: mbrl.models.ModelEnv, agent_cfg: omegaconf.DictConfig, num_particles: int = 1, ) -> TrajectoryOptimizerAgent: """Utility function for creating a trajectory optimizer agent for a model environment. This is a convenience function for creating a :class:`TrajectoryOptimizerAgent`, using :meth:`mbrl.models.ModelEnv.evaluate_action_sequences` as its objective function. Args: model_env (mbrl.models.ModelEnv): the model environment. agent_cfg (omegaconf.DictConfig): the agent's configuration. num_particles (int): the number of particles for taking averages of action sequences' total rewards. Returns: (:class:`TrajectoryOptimizerAgent`): the agent. """ complete_agent_cfg(model_env, agent_cfg) agent = hydra.utils.instantiate(agent_cfg) def trajectory_eval_fn(initial_state, action_sequences): return model_env.evaluate_action_sequences( action_sequences, initial_state=initial_state, num_particles=num_particles ) agent.set_trajectory_eval_fn(trajectory_eval_fn) return agent
0.952153
0.564249
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='uac/Workspace.proto', package='ai.verta.uac', syntax='proto3', serialized_options=b'P\001Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uac', serialized_pb=b'\n\x13uac/Workspace.proto\x12\x0c\x61i.verta.uac\x1a\x1cgoogle/api/annotations.proto\"\x1e\n\x10GetWorkspaceById\x12\n\n\x02id\x18\x01 \x01(\x04\"\"\n\x12GetWorkspaceByName\x12\x0c\n\x04name\x18\x01 \x01(\t\"{\n\tWorkspace\x12\n\n\x02id\x18\x01 \x01(\x04\x12\x11\n\x07user_id\x18\x02 \x01(\tH\x00\x12\x10\n\x06org_id\x18\x03 \x01(\tH\x00\x12\x12\n\x08username\x18\x04 \x01(\tH\x01\x12\x12\n\x08org_name\x18\x05 \x01(\tH\x01\x42\r\n\x0binternal_idB\x06\n\x04name2\x82\x02\n\x10WorkspaceService\x12s\n\x10getWorkspaceById\x12\x1e.ai.verta.uac.GetWorkspaceById\x1a\x17.ai.verta.uac.Workspace\"&\x82\xd3\xe4\x93\x02 \x12\x1e/v1/workspace/getWorkspaceById\x12y\n\x12getWorkspaceByName\x12 .ai.verta.uac.GetWorkspaceByName\x1a\x17.ai.verta.uac.Workspace\"(\x82\xd3\xe4\x93\x02\"\x12 /v1/workspace/getWorkspaceByNameB>P\x01Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uacb\x06proto3' , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _GETWORKSPACEBYID = _descriptor.Descriptor( name='GetWorkspaceById', full_name='ai.verta.uac.GetWorkspaceById', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.uac.GetWorkspaceById.id', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=67, serialized_end=97, ) _GETWORKSPACEBYNAME = _descriptor.Descriptor( name='GetWorkspaceByName', full_name='ai.verta.uac.GetWorkspaceByName', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='ai.verta.uac.GetWorkspaceByName.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=99, serialized_end=133, ) _WORKSPACE = _descriptor.Descriptor( name='Workspace', full_name='ai.verta.uac.Workspace', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.uac.Workspace.id', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='user_id', full_name='ai.verta.uac.Workspace.user_id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.Workspace.org_id', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='username', full_name='ai.verta.uac.Workspace.username', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org_name', full_name='ai.verta.uac.Workspace.org_name', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='internal_id', full_name='ai.verta.uac.Workspace.internal_id', index=0, containing_type=None, fields=[]), _descriptor.OneofDescriptor( name='name', full_name='ai.verta.uac.Workspace.name', index=1, containing_type=None, fields=[]), ], serialized_start=135, serialized_end=258, ) _WORKSPACE.oneofs_by_name['internal_id'].fields.append( _WORKSPACE.fields_by_name['user_id']) _WORKSPACE.fields_by_name['user_id'].containing_oneof = _WORKSPACE.oneofs_by_name['internal_id'] _WORKSPACE.oneofs_by_name['internal_id'].fields.append( _WORKSPACE.fields_by_name['org_id']) _WORKSPACE.fields_by_name['org_id'].containing_oneof = _WORKSPACE.oneofs_by_name['internal_id'] _WORKSPACE.oneofs_by_name['name'].fields.append( _WORKSPACE.fields_by_name['username']) _WORKSPACE.fields_by_name['username'].containing_oneof = _WORKSPACE.oneofs_by_name['name'] _WORKSPACE.oneofs_by_name['name'].fields.append( _WORKSPACE.fields_by_name['org_name']) _WORKSPACE.fields_by_name['org_name'].containing_oneof = _WORKSPACE.oneofs_by_name['name'] DESCRIPTOR.message_types_by_name['GetWorkspaceById'] = _GETWORKSPACEBYID DESCRIPTOR.message_types_by_name['GetWorkspaceByName'] = _GETWORKSPACEBYNAME DESCRIPTOR.message_types_by_name['Workspace'] = _WORKSPACE _sym_db.RegisterFileDescriptor(DESCRIPTOR) GetWorkspaceById = _reflection.GeneratedProtocolMessageType('GetWorkspaceById', (_message.Message,), { 'DESCRIPTOR' : _GETWORKSPACEBYID, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetWorkspaceById) }) _sym_db.RegisterMessage(GetWorkspaceById) GetWorkspaceByName = _reflection.GeneratedProtocolMessageType('GetWorkspaceByName', (_message.Message,), { 'DESCRIPTOR' : _GETWORKSPACEBYNAME, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetWorkspaceByName) }) _sym_db.RegisterMessage(GetWorkspaceByName) Workspace = _reflection.GeneratedProtocolMessageType('Workspace', (_message.Message,), { 'DESCRIPTOR' : _WORKSPACE, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.Workspace) }) _sym_db.RegisterMessage(Workspace) DESCRIPTOR._options = None _WORKSPACESERVICE = _descriptor.ServiceDescriptor( name='WorkspaceService', full_name='ai.verta.uac.WorkspaceService', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=261, serialized_end=519, methods=[ _descriptor.MethodDescriptor( name='getWorkspaceById', full_name='ai.verta.uac.WorkspaceService.getWorkspaceById', index=0, containing_service=None, input_type=_GETWORKSPACEBYID, output_type=_WORKSPACE, serialized_options=b'\202\323\344\223\002 \022\036/v1/workspace/getWorkspaceById', ), _descriptor.MethodDescriptor( name='getWorkspaceByName', full_name='ai.verta.uac.WorkspaceService.getWorkspaceByName', index=1, containing_service=None, input_type=_GETWORKSPACEBYNAME, output_type=_WORKSPACE, serialized_options=b'\202\323\344\223\002\"\022 /v1/workspace/getWorkspaceByName', ), ]) _sym_db.RegisterServiceDescriptor(_WORKSPACESERVICE) DESCRIPTOR.services_by_name['WorkspaceService'] = _WORKSPACESERVICE # @@protoc_insertion_point(module_scope)
protos/gen/python/protos/public/uac/Workspace_pb2.py
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='uac/Workspace.proto', package='ai.verta.uac', syntax='proto3', serialized_options=b'P\001Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uac', serialized_pb=b'\n\x13uac/Workspace.proto\x12\x0c\x61i.verta.uac\x1a\x1cgoogle/api/annotations.proto\"\x1e\n\x10GetWorkspaceById\x12\n\n\x02id\x18\x01 \x01(\x04\"\"\n\x12GetWorkspaceByName\x12\x0c\n\x04name\x18\x01 \x01(\t\"{\n\tWorkspace\x12\n\n\x02id\x18\x01 \x01(\x04\x12\x11\n\x07user_id\x18\x02 \x01(\tH\x00\x12\x10\n\x06org_id\x18\x03 \x01(\tH\x00\x12\x12\n\x08username\x18\x04 \x01(\tH\x01\x12\x12\n\x08org_name\x18\x05 \x01(\tH\x01\x42\r\n\x0binternal_idB\x06\n\x04name2\x82\x02\n\x10WorkspaceService\x12s\n\x10getWorkspaceById\x12\x1e.ai.verta.uac.GetWorkspaceById\x1a\x17.ai.verta.uac.Workspace\"&\x82\xd3\xe4\x93\x02 \x12\x1e/v1/workspace/getWorkspaceById\x12y\n\x12getWorkspaceByName\x12 .ai.verta.uac.GetWorkspaceByName\x1a\x17.ai.verta.uac.Workspace\"(\x82\xd3\xe4\x93\x02\"\x12 /v1/workspace/getWorkspaceByNameB>P\x01Z:github.com/VertaAI/modeldb/protos/gen/go/protos/public/uacb\x06proto3' , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _GETWORKSPACEBYID = _descriptor.Descriptor( name='GetWorkspaceById', full_name='ai.verta.uac.GetWorkspaceById', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.uac.GetWorkspaceById.id', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=67, serialized_end=97, ) _GETWORKSPACEBYNAME = _descriptor.Descriptor( name='GetWorkspaceByName', full_name='ai.verta.uac.GetWorkspaceByName', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='ai.verta.uac.GetWorkspaceByName.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=99, serialized_end=133, ) _WORKSPACE = _descriptor.Descriptor( name='Workspace', full_name='ai.verta.uac.Workspace', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.uac.Workspace.id', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='user_id', full_name='ai.verta.uac.Workspace.user_id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org_id', full_name='ai.verta.uac.Workspace.org_id', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='username', full_name='ai.verta.uac.Workspace.username', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org_name', full_name='ai.verta.uac.Workspace.org_name', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='internal_id', full_name='ai.verta.uac.Workspace.internal_id', index=0, containing_type=None, fields=[]), _descriptor.OneofDescriptor( name='name', full_name='ai.verta.uac.Workspace.name', index=1, containing_type=None, fields=[]), ], serialized_start=135, serialized_end=258, ) _WORKSPACE.oneofs_by_name['internal_id'].fields.append( _WORKSPACE.fields_by_name['user_id']) _WORKSPACE.fields_by_name['user_id'].containing_oneof = _WORKSPACE.oneofs_by_name['internal_id'] _WORKSPACE.oneofs_by_name['internal_id'].fields.append( _WORKSPACE.fields_by_name['org_id']) _WORKSPACE.fields_by_name['org_id'].containing_oneof = _WORKSPACE.oneofs_by_name['internal_id'] _WORKSPACE.oneofs_by_name['name'].fields.append( _WORKSPACE.fields_by_name['username']) _WORKSPACE.fields_by_name['username'].containing_oneof = _WORKSPACE.oneofs_by_name['name'] _WORKSPACE.oneofs_by_name['name'].fields.append( _WORKSPACE.fields_by_name['org_name']) _WORKSPACE.fields_by_name['org_name'].containing_oneof = _WORKSPACE.oneofs_by_name['name'] DESCRIPTOR.message_types_by_name['GetWorkspaceById'] = _GETWORKSPACEBYID DESCRIPTOR.message_types_by_name['GetWorkspaceByName'] = _GETWORKSPACEBYNAME DESCRIPTOR.message_types_by_name['Workspace'] = _WORKSPACE _sym_db.RegisterFileDescriptor(DESCRIPTOR) GetWorkspaceById = _reflection.GeneratedProtocolMessageType('GetWorkspaceById', (_message.Message,), { 'DESCRIPTOR' : _GETWORKSPACEBYID, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetWorkspaceById) }) _sym_db.RegisterMessage(GetWorkspaceById) GetWorkspaceByName = _reflection.GeneratedProtocolMessageType('GetWorkspaceByName', (_message.Message,), { 'DESCRIPTOR' : _GETWORKSPACEBYNAME, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.GetWorkspaceByName) }) _sym_db.RegisterMessage(GetWorkspaceByName) Workspace = _reflection.GeneratedProtocolMessageType('Workspace', (_message.Message,), { 'DESCRIPTOR' : _WORKSPACE, '__module__' : 'uac.Workspace_pb2' # @@protoc_insertion_point(class_scope:ai.verta.uac.Workspace) }) _sym_db.RegisterMessage(Workspace) DESCRIPTOR._options = None _WORKSPACESERVICE = _descriptor.ServiceDescriptor( name='WorkspaceService', full_name='ai.verta.uac.WorkspaceService', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=261, serialized_end=519, methods=[ _descriptor.MethodDescriptor( name='getWorkspaceById', full_name='ai.verta.uac.WorkspaceService.getWorkspaceById', index=0, containing_service=None, input_type=_GETWORKSPACEBYID, output_type=_WORKSPACE, serialized_options=b'\202\323\344\223\002 \022\036/v1/workspace/getWorkspaceById', ), _descriptor.MethodDescriptor( name='getWorkspaceByName', full_name='ai.verta.uac.WorkspaceService.getWorkspaceByName', index=1, containing_service=None, input_type=_GETWORKSPACEBYNAME, output_type=_WORKSPACE, serialized_options=b'\202\323\344\223\002\"\022 /v1/workspace/getWorkspaceByName', ), ]) _sym_db.RegisterServiceDescriptor(_WORKSPACESERVICE) DESCRIPTOR.services_by_name['WorkspaceService'] = _WORKSPACESERVICE # @@protoc_insertion_point(module_scope)
0.264928
0.08772