hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f71b74e1b33e2d32c75b576cb1deaa4ac7bf5e57 | 10,449 | py | Python | src/AuShadha/patient/models.py | GosthMan/AuShadha | 3ab48825a0dba19bf880b6ac6141ab7a6adf1f3e | [
"PostgreSQL"
] | 46 | 2015-03-04T14:19:47.000Z | 2021-12-09T02:58:46.000Z | src/AuShadha/patient/models.py | aytida23/AuShadha | 3ab48825a0dba19bf880b6ac6141ab7a6adf1f3e | [
"PostgreSQL"
] | 2 | 2015-06-05T10:29:04.000Z | 2015-12-06T16:54:10.000Z | src/AuShadha/patient/models.py | aytida23/AuShadha | 3ab48825a0dba19bf880b6ac6141ab7a6adf1f3e | [
"PostgreSQL"
] | 24 | 2015-03-23T01:38:11.000Z | 2022-01-24T16:23:42.000Z | ################################################################################
# PROJECT : AuShadha
# Description : Patient Models for managing patient
# Author : Dr. Easwar T R
# Date : 16-09-2013
# Licence : GNU GPL V3. Please see AuShadha/LICENSE.txt
################################################################################
from django.db import models
from django.contrib.auth.models import User
from AuShadha.utilities.urls import generic_url_maker
from AuShadha.utilities.queries import has_contact,\
has_phone,\
has_guardian,\
has_active_admission,\
has_active_visit, \
adm_for_pat,\
visit_for_pat,\
can_add_new_visit,\
get_patient_complaints
from AuShadha.apps.aushadha_base_models.models import AuShadhaBaseModel,AuShadhaBaseModelForm
from AuShadha.apps.clinic.models import Clinic
from dijit_fields_constants import PATIENT_DETAIL_FORM_CONSTANTS
from AuShadha.settings import APP_ROOT_URL
DEFAULT_PATIENT_DETAIL_FORM_EXCLUDES=('parent_clinic',)
class PatientDetail(AuShadhaBaseModel):
"""
Patient Model definition for Registration, Name entry and Hospital ID Generation
"""
# Some data to Generate the URLS
def __init__(self,*args,**kwargs):
super(PatientDetail,self).__init__(*args, **kwargs)
self.__model_label__ = "patient"
self._parent_model = 'parent_clinic'
self._can_add_list_or_json = [
'contact',
'phone',
'guardian',
'demographics',
'email_and_fax',
'admission',
'visit',
'medical_history',
'surgical_history',
'social_history',
'family_history',
'immunisation',
'obstetric_history_detail',
'medication_list',
'allergy_list'
]
self._extra_url_actions = ['transfer_patient','transfer_clinic','refer']
# Instance Methods imported from AuShadha.utilities.queries
self.has_active_admission = has_active_admission
self.has_active_visit = has_active_visit
self.has_contact = has_contact
self.has_guardian = has_guardian
self.has_phone = has_phone
self.can_add_new_visit = can_add_new_visit
self.get_patient_complaints = get_patient_complaints
# Model attributes
patient_hospital_id = models.CharField('Hospital ID',
max_length=15,
unique=True)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30,
help_text="Please enter Initials / Middle Name",
blank=True,
null=True)
last_name = models.CharField(max_length=30,
blank=True,
null=True,
help_text="Enter Initials / Last Name"
)
full_name = models.CharField(max_length=100,
editable=False,
null=False,
blank=False
)
age = models.CharField(max_length=10, blank=True, null=True)
sex = models.CharField(max_length=6,
choices=(("Male", "Male"),
("Female", "Female"),
("Others", "Others")
),
default = "Male")
parent_clinic = models.ForeignKey(Clinic)
class Meta:
verbose_name = "Patient - Basic Data"
verbose_name_plural = "Patient - Basic Data"
ordering = ('first_name',
'middle_name',
'last_name',
'age', 'sex',
'patient_hospital_id'
)
unique_together = ('patient_hospital_id', 'parent_clinic')
def get_all_json_exportable_fields(self):
"""
Gets the JSON exportable fields and its values as key, value pair
This skips AutoField, OneToOneField type of field
"""
exportable_fields = {}
for item in self._meta.get_fields_with_model():
if item[0].__class__.__name__ not in ['OneToOneField']:
exportable_fields[item[0][0].name] = item[0][0].value_from_object(self)
else:
continue
return exportable_fields
def get_all_related_fields(self):
"""
Gets the related fields (basically ForeignKey)
These are the keys used to add / list / json/ tree/ summary stuff in related models
This should be useful later in URL creation automagically
"""
related_field_list = []
for item in self._meta.get_all_related_objects():
if hasattr(item.model,'__model_label__'):
model_label = getattr(item.model, '__model_label__')
related_field_list.append(model_label)
else:
continue
for item in related_field_list:
if item not in self._can_add_list_or_json:
self._can_add_list_or_json.append(item)
print "_can_add_list_or_json, Updated"
return related_field_list
def __unicode__(self):
if self.middle_name and self.last_name:
return "%s %s %s" % (self.first_name.capitalize(),
self.middle_name.capitalize(),
self.last_name.capitalize()
)
elif self.last_name or self.middle_name:
if self.last_name:
return "%s %s" % (self.first_name.capitalize(), self.last_name.capitalize())
else:
return "%s %s" % (self.first_name.capitalize(), self.middle_name.capitalize())
def check_before_you_add(self):
"""
Checks whether the patient has already been registered in the
database before adding.
"""
all_pat = PatientDetail.objects.all()
hosp_id = self.patient_hospital_id
id_list = []
if all_pat:
for p in all_pat:
id_list.append(p.patient_hospital_id)
if hosp_id in id_list:
error = "Patient is already registered"
print error
return False
else:
return True
else:
return True
def save(self, *args, **kwargs):
"""
Custom Save Method needs to be defined.
This should check for:
1. Whether the patient is registered before.
2. Patient DOB / Age Verfication and attribute setting
3. Setting the full_name attribute
"""
self.check_before_you_add()
self._set_full_name()
# self._set_age()
super(PatientDetail, self).save(*args, **kwargs)
def _field_list(self):
self.field_list = []
print self._meta.fields
for field in self._meta.fields:
self.field_list.append(field)
return self.field_list
def _formatted_obj_data(self):
if not self.field_list:
_field_list()
str_obj = "<ul>"
for obj in self._field_list:
_str += "<li>" + obj + "<li>"
str_obj += _str
str_obj += "</ul>"
return str_obj
def _set_full_name(self):
"""
Defines and sets the Full Name for a Model on save.
This stores the value under the self.full_name attribute.
This is mainly intented for name display and search
"""
if self.middle_name and self.last_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.middle_name.capitalize() + " " +
self.last_name.capitalize()
)
else:
if self.last_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.last_name.capitalize()
)
if self.middle_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.middle_name.capitalize()
)
return self.full_name
def _set_age(self):
""" Check DOB and Age. See Which one to set.
Dont set age if DOB is given.
Dont allow age > 120 to be set.
This should be called before Form & Model save.
If this returns false, the save should fail raising proper Exception
"""
if self.date_of_birth:
min_allowed_dob = datetime.datetime(1900, 01, 01)
max_allowed_dob = datetime.datetime.now()
if self.date_of_birth >= min_allowed_dob and \
self.date_of_birth <= max_allowed_dob:
self.age = "%.2f" % (
round((max_allowed_dob - self.date_of_birth).days / 365.0, 2))
return True
else:
raise Exception(
"Invalid Date: Date should be from January 01 1900 to Today's Date")
else:
if self.age and int(self.age[0:3]) <= 120:
self.date_of_bith = None
return True
else:
raise Exception("Invalid Date of Birth / Age Supplied")
return False
class PatientDetailForm(AuShadhaBaseModelForm):
"""
ModelForm for Patient Basic Data
"""
__form_name__ = "Patient Detail Form"
dijit_fields = PATIENT_DETAIL_FORM_CONSTANTS
class Meta:
model = PatientDetail
exclude = DEFAULT_PATIENT_DETAIL_FORM_EXCLUDES | 36.28125 | 93 | 0.52072 | for p in all_pat:
id_list.append(p.patient_hospital_id)
if hosp_id in id_list:
error = "Patient is already registered"
print error
return False
else:
return True
else:
return True
def save(self, *args, **kwargs):
"""
Custom Save Method needs to be defined.
This should check for:
1. Whether the patient is registered before.
2. Patient DOB / Age Verfication and attribute setting
3. Setting the full_name attribute
"""
self.check_before_you_add()
self._set_full_name()
super(PatientDetail, self).save(*args, **kwargs)
def _field_list(self):
self.field_list = []
print self._meta.fields
for field in self._meta.fields:
self.field_list.append(field)
return self.field_list
def _formatted_obj_data(self):
if not self.field_list:
_field_list()
str_obj = "<ul>"
for obj in self._field_list:
_str += "<li>" + obj + "<li>"
str_obj += _str
str_obj += "</ul>"
return str_obj
def _set_full_name(self):
"""
Defines and sets the Full Name for a Model on save.
This stores the value under the self.full_name attribute.
This is mainly intented for name display and search
"""
if self.middle_name and self.last_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.middle_name.capitalize() + " " +
self.last_name.capitalize()
)
else:
if self.last_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.last_name.capitalize()
)
if self.middle_name:
self.full_name = unicode(self.first_name.capitalize() + " " +
self.middle_name.capitalize()
)
return self.full_name
def _set_age(self):
""" Check DOB and Age. See Which one to set.
Dont set age if DOB is given.
Dont allow age > 120 to be set.
This should be called before Form & Model save.
If this returns false, the save should fail raising proper Exception
"""
if self.date_of_birth:
min_allowed_dob = datetime.datetime(1900, 01, 01)
max_allowed_dob = datetime.datetime.now()
if self.date_of_birth >= min_allowed_dob and \
self.date_of_birth <= max_allowed_dob:
self.age = "%.2f" % (
round((max_allowed_dob - self.date_of_birth).days / 365.0, 2))
return True
else:
raise Exception(
"Invalid Date: Date should be from January 01 1900 to Today's Date")
else:
if self.age and int(self.age[0:3]) <= 120:
self.date_of_bith = None
return True
else:
raise Exception("Invalid Date of Birth / Age Supplied")
return False
class PatientDetailForm(AuShadhaBaseModelForm):
"""
ModelForm for Patient Basic Data
"""
__form_name__ = "Patient Detail Form"
dijit_fields = PATIENT_DETAIL_FORM_CONSTANTS
class Meta:
model = PatientDetail
exclude = DEFAULT_PATIENT_DETAIL_FORM_EXCLUDES | false | true |
f71b75660891063679e5531c8f4789ea15fdf36c | 17,910 | py | Python | skimage/transform/radon_transform.py | jjhelmus/scikit-image | b9b5fde0821fe8bcece2528b30d012c65c64ad6f | [
"BSD-3-Clause"
] | 2 | 2017-03-30T11:22:11.000Z | 2019-03-03T05:18:01.000Z | skimage/transform/radon_transform.py | jjhelmus/scikit-image | b9b5fde0821fe8bcece2528b30d012c65c64ad6f | [
"BSD-3-Clause"
] | 3 | 2021-03-19T14:27:58.000Z | 2022-03-12T00:42:39.000Z | skimage/transform/radon_transform.py | jjhelmus/scikit-image | b9b5fde0821fe8bcece2528b30d012c65c64ad6f | [
"BSD-3-Clause"
] | 1 | 2019-12-17T14:53:28.000Z | 2019-12-17T14:53:28.000Z | # -*- coding: utf-8 -*-
"""
radon.py - Radon and inverse radon transforms
Based on code of Justin K. Romberg
(http://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html)
J. Gillam and Chris Griffin.
References:
-B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing
the Discrete Radon Transform With Some Applications", Proceedings of
the Fourth IEEE Region 10 International Conference, TENCON '89, 1989.
-A. C. Kak, Malcolm Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988.
"""
from __future__ import division
import numpy as np
from scipy.fftpack import fft, ifft, fftfreq
from scipy.interpolate import interp1d
from ._warps_cy import _warp_fast
from ._radon_transform import sart_projection_update
from .. import util
from warnings import warn
__all__ = ["radon", "iradon", "iradon_sart"]
def radon(image, theta=None, circle=False):
"""
Calculates the radon transform of an image given specified
projection angles.
Parameters
----------
image : array_like, dtype=float
Input image. The rotation axis will be located in the pixel with
indices ``(image.shape[0] // 2, image.shape[1] // 2)``.
theta : array_like, dtype=float, optional (default np.arange(180))
Projection angles (in degrees).
circle : boolean, optional
Assume image is zero outside the inscribed circle, making the
width of each projection (the first dimension of the sinogram)
equal to ``min(image.shape)``.
Returns
-------
radon_image : ndarray
Radon transform (sinogram). The tomography rotation axis will lie
at the pixel index ``radon_image.shape[0] // 2`` along the 0th
dimension of ``radon_image``.
"""
if image.ndim != 2:
raise ValueError('The input image must be 2-D')
if theta is None:
theta = np.arange(180)
if circle:
radius = min(image.shape) // 2
c0, c1 = np.ogrid[0:image.shape[0], 0:image.shape[1]]
reconstruction_circle = ((c0 - image.shape[0] // 2) ** 2
+ (c1 - image.shape[1] // 2) ** 2)
reconstruction_circle = reconstruction_circle <= radius ** 2
if not np.all(reconstruction_circle | (image == 0)):
warn('Radon transform: image must be zero outside the '
'reconstruction circle')
# Crop image to make it square
slices = []
for d in (0, 1):
if image.shape[d] > min(image.shape):
excess = image.shape[d] - min(image.shape)
slices.append(slice(int(np.ceil(excess / 2)),
int(np.ceil(excess / 2)
+ min(image.shape))))
else:
slices.append(slice(None))
slices = tuple(slices)
padded_image = image[slices]
else:
diagonal = np.sqrt(2) * max(image.shape)
pad = [int(np.ceil(diagonal - s)) for s in image.shape]
new_center = [(s + p) // 2 for s, p in zip(image.shape, pad)]
old_center = [s // 2 for s in image.shape]
pad_before = [nc - oc for oc, nc in zip(old_center, new_center)]
pad_width = [(pb, p - pb) for pb, p in zip(pad_before, pad)]
padded_image = util.pad(image, pad_width, mode='constant',
constant_values=0)
# padded_image is always square
assert padded_image.shape[0] == padded_image.shape[1]
radon_image = np.zeros((padded_image.shape[0], len(theta)))
center = padded_image.shape[0] // 2
shift0 = np.array([[1, 0, -center],
[0, 1, -center],
[0, 0, 1]])
shift1 = np.array([[1, 0, center],
[0, 1, center],
[0, 0, 1]])
def build_rotation(theta):
T = np.deg2rad(theta)
R = np.array([[np.cos(T), np.sin(T), 0],
[-np.sin(T), np.cos(T), 0],
[0, 0, 1]])
return shift1.dot(R).dot(shift0)
for i in range(len(theta)):
rotated = _warp_fast(padded_image, build_rotation(theta[i]))
radon_image[:, i] = rotated.sum(0)
return radon_image
def _sinogram_circle_to_square(sinogram):
diagonal = int(np.ceil(np.sqrt(2) * sinogram.shape[0]))
pad = diagonal - sinogram.shape[0]
old_center = sinogram.shape[0] // 2
new_center = diagonal // 2
pad_before = new_center - old_center
pad_width = ((pad_before, pad - pad_before), (0, 0))
return util.pad(sinogram, pad_width, mode='constant', constant_values=0)
def iradon(radon_image, theta=None, output_size=None,
filter="ramp", interpolation="linear", circle=False):
"""
Inverse radon transform.
Reconstruct an image from the radon transform, using the filtered
back projection algorithm.
Parameters
----------
radon_image : array_like, dtype=float
Image containing radon transform (sinogram). Each column of
the image corresponds to a projection along a different angle. The
tomography rotation axis should lie at the pixel index
``radon_image.shape[0] // 2`` along the 0th dimension of
``radon_image``.
theta : array_like, dtype=float, optional
Reconstruction angles (in degrees). Default: m angles evenly spaced
between 0 and 180 (if the shape of `radon_image` is (N, M)).
output_size : int
Number of rows and columns in the reconstruction.
filter : str, optional (default ramp)
Filter used in frequency domain filtering. Ramp filter used by default.
Filters available: ramp, shepp-logan, cosine, hamming, hann.
Assign None to use no filter.
interpolation : str, optional (default 'linear')
Interpolation method used in reconstruction. Methods available:
'linear', 'nearest', and 'cubic' ('cubic' is slow).
circle : boolean, optional
Assume the reconstructed image is zero outside the inscribed circle.
Also changes the default output_size to match the behaviour of
``radon`` called with ``circle=True``.
Returns
-------
reconstructed : ndarray
Reconstructed image. The rotation axis will be located in the pixel
with indices
``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.
Notes
-----
It applies the Fourier slice theorem to reconstruct an image by
multiplying the frequency domain of the filter with the FFT of the
projection data. This algorithm is called filtered back projection.
"""
if radon_image.ndim != 2:
raise ValueError('The input image must be 2-D')
if theta is None:
m, n = radon_image.shape
theta = np.linspace(0, 180, n, endpoint=False)
else:
theta = np.asarray(theta)
if len(theta) != radon_image.shape[1]:
raise ValueError("The given ``theta`` does not match the number of "
"projections in ``radon_image``.")
interpolation_types = ('linear', 'nearest', 'cubic')
if not interpolation in interpolation_types:
raise ValueError("Unknown interpolation: %s" % interpolation)
if not output_size:
# If output size not specified, estimate from input radon image
if circle:
output_size = radon_image.shape[0]
else:
output_size = int(np.floor(np.sqrt((radon_image.shape[0]) ** 2
/ 2.0)))
if circle:
radon_image = _sinogram_circle_to_square(radon_image)
th = (np.pi / 180.0) * theta
# resize image to next power of two (but no less than 64) for
# Fourier analysis; speeds up Fourier and lessens artifacts
projection_size_padded = \
max(64, int(2 ** np.ceil(np.log2(2 * radon_image.shape[0]))))
pad_width = ((0, projection_size_padded - radon_image.shape[0]), (0, 0))
img = util.pad(radon_image, pad_width, mode='constant', constant_values=0)
# Construct the Fourier filter
f = fftfreq(projection_size_padded).reshape(-1, 1) # digital frequency
omega = 2 * np.pi * f # angular frequency
fourier_filter = 2 * np.abs(f) # ramp filter
if filter == "ramp":
pass
elif filter == "shepp-logan":
# Start from first element to avoid divide by zero
fourier_filter[1:] = fourier_filter[1:] * np.sin(omega[1:]) / omega[1:]
elif filter == "cosine":
fourier_filter *= np.cos(omega)
elif filter == "hamming":
fourier_filter *= (0.54 + 0.46 * np.cos(omega / 2))
elif filter == "hann":
fourier_filter *= (1 + np.cos(omega / 2)) / 2
elif filter is None:
fourier_filter[:] = 1
else:
raise ValueError("Unknown filter: %s" % filter)
# Apply filter in Fourier domain
projection = fft(img, axis=0) * fourier_filter
radon_filtered = np.real(ifft(projection, axis=0))
# Resize filtered image back to original size
radon_filtered = radon_filtered[:radon_image.shape[0], :]
reconstructed = np.zeros((output_size, output_size))
# Determine the center of the projections (= center of sinogram)
mid_index = radon_image.shape[0] // 2
[X, Y] = np.mgrid[0:output_size, 0:output_size]
xpr = X - int(output_size) // 2
ypr = Y - int(output_size) // 2
# Reconstruct image by interpolation
for i in range(len(theta)):
t = ypr * np.cos(th[i]) - xpr * np.sin(th[i])
x = np.arange(radon_filtered.shape[0]) - mid_index
if interpolation == 'linear':
backprojected = np.interp(t, x, radon_filtered[:, i],
left=0, right=0)
else:
interpolant = interp1d(x, radon_filtered[:, i], kind=interpolation,
bounds_error=False, fill_value=0)
backprojected = interpolant(t)
reconstructed += backprojected
if circle:
radius = output_size // 2
reconstruction_circle = (xpr ** 2 + ypr ** 2) <= radius ** 2
reconstructed[~reconstruction_circle] = 0.
return reconstructed * np.pi / (2 * len(th))
def order_angles_golden_ratio(theta):
"""
Order angles to reduce the amount of correlated information
in subsequent projections.
Parameters
----------
theta : 1D array of floats
Projection angles in degrees. Duplicate angles are not allowed.
Returns
-------
indices_generator : generator yielding unsigned integers
The returned generator yields indices into ``theta`` such that
``theta[indices]`` gives the approximate golden ratio ordering
of the projections. In total, ``len(theta)`` indices are yielded.
All non-negative integers < ``len(theta)`` are yielded exactly once.
Notes
-----
The method used here is that of the golden ratio introduced
by T. Kohler.
References
----------
.. [1] Kohler, T. "A projection access scheme for iterative
reconstruction based on the golden section." Nuclear Science
Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
.. [2] Winkelmann, Stefanie, et al. "An optimal radial profile order
based on the Golden Ratio for time-resolved MRI."
Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76.
"""
interval = 180
def angle_distance(a, b):
difference = a - b
return min(abs(difference % interval), abs(difference % -interval))
remaining = list(np.argsort(theta)) # indices into theta
# yield an arbitrary angle to start things off
index = remaining.pop(0)
angle = theta[index]
yield index
# determine subsequent angles using the golden ratio method
angle_increment = interval * (1 - (np.sqrt(5) - 1) / 2)
while remaining:
angle = (angle + angle_increment) % interval
insert_point = np.searchsorted(theta[remaining], angle)
index_below = insert_point - 1
index_above = 0 if insert_point == len(remaining) else insert_point
distance_below = angle_distance(angle, theta[remaining[index_below]])
distance_above = angle_distance(angle, theta[remaining[index_above]])
if distance_below < distance_above:
yield remaining.pop(index_below)
else:
yield remaining.pop(index_above)
def iradon_sart(radon_image, theta=None, image=None, projection_shifts=None,
clip=None, relaxation=0.15):
"""
Inverse radon transform
Reconstruct an image from the radon transform, using a single iteration of
the Simultaneous Algebraic Reconstruction Technique (SART) algorithm.
Parameters
----------
radon_image : 2D array, dtype=float
Image containing radon transform (sinogram). Each column of
the image corresponds to a projection along a different angle. The
tomography rotation axis should lie at the pixel index
``radon_image.shape[0] // 2`` along the 0th dimension of
``radon_image``.
theta : 1D array, dtype=float, optional
Reconstruction angles (in degrees). Default: m angles evenly spaced
between 0 and 180 (if the shape of `radon_image` is (N, M)).
image : 2D array, dtype=float, optional
Image containing an initial reconstruction estimate. Shape of this
array should be ``(radon_image.shape[0], radon_image.shape[0])``. The
default is an array of zeros.
projection_shifts : 1D array, dtype=float
Shift the projections contained in ``radon_image`` (the sinogram) by
this many pixels before reconstructing the image. The i'th value
defines the shift of the i'th column of ``radon_image``.
clip : length-2 sequence of floats
Force all values in the reconstructed tomogram to lie in the range
``[clip[0], clip[1]]``
relaxation : float
Relaxation parameter for the update step. A higher value can
improve the convergence rate, but one runs the risk of instabilities.
Values close to or higher than 1 are not recommended.
Returns
-------
reconstructed : ndarray
Reconstructed image. The rotation axis will be located in the pixel
with indices
``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``.
Notes
-----
Algebraic Reconstruction Techniques are based on formulating the tomography
reconstruction problem as a set of linear equations. Along each ray,
the projected value is the sum of all the values of the cross section along
the ray. A typical feature of SART (and a few other variants of algebraic
techniques) is that it samples the cross section at equidistant points
along the ray, using linear interpolation between the pixel values of the
cross section. The resulting set of linear equations are then solved using
a slightly modified Kaczmarz method.
When using SART, a single iteration is usually sufficient to obtain a good
reconstruction. Further iterations will tend to enhance high-frequency
information, but will also often increase the noise.
References
----------
.. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic
Imaging", IEEE Press 1988.
.. [2] AH Andersen, AC Kak, "Simultaneous algebraic reconstruction
technique (SART): a superior implementation of the ART algorithm",
Ultrasonic Imaging 6 pp 81--94 (1984)
.. [3] S Kaczmarz, "Angenäherte auflösung von systemen linearer
gleichungen", Bulletin International de l’Academie Polonaise des
Sciences et des Lettres 35 pp 355--357 (1937)
.. [4] Kohler, T. "A projection access scheme for iterative
reconstruction based on the golden section." Nuclear Science
Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004.
.. [5] Kaczmarz' method, Wikipedia,
http://en.wikipedia.org/wiki/Kaczmarz_method
"""
if radon_image.ndim != 2:
raise ValueError('radon_image must be two dimensional')
reconstructed_shape = (radon_image.shape[0], radon_image.shape[0])
if theta is None:
theta = np.linspace(0, 180, radon_image.shape[1], endpoint=False)
elif theta.shape != (radon_image.shape[1],):
raise ValueError('Shape of theta (%s) does not match the '
'number of projections (%d)'
% (projection_shifts.shape, radon_image.shape[1]))
if image is None:
image = np.zeros(reconstructed_shape, dtype=np.float)
elif image.shape != reconstructed_shape:
raise ValueError('Shape of image (%s) does not match first dimension '
'of radon_image (%s)'
% (image.shape, reconstructed_shape))
if projection_shifts is None:
projection_shifts = np.zeros((radon_image.shape[1],), dtype=np.float)
elif projection_shifts.shape != (radon_image.shape[1],):
raise ValueError('Shape of projection_shifts (%s) does not match the '
'number of projections (%d)'
% (projection_shifts.shape, radon_image.shape[1]))
if not clip is None:
if len(clip) != 2:
raise ValueError('clip must be a length-2 sequence')
clip = (float(clip[0]), float(clip[1]))
relaxation = float(relaxation)
for angle_index in order_angles_golden_ratio(theta):
image_update = sart_projection_update(image, theta[angle_index],
radon_image[:, angle_index],
projection_shifts[angle_index])
image += relaxation * image_update
if not clip is None:
image = np.clip(image, clip[0], clip[1])
return image
| 42.541568 | 79 | 0.629202 |
from __future__ import division
import numpy as np
from scipy.fftpack import fft, ifft, fftfreq
from scipy.interpolate import interp1d
from ._warps_cy import _warp_fast
from ._radon_transform import sart_projection_update
from .. import util
from warnings import warn
__all__ = ["radon", "iradon", "iradon_sart"]
def radon(image, theta=None, circle=False):
if image.ndim != 2:
raise ValueError('The input image must be 2-D')
if theta is None:
theta = np.arange(180)
if circle:
radius = min(image.shape) // 2
c0, c1 = np.ogrid[0:image.shape[0], 0:image.shape[1]]
reconstruction_circle = ((c0 - image.shape[0] // 2) ** 2
+ (c1 - image.shape[1] // 2) ** 2)
reconstruction_circle = reconstruction_circle <= radius ** 2
if not np.all(reconstruction_circle | (image == 0)):
warn('Radon transform: image must be zero outside the '
'reconstruction circle')
slices = []
for d in (0, 1):
if image.shape[d] > min(image.shape):
excess = image.shape[d] - min(image.shape)
slices.append(slice(int(np.ceil(excess / 2)),
int(np.ceil(excess / 2)
+ min(image.shape))))
else:
slices.append(slice(None))
slices = tuple(slices)
padded_image = image[slices]
else:
diagonal = np.sqrt(2) * max(image.shape)
pad = [int(np.ceil(diagonal - s)) for s in image.shape]
new_center = [(s + p) // 2 for s, p in zip(image.shape, pad)]
old_center = [s // 2 for s in image.shape]
pad_before = [nc - oc for oc, nc in zip(old_center, new_center)]
pad_width = [(pb, p - pb) for pb, p in zip(pad_before, pad)]
padded_image = util.pad(image, pad_width, mode='constant',
constant_values=0)
assert padded_image.shape[0] == padded_image.shape[1]
radon_image = np.zeros((padded_image.shape[0], len(theta)))
center = padded_image.shape[0] // 2
shift0 = np.array([[1, 0, -center],
[0, 1, -center],
[0, 0, 1]])
shift1 = np.array([[1, 0, center],
[0, 1, center],
[0, 0, 1]])
def build_rotation(theta):
T = np.deg2rad(theta)
R = np.array([[np.cos(T), np.sin(T), 0],
[-np.sin(T), np.cos(T), 0],
[0, 0, 1]])
return shift1.dot(R).dot(shift0)
for i in range(len(theta)):
rotated = _warp_fast(padded_image, build_rotation(theta[i]))
radon_image[:, i] = rotated.sum(0)
return radon_image
def _sinogram_circle_to_square(sinogram):
diagonal = int(np.ceil(np.sqrt(2) * sinogram.shape[0]))
pad = diagonal - sinogram.shape[0]
old_center = sinogram.shape[0] // 2
new_center = diagonal // 2
pad_before = new_center - old_center
pad_width = ((pad_before, pad - pad_before), (0, 0))
return util.pad(sinogram, pad_width, mode='constant', constant_values=0)
def iradon(radon_image, theta=None, output_size=None,
filter="ramp", interpolation="linear", circle=False):
if radon_image.ndim != 2:
raise ValueError('The input image must be 2-D')
if theta is None:
m, n = radon_image.shape
theta = np.linspace(0, 180, n, endpoint=False)
else:
theta = np.asarray(theta)
if len(theta) != radon_image.shape[1]:
raise ValueError("The given ``theta`` does not match the number of "
"projections in ``radon_image``.")
interpolation_types = ('linear', 'nearest', 'cubic')
if not interpolation in interpolation_types:
raise ValueError("Unknown interpolation: %s" % interpolation)
if not output_size:
if circle:
output_size = radon_image.shape[0]
else:
output_size = int(np.floor(np.sqrt((radon_image.shape[0]) ** 2
/ 2.0)))
if circle:
radon_image = _sinogram_circle_to_square(radon_image)
th = (np.pi / 180.0) * theta
projection_size_padded = \
max(64, int(2 ** np.ceil(np.log2(2 * radon_image.shape[0]))))
pad_width = ((0, projection_size_padded - radon_image.shape[0]), (0, 0))
img = util.pad(radon_image, pad_width, mode='constant', constant_values=0)
f = fftfreq(projection_size_padded).reshape(-1, 1)
omega = 2 * np.pi * f
fourier_filter = 2 * np.abs(f)
if filter == "ramp":
pass
elif filter == "shepp-logan":
fourier_filter[1:] = fourier_filter[1:] * np.sin(omega[1:]) / omega[1:]
elif filter == "cosine":
fourier_filter *= np.cos(omega)
elif filter == "hamming":
fourier_filter *= (0.54 + 0.46 * np.cos(omega / 2))
elif filter == "hann":
fourier_filter *= (1 + np.cos(omega / 2)) / 2
elif filter is None:
fourier_filter[:] = 1
else:
raise ValueError("Unknown filter: %s" % filter)
projection = fft(img, axis=0) * fourier_filter
radon_filtered = np.real(ifft(projection, axis=0))
radon_filtered = radon_filtered[:radon_image.shape[0], :]
reconstructed = np.zeros((output_size, output_size))
mid_index = radon_image.shape[0] // 2
[X, Y] = np.mgrid[0:output_size, 0:output_size]
xpr = X - int(output_size) // 2
ypr = Y - int(output_size) // 2
for i in range(len(theta)):
t = ypr * np.cos(th[i]) - xpr * np.sin(th[i])
x = np.arange(radon_filtered.shape[0]) - mid_index
if interpolation == 'linear':
backprojected = np.interp(t, x, radon_filtered[:, i],
left=0, right=0)
else:
interpolant = interp1d(x, radon_filtered[:, i], kind=interpolation,
bounds_error=False, fill_value=0)
backprojected = interpolant(t)
reconstructed += backprojected
if circle:
radius = output_size // 2
reconstruction_circle = (xpr ** 2 + ypr ** 2) <= radius ** 2
reconstructed[~reconstruction_circle] = 0.
return reconstructed * np.pi / (2 * len(th))
def order_angles_golden_ratio(theta):
interval = 180
def angle_distance(a, b):
difference = a - b
return min(abs(difference % interval), abs(difference % -interval))
remaining = list(np.argsort(theta))
index = remaining.pop(0)
angle = theta[index]
yield index
angle_increment = interval * (1 - (np.sqrt(5) - 1) / 2)
while remaining:
angle = (angle + angle_increment) % interval
insert_point = np.searchsorted(theta[remaining], angle)
index_below = insert_point - 1
index_above = 0 if insert_point == len(remaining) else insert_point
distance_below = angle_distance(angle, theta[remaining[index_below]])
distance_above = angle_distance(angle, theta[remaining[index_above]])
if distance_below < distance_above:
yield remaining.pop(index_below)
else:
yield remaining.pop(index_above)
def iradon_sart(radon_image, theta=None, image=None, projection_shifts=None,
clip=None, relaxation=0.15):
if radon_image.ndim != 2:
raise ValueError('radon_image must be two dimensional')
reconstructed_shape = (radon_image.shape[0], radon_image.shape[0])
if theta is None:
theta = np.linspace(0, 180, radon_image.shape[1], endpoint=False)
elif theta.shape != (radon_image.shape[1],):
raise ValueError('Shape of theta (%s) does not match the '
'number of projections (%d)'
% (projection_shifts.shape, radon_image.shape[1]))
if image is None:
image = np.zeros(reconstructed_shape, dtype=np.float)
elif image.shape != reconstructed_shape:
raise ValueError('Shape of image (%s) does not match first dimension '
'of radon_image (%s)'
% (image.shape, reconstructed_shape))
if projection_shifts is None:
projection_shifts = np.zeros((radon_image.shape[1],), dtype=np.float)
elif projection_shifts.shape != (radon_image.shape[1],):
raise ValueError('Shape of projection_shifts (%s) does not match the '
'number of projections (%d)'
% (projection_shifts.shape, radon_image.shape[1]))
if not clip is None:
if len(clip) != 2:
raise ValueError('clip must be a length-2 sequence')
clip = (float(clip[0]), float(clip[1]))
relaxation = float(relaxation)
for angle_index in order_angles_golden_ratio(theta):
image_update = sart_projection_update(image, theta[angle_index],
radon_image[:, angle_index],
projection_shifts[angle_index])
image += relaxation * image_update
if not clip is None:
image = np.clip(image, clip[0], clip[1])
return image
| true | true |
f71b763ae51e39e2fc92c256e70e59add5287950 | 12,944 | py | Python | stix2/datastore/memory.py | 2xyo/cti-python-stix2 | cffee92c7ed18c4cdd54c4370c6a17878dfd36cd | [
"BSD-3-Clause"
] | 1 | 2020-08-17T23:53:48.000Z | 2020-08-17T23:53:48.000Z | stix2/datastore/memory.py | 2xyo/cti-python-stix2 | cffee92c7ed18c4cdd54c4370c6a17878dfd36cd | [
"BSD-3-Clause"
] | null | null | null | stix2/datastore/memory.py | 2xyo/cti-python-stix2 | cffee92c7ed18c4cdd54c4370c6a17878dfd36cd | [
"BSD-3-Clause"
] | null | null | null | """Python STIX2 Memory Source/Sink"""
import io
import itertools
import json
import os
from stix2 import v20, v21
from stix2.base import _STIXBase
from stix2.datastore import DataSink, DataSource, DataStoreMixin
from stix2.datastore.filters import FilterSet, apply_common_filters
from stix2.parsing import parse
def _add(store, stix_data, allow_custom=True, version=None):
"""Add STIX objects to MemoryStore/Sink.
Adds STIX objects to an in-memory dictionary for fast lookup.
Recursive function, breaks down STIX Bundles and lists.
Args:
store: A MemoryStore, MemorySink or MemorySource object.
stix_data (list OR dict OR STIX object): STIX objects to be added
allow_custom (bool): Whether to allow custom properties as well unknown
custom objects. Note that unknown custom objects cannot be parsed
into STIX objects, and will be returned as is. Default: False.
version (str): Which STIX2 version to lock the parser to. (e.g. "2.0",
"2.1"). If None, the library makes the best effort to figure
out the spec representation of the object.
"""
if isinstance(stix_data, list):
# STIX objects are in a list- recurse on each object
for stix_obj in stix_data:
_add(store, stix_obj, allow_custom, version)
elif stix_data["type"] == "bundle":
# adding a json bundle - so just grab STIX objects
for stix_obj in stix_data.get("objects", []):
_add(store, stix_obj, allow_custom, version)
else:
# Adding a single non-bundle object
if isinstance(stix_data, _STIXBase):
stix_obj = stix_data
else:
stix_obj = parse(stix_data, allow_custom, version)
# Map ID to a _ObjectFamily if the object is versioned, so we can track
# multiple versions. Otherwise, map directly to the object. All
# versioned objects should have a "modified" property.
if "modified" in stix_obj:
if stix_obj["id"] in store._data:
obj_family = store._data[stix_obj["id"]]
else:
obj_family = _ObjectFamily()
store._data[stix_obj["id"]] = obj_family
obj_family.add(stix_obj)
else:
store._data[stix_obj["id"]] = stix_obj
class _ObjectFamily(object):
"""
An internal implementation detail of memory sources/sinks/stores.
Represents a "family" of STIX objects: all objects with a particular
ID. (I.e. all versions.) The latest version is also tracked so that it
can be obtained quickly.
"""
def __init__(self):
self.all_versions = {}
self.latest_version = None
def add(self, obj):
self.all_versions[obj["modified"]] = obj
if (self.latest_version is None or
obj["modified"] > self.latest_version["modified"]):
self.latest_version = obj
def __str__(self):
return "<<{}; latest={}>>".format(
self.all_versions,
self.latest_version["modified"],
)
def __repr__(self):
return str(self)
class MemoryStore(DataStoreMixin):
"""Interface to an in-memory dictionary of STIX objects.
MemoryStore is a wrapper around a paired MemorySink and MemorySource.
Note: It doesn't make sense to create a MemoryStore by passing
in existing MemorySource and MemorySink because there could
be data concurrency issues. As well, just as easy to create new MemoryStore.
Args:
stix_data (list OR dict OR STIX object): STIX content to be added
allow_custom (bool): whether to allow custom STIX content.
Only applied when export/input functions called, i.e.
load_from_file() and save_to_file(). Defaults to True.
Attributes:
_data (dict): the in-memory dict that holds STIX objects
source (MemorySource): MemorySource
sink (MemorySink): MemorySink
"""
def __init__(self, stix_data=None, allow_custom=True, version=None):
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
super(MemoryStore, self).__init__(
source=MemorySource(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True),
sink=MemorySink(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True),
)
def save_to_file(self, *args, **kwargs):
"""Write SITX objects from in-memory dictionary to JSON file, as a STIX
Bundle. If a directory is given, the Bundle 'id' will be used as
filename. Otherwise, the provided value will be used.
Args:
path (str): file path to write STIX data to.
encoding (str): The file encoding. Default utf-8.
"""
return self.sink.save_to_file(*args, **kwargs)
def load_from_file(self, *args, **kwargs):
"""Load STIX data from JSON file.
File format is expected to be a single JSON STIX object or JSON STIX
bundle.
Args:
path (str): file path to load STIX data from
"""
return self.source.load_from_file(*args, **kwargs)
class MemorySink(DataSink):
"""Interface for adding/pushing STIX objects to an in-memory dictionary.
Designed to be paired with a MemorySource, together as the two
components of a MemoryStore.
Args:
stix_data (dict OR list): valid STIX 2.0 content in
bundle or a list.
_store (bool): whether the MemorySink is a part of a MemoryStore,
in which case "stix_data" is a direct reference to
shared memory with DataSource. Not user supplied
allow_custom (bool): whether to allow custom objects/properties
when exporting STIX content to file.
Default: True.
version (str): If present, it forces the parser to use the version
provided. Otherwise, the library will make the best effort based
on checking the "spec_version" property.
Attributes:
_data (dict): the in-memory dict that holds STIX objects.
If part of a MemoryStore, the dict is shared with a MemorySource
"""
def __init__(self, stix_data=None, allow_custom=True, version=None, _store=False):
super(MemorySink, self).__init__()
self.allow_custom = allow_custom
if _store:
self._data = stix_data
else:
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
def add(self, stix_data, version=None):
_add(self, stix_data, self.allow_custom, version)
add.__doc__ = _add.__doc__
def save_to_file(self, path, encoding="utf-8"):
path = os.path.abspath(path)
all_objs = list(itertools.chain.from_iterable(
value.all_versions.values() if isinstance(value, _ObjectFamily)
else [value]
for value in self._data.values()
))
if any("spec_version" in x for x in all_objs):
bundle = v21.Bundle(all_objs, allow_custom=self.allow_custom)
else:
bundle = v20.Bundle(all_objs, allow_custom=self.allow_custom)
if path.endswith(".json"):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
else:
if not os.path.exists(path):
os.makedirs(path)
# if the user only provided a directory, use the bundle id for filename
path = os.path.join(path, bundle["id"] + ".json")
with io.open(path, "w", encoding=encoding) as f:
bundle = bundle.serialize(pretty=True, encoding=encoding, ensure_ascii=False)
f.write(bundle)
return path
save_to_file.__doc__ = MemoryStore.save_to_file.__doc__
class MemorySource(DataSource):
"""Interface for searching/retrieving STIX objects from an in-memory
dictionary.
Designed to be paired with a MemorySink, together as the two
components of a MemoryStore.
Args:
stix_data (dict OR list OR STIX object): valid STIX 2.0 content in
bundle or list.
_store (bool): if the MemorySource is a part of a MemoryStore,
in which case "stix_data" is a direct reference to shared
memory with DataSink. Not user supplied
allow_custom (bool): whether to allow custom objects/properties
when importing STIX content from file.
Default: True.
version (str): If present, it forces the parser to use the version
provided. Otherwise, the library will make the best effort based
on checking the "spec_version" property.
Attributes:
_data (dict): the in-memory dict that holds STIX objects.
If part of a MemoryStore, the dict is shared with a MemorySink
"""
def __init__(self, stix_data=None, allow_custom=True, version=None, _store=False):
super(MemorySource, self).__init__()
self.allow_custom = allow_custom
if _store:
self._data = stix_data
else:
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
def get(self, stix_id, _composite_filters=None):
"""Retrieve STIX object from in-memory dict via STIX ID.
Args:
stix_id (str): The STIX ID of the STIX object to be retrieved.
_composite_filters (FilterSet): collection of filters passed from the parent
CompositeDataSource, not user supplied
Returns:
(STIX object): STIX object that has the supplied ID.
"""
stix_obj = None
mapped_value = self._data.get(stix_id)
if mapped_value:
if isinstance(mapped_value, _ObjectFamily):
stix_obj = mapped_value.latest_version
else:
stix_obj = mapped_value
if stix_obj:
all_filters = list(
itertools.chain(
_composite_filters or [],
self.filters,
),
)
stix_obj = next(apply_common_filters([stix_obj], all_filters), None)
return stix_obj
def all_versions(self, stix_id, _composite_filters=None):
"""Retrieve STIX objects from in-memory dict via STIX ID, all versions
of it.
Args:
stix_id (str): The STIX ID of the STIX 2 object to retrieve.
_composite_filters (FilterSet): collection of filters passed from
the parent CompositeDataSource, not user supplied
Returns:
(list): list of STIX objects that have the supplied ID.
"""
results = []
mapped_value = self._data.get(stix_id)
if mapped_value:
if isinstance(mapped_value, _ObjectFamily):
stix_objs_to_filter = mapped_value.all_versions.values()
else:
stix_objs_to_filter = [mapped_value]
all_filters = list(
itertools.chain(
_composite_filters or [],
self.filters,
),
)
results.extend(
apply_common_filters(stix_objs_to_filter, all_filters),
)
return results
def query(self, query=None, _composite_filters=None):
"""Search and retrieve STIX objects based on the complete query.
A "complete query" includes the filters from the query, the filters
attached to this MemorySource, and any filters passed from a
CompositeDataSource (i.e. _composite_filters).
Args:
query (list): list of filters to search on
_composite_filters (FilterSet): collection of filters passed from
the CompositeDataSource, not user supplied
Returns:
(list): list of STIX objects that match the supplied query.
"""
query = FilterSet(query)
# combine all query filters
if self.filters:
query.add(self.filters)
if _composite_filters:
query.add(_composite_filters)
all_objs = itertools.chain.from_iterable(
value.all_versions.values() if isinstance(value, _ObjectFamily)
else [value]
for value in self._data.values()
)
# Apply STIX common property filters.
all_data = list(apply_common_filters(all_objs, query))
return all_data
def load_from_file(self, file_path, version=None, encoding='utf-8'):
with io.open(os.path.abspath(file_path), "r", encoding=encoding) as f:
stix_data = json.load(f)
_add(self, stix_data, self.allow_custom, version)
load_from_file.__doc__ = MemoryStore.load_from_file.__doc__
| 35.56044 | 111 | 0.627704 |
import io
import itertools
import json
import os
from stix2 import v20, v21
from stix2.base import _STIXBase
from stix2.datastore import DataSink, DataSource, DataStoreMixin
from stix2.datastore.filters import FilterSet, apply_common_filters
from stix2.parsing import parse
def _add(store, stix_data, allow_custom=True, version=None):
if isinstance(stix_data, list):
for stix_obj in stix_data:
_add(store, stix_obj, allow_custom, version)
elif stix_data["type"] == "bundle":
for stix_obj in stix_data.get("objects", []):
_add(store, stix_obj, allow_custom, version)
else:
if isinstance(stix_data, _STIXBase):
stix_obj = stix_data
else:
stix_obj = parse(stix_data, allow_custom, version)
if "modified" in stix_obj:
if stix_obj["id"] in store._data:
obj_family = store._data[stix_obj["id"]]
else:
obj_family = _ObjectFamily()
store._data[stix_obj["id"]] = obj_family
obj_family.add(stix_obj)
else:
store._data[stix_obj["id"]] = stix_obj
class _ObjectFamily(object):
def __init__(self):
self.all_versions = {}
self.latest_version = None
def add(self, obj):
self.all_versions[obj["modified"]] = obj
if (self.latest_version is None or
obj["modified"] > self.latest_version["modified"]):
self.latest_version = obj
def __str__(self):
return "<<{}; latest={}>>".format(
self.all_versions,
self.latest_version["modified"],
)
def __repr__(self):
return str(self)
class MemoryStore(DataStoreMixin):
def __init__(self, stix_data=None, allow_custom=True, version=None):
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
super(MemoryStore, self).__init__(
source=MemorySource(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True),
sink=MemorySink(stix_data=self._data, allow_custom=allow_custom, version=version, _store=True),
)
def save_to_file(self, *args, **kwargs):
return self.sink.save_to_file(*args, **kwargs)
def load_from_file(self, *args, **kwargs):
return self.source.load_from_file(*args, **kwargs)
class MemorySink(DataSink):
def __init__(self, stix_data=None, allow_custom=True, version=None, _store=False):
super(MemorySink, self).__init__()
self.allow_custom = allow_custom
if _store:
self._data = stix_data
else:
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
def add(self, stix_data, version=None):
_add(self, stix_data, self.allow_custom, version)
add.__doc__ = _add.__doc__
def save_to_file(self, path, encoding="utf-8"):
path = os.path.abspath(path)
all_objs = list(itertools.chain.from_iterable(
value.all_versions.values() if isinstance(value, _ObjectFamily)
else [value]
for value in self._data.values()
))
if any("spec_version" in x for x in all_objs):
bundle = v21.Bundle(all_objs, allow_custom=self.allow_custom)
else:
bundle = v20.Bundle(all_objs, allow_custom=self.allow_custom)
if path.endswith(".json"):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
else:
if not os.path.exists(path):
os.makedirs(path)
path = os.path.join(path, bundle["id"] + ".json")
with io.open(path, "w", encoding=encoding) as f:
bundle = bundle.serialize(pretty=True, encoding=encoding, ensure_ascii=False)
f.write(bundle)
return path
save_to_file.__doc__ = MemoryStore.save_to_file.__doc__
class MemorySource(DataSource):
def __init__(self, stix_data=None, allow_custom=True, version=None, _store=False):
super(MemorySource, self).__init__()
self.allow_custom = allow_custom
if _store:
self._data = stix_data
else:
self._data = {}
if stix_data:
_add(self, stix_data, allow_custom, version)
def get(self, stix_id, _composite_filters=None):
stix_obj = None
mapped_value = self._data.get(stix_id)
if mapped_value:
if isinstance(mapped_value, _ObjectFamily):
stix_obj = mapped_value.latest_version
else:
stix_obj = mapped_value
if stix_obj:
all_filters = list(
itertools.chain(
_composite_filters or [],
self.filters,
),
)
stix_obj = next(apply_common_filters([stix_obj], all_filters), None)
return stix_obj
def all_versions(self, stix_id, _composite_filters=None):
results = []
mapped_value = self._data.get(stix_id)
if mapped_value:
if isinstance(mapped_value, _ObjectFamily):
stix_objs_to_filter = mapped_value.all_versions.values()
else:
stix_objs_to_filter = [mapped_value]
all_filters = list(
itertools.chain(
_composite_filters or [],
self.filters,
),
)
results.extend(
apply_common_filters(stix_objs_to_filter, all_filters),
)
return results
def query(self, query=None, _composite_filters=None):
query = FilterSet(query)
if self.filters:
query.add(self.filters)
if _composite_filters:
query.add(_composite_filters)
all_objs = itertools.chain.from_iterable(
value.all_versions.values() if isinstance(value, _ObjectFamily)
else [value]
for value in self._data.values()
)
all_data = list(apply_common_filters(all_objs, query))
return all_data
def load_from_file(self, file_path, version=None, encoding='utf-8'):
with io.open(os.path.abspath(file_path), "r", encoding=encoding) as f:
stix_data = json.load(f)
_add(self, stix_data, self.allow_custom, version)
load_from_file.__doc__ = MemoryStore.load_from_file.__doc__
| true | true |
f71b769c9bfe02547922c7632d7e21d4cba88350 | 6,126 | py | Python | aoc/solutions/day08/solution.py | SebastiaanZ/aoc-2020 | e5480be10da053a6ad382dc27fcea7890986cd8e | [
"MIT"
] | 3 | 2020-12-08T13:36:32.000Z | 2020-12-15T11:37:25.000Z | aoc/solutions/day08/solution.py | SebastiaanZ/aoc-2020 | e5480be10da053a6ad382dc27fcea7890986cd8e | [
"MIT"
] | null | null | null | aoc/solutions/day08/solution.py | SebastiaanZ/aoc-2020 | e5480be10da053a6ad382dc27fcea7890986cd8e | [
"MIT"
] | null | null | null | from __future__ import annotations
import collections
import logging
import typing
from aoc.helpers import Puzzle
__all__ = ["part_one", "part_two", "prepare_puzzle"]
log = logging.getLogger(__name__)
class Instruction(typing.NamedTuple):
"""A ConsoleApplication instruction."""
operation: str
argument: int
@classmethod
def from_text(cls, instruction: str) -> Instruction:
"""Parse a raw text instruction and return an Instruction instance."""
operation, raw_argument = instruction.split(" ")
return cls(operation=operation, argument=int(raw_argument))
class ApplicationState(typing.NamedTuple):
"""An application exit state."""
success: bool
value: int
class ConsoleApplication:
"""A virtual handheld game console."""
def __init__(self, instructions: dict[int, Instruction]) -> None:
"""Parse the instructions and load the application into memory."""
self.instructions = dict(instructions)
self.pointer = 0
self.accumulator = 0
@classmethod
def from_raw_instructions(
cls: type[ConsoleApplication],
instructions: list[str]
) -> ConsoleApplication:
"""Create an application from a raw instruction set."""
instructions = {
i: Instruction.from_text(instruction) for i, instruction in enumerate(instructions)
}
return cls(instructions=instructions)
def copy(self) -> ConsoleApplication:
"""Create a copy of the application."""
return type(self)(self.instructions)
def run(self, debug_mode: bool = False) -> ApplicationState:
"""
Run the application and return the final accumulator value as the exit code.
If run in safe mode, the application returns whenever it detects it has
entered an infinite loop by keeping track of the instructions it has
executed previously.
"""
if debug_mode:
seen = set()
while True:
if self.pointer in seen:
return ApplicationState(success=False, value=self.accumulator)
if self.pointer == len(self.instructions):
return ApplicationState(success=True, value=self.accumulator)
seen.add(self.pointer)
self.step()
else:
while True:
self.step()
if self.pointer == len(self.instructions):
return ApplicationState(success=True, value=self.accumulator)
def step(self) -> None:
"""Perform a single step in the application."""
operation, argument = self.instructions[self.pointer]
getattr(self, operation)(argument)
def acc(self, value: int) -> None:
"""Add a `value` to the accumulator and increase the pointer by one."""
self.accumulator += value
self.pointer += 1
def jmp(self, steps: int) -> None:
"""Execute a jump to another instruction relative to its own location."""
self.pointer += steps
def nop(self, _argument: int) -> None:
"""Do not do anything at all except going to the next instruction."""
self.pointer += 1
def debugger(application: ConsoleApplication) -> int:
"""
Debug a ConsoleApplication by tracing terminating paths.
This debugger works by taking the followings steps:
1. For each instruction position, determine which instructions end up there;
2. Use the instruction targets to trace which instructions will end up at
the termination location;
3. Run to the application, checking if an operation flip would make us jump
to a halting path target location.
It returns the final value after the application has halted successfully.
"""
# 1. For each instruction location, determine which instructions end up there.
instruction_destinations = collections.defaultdict(list)
for i, (instruction, value) in reversed(application.instructions.items()):
if instruction == "jmp":
instruction_destinations[i + value].append(i)
else:
instruction_destinations[i + 1].append(i)
# 2. Use the target locations of instructions to determine which
# instructions already lead naturally to the halting position.
targets = {len(application.instructions)}
targets_to_check = {len(application.instructions)}
while True:
new_targets = set()
for target in targets_to_check:
new_targets.update(instruction_destinations[target])
if not new_targets:
# No other instructions end up at an identified target instruction.
break
targets_to_check = new_targets
targets.update(new_targets)
# 3. Run the application, checking for each `jmp` or `nop` instruction if
# flipping it would result in the application hitting a target instruction.
debugged = False
while application.pointer != len(application.instructions):
operation, argument = application.instructions[application.pointer]
if not debugged and operation == "jmp" and application.pointer + 1 in targets:
application.pointer += 1
debugged = True
elif not debugged and operation == "nop" and application.pointer + argument in targets:
application.pointer += argument
debugged = True
else:
getattr(application, operation)(argument)
# Return the final value of the accumulator
return application.accumulator
def prepare_puzzle(puzzle: Puzzle) -> None:
"""Prepare the ConsoleApplication for today's puzzle."""
puzzle["application"] = ConsoleApplication.from_raw_instructions(puzzle.lines)
def part_one(puzzle: Puzzle) -> typing.Optional[typing.Union[str, int]]:
"""Return the solution for part one of this day."""
return puzzle["application"].run(debug_mode=True).value
def part_two(puzzle: Puzzle) -> typing.Optional[typing.Union[str, int]]:
"""Return the solution for part two of this day."""
return debugger(puzzle["application"].copy())
| 36.464286 | 95 | 0.663728 | from __future__ import annotations
import collections
import logging
import typing
from aoc.helpers import Puzzle
__all__ = ["part_one", "part_two", "prepare_puzzle"]
log = logging.getLogger(__name__)
class Instruction(typing.NamedTuple):
operation: str
argument: int
@classmethod
def from_text(cls, instruction: str) -> Instruction:
operation, raw_argument = instruction.split(" ")
return cls(operation=operation, argument=int(raw_argument))
class ApplicationState(typing.NamedTuple):
success: bool
value: int
class ConsoleApplication:
def __init__(self, instructions: dict[int, Instruction]) -> None:
self.instructions = dict(instructions)
self.pointer = 0
self.accumulator = 0
@classmethod
def from_raw_instructions(
cls: type[ConsoleApplication],
instructions: list[str]
) -> ConsoleApplication:
instructions = {
i: Instruction.from_text(instruction) for i, instruction in enumerate(instructions)
}
return cls(instructions=instructions)
def copy(self) -> ConsoleApplication:
return type(self)(self.instructions)
def run(self, debug_mode: bool = False) -> ApplicationState:
if debug_mode:
seen = set()
while True:
if self.pointer in seen:
return ApplicationState(success=False, value=self.accumulator)
if self.pointer == len(self.instructions):
return ApplicationState(success=True, value=self.accumulator)
seen.add(self.pointer)
self.step()
else:
while True:
self.step()
if self.pointer == len(self.instructions):
return ApplicationState(success=True, value=self.accumulator)
def step(self) -> None:
operation, argument = self.instructions[self.pointer]
getattr(self, operation)(argument)
def acc(self, value: int) -> None:
self.accumulator += value
self.pointer += 1
def jmp(self, steps: int) -> None:
self.pointer += steps
def nop(self, _argument: int) -> None:
self.pointer += 1
def debugger(application: ConsoleApplication) -> int:
instruction_destinations = collections.defaultdict(list)
for i, (instruction, value) in reversed(application.instructions.items()):
if instruction == "jmp":
instruction_destinations[i + value].append(i)
else:
instruction_destinations[i + 1].append(i)
targets = {len(application.instructions)}
targets_to_check = {len(application.instructions)}
while True:
new_targets = set()
for target in targets_to_check:
new_targets.update(instruction_destinations[target])
if not new_targets:
break
targets_to_check = new_targets
targets.update(new_targets)
debugged = False
while application.pointer != len(application.instructions):
operation, argument = application.instructions[application.pointer]
if not debugged and operation == "jmp" and application.pointer + 1 in targets:
application.pointer += 1
debugged = True
elif not debugged and operation == "nop" and application.pointer + argument in targets:
application.pointer += argument
debugged = True
else:
getattr(application, operation)(argument)
return application.accumulator
def prepare_puzzle(puzzle: Puzzle) -> None:
puzzle["application"] = ConsoleApplication.from_raw_instructions(puzzle.lines)
def part_one(puzzle: Puzzle) -> typing.Optional[typing.Union[str, int]]:
return puzzle["application"].run(debug_mode=True).value
def part_two(puzzle: Puzzle) -> typing.Optional[typing.Union[str, int]]:
return debugger(puzzle["application"].copy())
| true | true |
f71b78508ce2826de11a533ccf49d10b6b2ff055 | 25,387 | py | Python | pyabc/epsilon/temperature.py | chrhck/pyABC | 731cfdec26bef3898bf6e244daa5c8f83f3fe19d | [
"BSD-3-Clause"
] | null | null | null | pyabc/epsilon/temperature.py | chrhck/pyABC | 731cfdec26bef3898bf6e244daa5c8f83f3fe19d | [
"BSD-3-Clause"
] | null | null | null | pyabc/epsilon/temperature.py | chrhck/pyABC | 731cfdec26bef3898bf6e244daa5c8f83f3fe19d | [
"BSD-3-Clause"
] | null | null | null | import numpy as np
import scipy as sp
import pandas as pd
import numbers
from typing import Callable, List, Union
import logging
from .base import Epsilon
from ..distance import SCALE_LIN
from ..sampler import Sampler
from ..storage import save_dict_to_json
logger = logging.getLogger("Epsilon")
class TemperatureBase(Epsilon):
"""
A temperature scheme handles the decrease of the temperatures employed
by a :class:`pyabc.acceptor.StochasticAcceptor` over time.
This class is not functional on its own, its derivatives must be used.
"""
class ListTemperature(TemperatureBase):
"""
Pass a list of temperature values to use successively.
Parameters
----------
values:
The array of temperatures to use successively.
For exact inference, finish with 1.
"""
def __init__(self, values: List[float]):
self.values = values
def __call__(self,
t: int) -> float:
return self.values[t]
class Temperature(TemperatureBase):
"""
This class implements a highly adaptive and configurable temperature
scheme. Via the argument `schemes`, arbitrary temperature schemes can be
passed to calculate the next generation's temperature, via `aggregate_fun`
one can define how to combine multiple guesses, via `initial_temperature`
the initial temperature can be set.
Parameters
----------
schemes: Union[Callable, List[Callable]], optional
Temperature schemes returning proposed
temperatures for the next time point, e.g.
instances of :class:`pyabc.epsilon.TemperatureScheme`.
aggregate_fun: Callable[List[float], float], optional
The function to aggregate the schemes by, of the form
``Callable[List[float], float]``.
Defaults to taking the minimum.
initial_temperature: float, optional
The initial temperature. If None provided, an AcceptanceRateScheme
is used.
enforce_exact_final_temperature: bool, optional
Whether to force the final temperature (if max_nr_populations < inf)
to be 1.0, giving exact inference.
log_file: str, optional
A log file for storing data of the temperature that are currently not
saved in the database. The data are saved in json format.
Properties
----------
max_nr_populations: int
The maximum number of iterations as passed to ABCSMC.
May be inf, but not all schemes can handle that (and will complain).
temperatures: Dict[int, float]
Times as keys and temperatures as values.
"""
def __init__(
self,
schemes: Union[Callable, List[Callable]] = None,
aggregate_fun: Callable[[List[float]], float] = None,
initial_temperature: float = None,
enforce_exact_final_temperature: bool = True,
log_file: str = None):
self.schemes = schemes
if aggregate_fun is None:
# use minimum over all proposed temperature values
aggregate_fun = min
self.aggregate_fun = aggregate_fun
if initial_temperature is None:
initial_temperature = AcceptanceRateScheme()
self.initial_temperature = initial_temperature
self.enforce_exact_final_temperature = enforce_exact_final_temperature
self.log_file = log_file
# to be filled later
self.max_nr_populations = None
self.temperatures = {}
self.temperature_proposals = {}
def initialize(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
acceptor_config: dict):
self.max_nr_populations = max_nr_populations
# set default schemes
if self.schemes is None:
# this combination proved rather stable
acc_rate_scheme = AcceptanceRateScheme()
decay_scheme = (
ExpDecayFixedIterScheme() if np.isfinite(max_nr_populations)
else ExpDecayFixedRatioScheme())
self.schemes = [acc_rate_scheme, decay_scheme]
# set initial temperature for time t
self._update(t, get_weighted_distances, get_all_records,
1.0, acceptor_config)
def configure_sampler(self, sampler: Sampler):
if callable(self.initial_temperature):
self.initial_temperature.configure_sampler(sampler)
for scheme in self.schemes:
scheme.configure_sampler(sampler)
def update(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
acceptance_rate: float,
acceptor_config: dict):
# set temperature for time t
self._update(t, get_weighted_distances,
get_all_records, acceptance_rate,
acceptor_config)
def _update(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
acceptance_rate: float,
acceptor_config):
"""
Compute the temperature for time `t`.
"""
# scheme arguments
kwargs = dict(
t=t,
get_weighted_distances=get_weighted_distances,
get_all_records=get_all_records,
max_nr_populations=self.max_nr_populations,
pdf_norm=acceptor_config['pdf_norm'],
kernel_scale=acceptor_config['kernel_scale'],
prev_temperature=self.temperatures.get(t-1, None),
acceptance_rate=acceptance_rate,
)
if t >= self.max_nr_populations - 1 \
and self.enforce_exact_final_temperature:
# t is last time
temps = [1.0]
elif not self.temperatures: # need an initial value
if callable(self.initial_temperature):
# execute scheme
temps = [self.initial_temperature(**kwargs)]
elif isinstance(self.initial_temperature, numbers.Number):
temps = [self.initial_temperature]
else:
raise ValueError(
"Initial temperature must be a float or a callable")
else:
# evaluate schemes
temps = []
for scheme in self.schemes:
temp = scheme(**kwargs)
temps.append(temp)
# compute next temperature based on proposals and fallback
# should not be higher than before
fallback = self.temperatures[t-1] \
if t-1 in self.temperatures else np.inf
temperature = self.aggregate_fun(temps)
# also a value lower than 1.0 does not make sense
temperature = max(min(temperature, fallback), 1.0)
if not np.isfinite(temperature):
raise ValueError("Temperature must be finite.")
# record found value
self.temperatures[t] = temperature
# logging
logger.debug(f"Proposed temperatures for {t}: {temps}.")
self.temperature_proposals[t] = temps
if self.log_file:
save_dict_to_json(self.temperature_proposals, self.log_file)
def __call__(self,
t: int) -> float:
return self.temperatures[t]
class TemperatureScheme:
"""
A TemperatureScheme suggests the next temperature value. It is used as
one of potentially multiple schemes employed in the Temperature class.
This class is abstract.
Parameters
----------
t:
The time to compute for.
get_weighted_distances:
Callable to obtain the weights and kernel values to be used for
the scheme.
get_all_records:
Callable returning a List[dict] of all recorded particles.
max_nr_populations:
The maximum number of populations that are supposed to be taken.
pdf_norm:
The normalization constant c that will be used in the acceptance step.
kernel_scale:
Scale on which the pdf values are (linear or logarithmic).
prev_temperature:
The temperature that was used last time (or None if not applicable).
acceptance_rate:
The recently obtained rate.
"""
def __init__(self):
pass
def configure_sampler(self, sampler: Sampler):
"""
Modify the sampler. As in, and redirected from,
:func:`pyabc.epsilon.Temperature.configure_sampler`.
"""
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
pass
class AcceptanceRateScheme(TemperatureScheme):
"""
Try to keep the acceptance rate constant at a value of
`target_rate`. Note that this scheme will fail to
reduce the temperature sufficiently in later iterations, if the
problem's inherent acceptance rate is lower, but it has been
observed to give big feasible temperature leaps in early iterations.
In particular, this scheme can be used to propose an initial temperature.
Parameters
----------
target_rate: float, optional
The target acceptance rate to match.
min_rate: float, optional
The minimum rate below which not to apply the acceptance step scheme
any more. Setting this to a value of e.g. 0.05 can make sense
1) because it may be unlikely that the acceptance rate scheme will
propose a useful temperature at such low acceptance levels, and
2) to avoid uneccessary computations.
"""
def __init__(self, target_rate: float = 0.3, min_rate: float = None):
self.target_rate = target_rate
self.min_rate = min_rate
def configure_sampler(self, sampler: Sampler):
sampler.sample_factory.record_rejected = True
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# check minimum rate
if self.min_rate is not None and acceptance_rate < self.min_rate:
return np.inf
# execute function (expensive if in calibration)
records = get_all_records()
# convert to dataframe for easier extraction
records = pd.DataFrame(records)
# previous and current transition densities
t_pd_prev = np.array(records['transition_pd_prev'], dtype=float)
t_pd = np.array(records['transition_pd'], dtype=float)
# acceptance kernel likelihoods
pds = np.array(records['distance'], dtype=float)
# compute importance weights
weights = t_pd / t_pd_prev
# len would suffice, but maybe rather not rely on things to be normed
weights /= sum(weights)
temperature = match_acceptance_rate(
weights, pds, pdf_norm, kernel_scale, self.target_rate)
return temperature
def match_acceptance_rate(
weights, pds, pdf_norm, kernel_scale, target_rate):
"""
For large temperature, changes become effective on an exponential scale,
thus we optimize the logarithm of the inverse temperature beta.
For a temperature close to 1, subtler changes are neccesary, however here
the logarhtm is nearly linear anyway.
"""
# objective function which we wish to find a root for
def obj(b):
beta = np.exp(b)
# compute rescaled posterior densities
if kernel_scale == SCALE_LIN:
acc_probs = (pds / pdf_norm) ** beta
else: # kernel_scale == SCALE_LOG
acc_probs = np.exp((pds - pdf_norm) * beta)
# to acceptance probabilities to be sure
acc_probs = np.minimum(acc_probs, 1.0)
# objective function
val = np.sum(weights * acc_probs) - target_rate
return val
# TODO the lower boundary min_b is somewhat arbitrary
min_b = -100
if obj(0) > 0:
# function is monotonically decreasing
# smallest possible value already > 0
b_opt = 0
elif obj(min_b) < 0:
# it is obj(-inf) > 0 always
logger.info("AcceptanceRateScheme: Numerics limit temperature.")
b_opt = min_b
else:
# perform binary search
b_opt = sp.optimize.bisect(obj, min_b, 0, maxiter=100000)
beta_opt = np.exp(b_opt)
temperature = 1. / beta_opt
return temperature
class ExpDecayFixedIterScheme(TemperatureScheme):
"""
The next temperature is set as
.. math::
T_j = T_{max}^{(n-j)/n}
where n denotes the number of populations, and j=1,...,n the iteration.
This translates to
.. math::
T_j = T_{j-1}^{(n-j)/(n-(j-1))}.
This ensures that a temperature of 1.0 is reached after exactly the
remaining number of steps.
So, in both cases the sequence of temperatures follows an exponential
decay, also known as a geometric progression, or a linear progression
in log-space.
Note that the formula is applied anew in each iteration.
This is advantageous if also other schemes are used s.t. T_{j-1}
is smaller than by the above.
Parameters
----------
alpha: float
Factor by which to reduce the temperature, if `max_nr_populations`
is infinite.
"""
def __init__(self):
pass
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# needs a finite number of iterations
if max_nr_populations == np.inf:
raise ValueError(
"The ExpDecayFixedIterScheme requires a finite "
"`max_nr_populations`.")
# needs a starting temperature
# if not available, return infinite temperature
if prev_temperature is None:
return np.inf
# base temperature
temp_base = prev_temperature
# how many steps left?
t_to_go = max_nr_populations - t
# compute next temperature according to exponential decay
temperature = temp_base ** ((t_to_go - 1) / t_to_go)
return temperature
class ExpDecayFixedRatioScheme(TemperatureScheme):
"""
The next temperature is chosen as
.. math::
T_j = \\alpha \\cdot T_{j-1}.
Like the :class:`pyabc.epsilon.ExpDecayFixedIterScheme`,
this yields a geometric progression, however with a fixed ratio,
irrespective of the number of iterations. If a finite number of
iterations is specified in ABCSMC, there is no influence on the final
jump to a temperature of 1.0.
This is quite similar to the :class:`pyabc.epsilon.DalyScheme`, although
simpler in implementation. The alpha value here corresponds to a value of
1 - alpha there.
Parameters
----------
alpha: float, optional
The ratio of subsequent temperatures.
min_rate: float, optional
A minimum acceptance rate. If this rate has been violated in the
previous iteration, the alpha value is increased.
max_rate: float, optional
Maximum rate to not be exceeded, otherwise the alpha value is
decreased.
"""
def __init__(self, alpha: float = 0.5,
min_rate: float = 1e-4, max_rate: float = 0.5):
self.alpha = alpha
self.min_rate = min_rate
self.max_rate = max_rate
self.alphas = {}
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if prev_temperature is None:
return np.inf
# previous alpha
alpha = self.alphas.get(t-1, self.alpha)
# check if acceptance rate criterion violated
if acceptance_rate > self.max_rate and t > 1:
logger.debug("ExpDecayFixedRatioScheme: "
"Reacting to high acceptance rate.")
alpha = max(alpha / 2, alpha - (1 - alpha) * 2)
if acceptance_rate < self.min_rate:
logger.debug("ExpDecayFixedRatioScheme: "
"Reacting to low acceptance rate.")
# increase alpha
alpha = alpha + (1 - alpha) / 2
# record
self.alphas[t] = alpha
# reduce temperature
temperature = self.alphas[t] * prev_temperature
return temperature
class PolynomialDecayFixedIterScheme(TemperatureScheme):
"""
Compute next temperature as pre-last entry in
>>> np.linspace(1, (temp_base)**(1 / temp_decay_exponent),
>>> t_to_go + 1) ** temp_decay_exponent)
Requires finite `max_nr_populations`.
Note that this is similar to the
:class:`pyabc.epsilon.ExpDecayFixedIterScheme`, which is
indeed the limit for `exponent -> infinity`. For smaller
exponent, the sequence makes larger steps for low temperatures. This
can be useful in cases, where lower temperatures (which are usually
more expensive) can be traversed in few larger steps, however also
the opposite may be true, i.e. that more steps at low temperatures
are advantageous.
Parameters
----------
exponent: float, optional
The exponent to use in the scheme.
"""
def __init__(self, exponent: float = 3):
self.exponent = exponent
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# needs a starting temperature
# if not available, return infinite temperature
if prev_temperature is None:
return np.inf
# base temperature
temp_base = prev_temperature
# check if we can compute a decay step
if max_nr_populations == np.inf:
raise ValueError("Can only perform PolynomialDecayScheme step "
"with a finite max_nr_populations.")
# how many steps left?
t_to_go = max_nr_populations - t
# compute sequence
temps = np.linspace(1, (temp_base)**(1 / self.exponent),
t_to_go+1) ** self.exponent
logger.debug(f"Temperatures proposed by polynomial decay method: "
f"{temps}.")
# pre-last step is the next step
temperature = temps[-2]
return temperature
class DalyScheme(TemperatureScheme):
"""
This scheme is loosely based on [#daly2017]_, however note that it does
not try to replicate it entirely. In particular, the implementation
of pyABC does not allow the sampling to be stopped when encountering
too low acceptance rates, such that this can only be done ex-posteriori
here.
Parameters
----------
alpha: float, optional
The ratio by which to decrease the temperature value. More
specifically, the next temperature is given as
`(1-alpha) * temperature`.
min_rate: float, optional
A minimum acceptance rate. If this rate has been violated in the
previous iteration, the alpha value is decreased.
.. [#daly2017] Daly Aidan C., Cooper Jonathan, Gavaghan David J.,
and Holmes Chris. "Comparing two sequential Monte Carlo samplers
for exact and approximate Bayesian inference on biological
models". Journal of The Royal Society Interface, 2017.
"""
def __init__(self, alpha: float = 0.5, min_rate: float = 1e-4):
self.alpha = alpha
self.min_rate = min_rate
self.k = {}
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# needs a starting temperature
# if not available, return infinite temperature
if prev_temperature is None:
return np.inf
# base temperature
temp_base = prev_temperature
# addressing the std, not the var
eps_base = np.sqrt(temp_base)
if not self.k:
# initial iteration
self.k[t - 1] = eps_base
k_base = self.k[t - 1]
if acceptance_rate < self.min_rate:
logger.debug("DalyScheme: Reacting to low acceptance rate.")
# reduce reduction
k_base = self.alpha * k_base
self.k[t] = min(k_base, self.alpha * eps_base)
eps = eps_base - self.k[t]
temperature = eps**2
return temperature
class FrielPettittScheme(TemperatureScheme):
"""
Basically takes linear steps in log-space. See [#vyshemirsky2008]_.
.. [#vyshemirsky2008] Vyshemirsky, Vladislav, and Mark A. Girolami.
"Bayesian ranking of biochemical system models."
Bioinformatics 24.6 (2007): 833-839.
"""
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# needs a starting temperature
# if not available, return infinite temperature
if prev_temperature is None:
return np.inf
# check if we can compute a decay step
if max_nr_populations == np.inf:
raise ValueError("Can only perform FrielPettittScheme step with a "
"finite max_nr_populations.")
# base temperature
temp_base = prev_temperature
beta_base = 1. / temp_base
# time to go
t_to_go = max_nr_populations - t
beta = beta_base + ((1. - beta_base) * 1 / t_to_go) ** 2
temperature = 1. / beta
return temperature
class EssScheme(TemperatureScheme):
"""
Try to keep the effective sample size (ESS) constant.
Parameters
----------
target_relative_ess: float
Targe relative effective sample size.
"""
def __init__(self, target_relative_ess: float = 0.8):
self.target_relative_ess = target_relative_ess
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
# execute function (expensive if in calibration)
df = get_weighted_distances()
weights = np.array(df['w'], dtype=float)
pdfs = np.array(df['distance'], dtype=float)
# compute rescaled posterior densities
if kernel_scale == SCALE_LIN:
values = pdfs / pdf_norm
else: # kernel_scale == SCALE_LOG
values = np.exp(pdfs - pdf_norm)
# to probability mass function (i.e. normalize)
weights /= np.sum(weights)
target_ess = len(weights) * self.target_relative_ess
if prev_temperature is None:
beta_base = 0.0
else:
beta_base = 1. / prev_temperature
# objective to minimize
def obj(beta):
return (_ess(values, weights, beta) - target_ess)**2
bounds = sp.optimize.Bounds(lb=np.array([beta_base]),
ub=np.array([1.]))
# TODO make more efficient by providing gradients
ret = sp.optimize.minimize(
obj, x0=np.array([0.5 * (1 + beta_base)]),
bounds=bounds)
beta = ret.x
temperature = 1. / beta
return temperature
def _ess(pdfs, weights, beta):
"""
Effective sample size (ESS) of importance samples.
"""
num = np.sum(weights * pdfs**beta)**2
den = np.sum((weights * pdfs**beta)**2)
return num / den
| 34.168237 | 79 | 0.612873 | import numpy as np
import scipy as sp
import pandas as pd
import numbers
from typing import Callable, List, Union
import logging
from .base import Epsilon
from ..distance import SCALE_LIN
from ..sampler import Sampler
from ..storage import save_dict_to_json
logger = logging.getLogger("Epsilon")
class TemperatureBase(Epsilon):
class ListTemperature(TemperatureBase):
def __init__(self, values: List[float]):
self.values = values
def __call__(self,
t: int) -> float:
return self.values[t]
class Temperature(TemperatureBase):
def __init__(
self,
schemes: Union[Callable, List[Callable]] = None,
aggregate_fun: Callable[[List[float]], float] = None,
initial_temperature: float = None,
enforce_exact_final_temperature: bool = True,
log_file: str = None):
self.schemes = schemes
if aggregate_fun is None:
aggregate_fun = min
self.aggregate_fun = aggregate_fun
if initial_temperature is None:
initial_temperature = AcceptanceRateScheme()
self.initial_temperature = initial_temperature
self.enforce_exact_final_temperature = enforce_exact_final_temperature
self.log_file = log_file
self.max_nr_populations = None
self.temperatures = {}
self.temperature_proposals = {}
def initialize(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
acceptor_config: dict):
self.max_nr_populations = max_nr_populations
if self.schemes is None:
acc_rate_scheme = AcceptanceRateScheme()
decay_scheme = (
ExpDecayFixedIterScheme() if np.isfinite(max_nr_populations)
else ExpDecayFixedRatioScheme())
self.schemes = [acc_rate_scheme, decay_scheme]
self._update(t, get_weighted_distances, get_all_records,
1.0, acceptor_config)
def configure_sampler(self, sampler: Sampler):
if callable(self.initial_temperature):
self.initial_temperature.configure_sampler(sampler)
for scheme in self.schemes:
scheme.configure_sampler(sampler)
def update(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
acceptance_rate: float,
acceptor_config: dict):
self._update(t, get_weighted_distances,
get_all_records, acceptance_rate,
acceptor_config)
def _update(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
acceptance_rate: float,
acceptor_config):
kwargs = dict(
t=t,
get_weighted_distances=get_weighted_distances,
get_all_records=get_all_records,
max_nr_populations=self.max_nr_populations,
pdf_norm=acceptor_config['pdf_norm'],
kernel_scale=acceptor_config['kernel_scale'],
prev_temperature=self.temperatures.get(t-1, None),
acceptance_rate=acceptance_rate,
)
if t >= self.max_nr_populations - 1 \
and self.enforce_exact_final_temperature:
temps = [1.0]
elif not self.temperatures:
if callable(self.initial_temperature):
temps = [self.initial_temperature(**kwargs)]
elif isinstance(self.initial_temperature, numbers.Number):
temps = [self.initial_temperature]
else:
raise ValueError(
"Initial temperature must be a float or a callable")
else:
temps = []
for scheme in self.schemes:
temp = scheme(**kwargs)
temps.append(temp)
fallback = self.temperatures[t-1] \
if t-1 in self.temperatures else np.inf
temperature = self.aggregate_fun(temps)
temperature = max(min(temperature, fallback), 1.0)
if not np.isfinite(temperature):
raise ValueError("Temperature must be finite.")
self.temperatures[t] = temperature
logger.debug(f"Proposed temperatures for {t}: {temps}.")
self.temperature_proposals[t] = temps
if self.log_file:
save_dict_to_json(self.temperature_proposals, self.log_file)
def __call__(self,
t: int) -> float:
return self.temperatures[t]
class TemperatureScheme:
def __init__(self):
pass
def configure_sampler(self, sampler: Sampler):
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
pass
class AcceptanceRateScheme(TemperatureScheme):
def __init__(self, target_rate: float = 0.3, min_rate: float = None):
self.target_rate = target_rate
self.min_rate = min_rate
def configure_sampler(self, sampler: Sampler):
sampler.sample_factory.record_rejected = True
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if self.min_rate is not None and acceptance_rate < self.min_rate:
return np.inf
records = get_all_records()
records = pd.DataFrame(records)
t_pd_prev = np.array(records['transition_pd_prev'], dtype=float)
t_pd = np.array(records['transition_pd'], dtype=float)
pds = np.array(records['distance'], dtype=float)
weights = t_pd / t_pd_prev
weights /= sum(weights)
temperature = match_acceptance_rate(
weights, pds, pdf_norm, kernel_scale, self.target_rate)
return temperature
def match_acceptance_rate(
weights, pds, pdf_norm, kernel_scale, target_rate):
def obj(b):
beta = np.exp(b)
if kernel_scale == SCALE_LIN:
acc_probs = (pds / pdf_norm) ** beta
else:
acc_probs = np.exp((pds - pdf_norm) * beta)
acc_probs = np.minimum(acc_probs, 1.0)
val = np.sum(weights * acc_probs) - target_rate
return val
min_b = -100
if obj(0) > 0:
b_opt = 0
elif obj(min_b) < 0:
logger.info("AcceptanceRateScheme: Numerics limit temperature.")
b_opt = min_b
else:
b_opt = sp.optimize.bisect(obj, min_b, 0, maxiter=100000)
beta_opt = np.exp(b_opt)
temperature = 1. / beta_opt
return temperature
class ExpDecayFixedIterScheme(TemperatureScheme):
def __init__(self):
pass
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if max_nr_populations == np.inf:
raise ValueError(
"The ExpDecayFixedIterScheme requires a finite "
"`max_nr_populations`.")
if prev_temperature is None:
return np.inf
temp_base = prev_temperature
t_to_go = max_nr_populations - t
temperature = temp_base ** ((t_to_go - 1) / t_to_go)
return temperature
class ExpDecayFixedRatioScheme(TemperatureScheme):
def __init__(self, alpha: float = 0.5,
min_rate: float = 1e-4, max_rate: float = 0.5):
self.alpha = alpha
self.min_rate = min_rate
self.max_rate = max_rate
self.alphas = {}
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if prev_temperature is None:
return np.inf
alpha = self.alphas.get(t-1, self.alpha)
if acceptance_rate > self.max_rate and t > 1:
logger.debug("ExpDecayFixedRatioScheme: "
"Reacting to high acceptance rate.")
alpha = max(alpha / 2, alpha - (1 - alpha) * 2)
if acceptance_rate < self.min_rate:
logger.debug("ExpDecayFixedRatioScheme: "
"Reacting to low acceptance rate.")
alpha = alpha + (1 - alpha) / 2
self.alphas[t] = alpha
temperature = self.alphas[t] * prev_temperature
return temperature
class PolynomialDecayFixedIterScheme(TemperatureScheme):
def __init__(self, exponent: float = 3):
self.exponent = exponent
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if prev_temperature is None:
return np.inf
temp_base = prev_temperature
if max_nr_populations == np.inf:
raise ValueError("Can only perform PolynomialDecayScheme step "
"with a finite max_nr_populations.")
t_to_go = max_nr_populations - t
temps = np.linspace(1, (temp_base)**(1 / self.exponent),
t_to_go+1) ** self.exponent
logger.debug(f"Temperatures proposed by polynomial decay method: "
f"{temps}.")
temperature = temps[-2]
return temperature
class DalyScheme(TemperatureScheme):
def __init__(self, alpha: float = 0.5, min_rate: float = 1e-4):
self.alpha = alpha
self.min_rate = min_rate
self.k = {}
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if prev_temperature is None:
return np.inf
temp_base = prev_temperature
eps_base = np.sqrt(temp_base)
if not self.k:
self.k[t - 1] = eps_base
k_base = self.k[t - 1]
if acceptance_rate < self.min_rate:
logger.debug("DalyScheme: Reacting to low acceptance rate.")
k_base = self.alpha * k_base
self.k[t] = min(k_base, self.alpha * eps_base)
eps = eps_base - self.k[t]
temperature = eps**2
return temperature
class FrielPettittScheme(TemperatureScheme):
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
if prev_temperature is None:
return np.inf
if max_nr_populations == np.inf:
raise ValueError("Can only perform FrielPettittScheme step with a "
"finite max_nr_populations.")
temp_base = prev_temperature
beta_base = 1. / temp_base
t_to_go = max_nr_populations - t
beta = beta_base + ((1. - beta_base) * 1 / t_to_go) ** 2
temperature = 1. / beta
return temperature
class EssScheme(TemperatureScheme):
def __init__(self, target_relative_ess: float = 0.8):
self.target_relative_ess = target_relative_ess
def __call__(self,
t: int,
get_weighted_distances: Callable[[], pd.DataFrame],
get_all_records: Callable[[], List[dict]],
max_nr_populations: int,
pdf_norm: float,
kernel_scale: str,
prev_temperature: float,
acceptance_rate: float):
df = get_weighted_distances()
weights = np.array(df['w'], dtype=float)
pdfs = np.array(df['distance'], dtype=float)
if kernel_scale == SCALE_LIN:
values = pdfs / pdf_norm
else:
values = np.exp(pdfs - pdf_norm)
weights /= np.sum(weights)
target_ess = len(weights) * self.target_relative_ess
if prev_temperature is None:
beta_base = 0.0
else:
beta_base = 1. / prev_temperature
def obj(beta):
return (_ess(values, weights, beta) - target_ess)**2
bounds = sp.optimize.Bounds(lb=np.array([beta_base]),
ub=np.array([1.]))
ret = sp.optimize.minimize(
obj, x0=np.array([0.5 * (1 + beta_base)]),
bounds=bounds)
beta = ret.x
temperature = 1. / beta
return temperature
def _ess(pdfs, weights, beta):
num = np.sum(weights * pdfs**beta)**2
den = np.sum((weights * pdfs**beta)**2)
return num / den
| true | true |
f71b787fa525196b698da70d6376942add8376c6 | 12,785 | py | Python | tests/db_stats.py | chrisjsewell/aiida-performance | 160606f07fe092a9e2bacdf62bfecec460fac642 | [
"MIT"
] | null | null | null | tests/db_stats.py | chrisjsewell/aiida-performance | 160606f07fe092a9e2bacdf62bfecec460fac642 | [
"MIT"
] | null | null | null | tests/db_stats.py | chrisjsewell/aiida-performance | 160606f07fe092a9e2bacdf62bfecec460fac642 | [
"MIT"
] | null | null | null | """Useful queries for profiling PostgreSQL databases
These queries are mainly adapted from
https://gist.github.com/anvk/475c22cbca1edc5ce94546c871460fdd
"""
from functools import wraps
from pathlib import Path
def execute_raw(raw):
from aiida.manage.manager import get_manager
backend = get_manager()._load_backend(schema_check=False)
return backend.execute_raw(raw)
# ------------------
# -- Memory Size --
# ------------------
def memory_db_df():
import pandas as pd
result = execute_raw(
r"""
SELECT
datname,
pg_database_size(datname)
from pg_database
order by pg_database_size(datname);
"""
)
df = pd.DataFrame(result, columns=["database", "size_mb"])
df["size_mb"] = df["size_mb"] * 1e-6
return df
def memory_pg_classes_df():
"""Return size of `pg_class`'s
`pg_class` catalogs tables and most everything else that has columns,
or is otherwise similar to a table.
See https://www.postgresql.org/docs/9.3/catalog-pg-class.html
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
sum(pg_relation_size(pg_class.oid))::bigint,
nspname,
CASE pg_class.relkind
WHEN 'r' THEN 'table'
WHEN 'i' THEN 'index'
WHEN 'S' THEN 'sequence'
WHEN 'v' THEN 'view'
WHEN 't' THEN 'toast'
ELSE pg_class.relkind::text
END
FROM pg_class
LEFT OUTER JOIN pg_namespace ON (pg_namespace.oid = pg_class.relnamespace)
GROUP BY pg_class.relkind, nspname
ORDER BY sum(pg_relation_size(pg_class.oid)) DESC;
"""
)
df = pd.DataFrame(result, columns=["size_mb", "namespace", "relkind"])
df.sort_index(axis=1, inplace=True)
df["size_mb"] = df.size_mb * 1e-6
return df
def memory_tables_df():
"""Return statistics on indices.
See https://www.postgresql.org/docs/current/monitoring-stats.html
"""
import pandas as pd
result = execute_raw(
r"""
select
relname,
pg_relation_size(relname::regclass) as table_size,
pg_total_relation_size(relname::regclass) - pg_relation_size(relname::regclass) as index_size,
pg_total_relation_size(relname::regclass) as total_size
from pg_stat_user_tables
"""
)
df = pd.DataFrame(result, columns=["name", "table_mb", "indices_mb", "total_mb"])
df.set_index("name", inplace=True)
df = df * 1e-6
df.sort_values("total_mb", ascending=False, inplace=True)
return df
# -------------
# -- Indices --
# -------------
def indices_list_df():
"""Return list of indices by table and columns."""
import pandas as pd
result = execute_raw(
r"""
select
t.relname as table_name,
i.relname as index_name,
string_agg(a.attname, ',') as column_name
from
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
where
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'
and t.relname not like 'pg_%'
group by
t.relname,
i.relname
order by
t.relname,
i.relname;
"""
)
df = pd.DataFrame(result, columns=["table", "index", "columns"])
df.set_index(["table", "columns"], inplace=True)
return df
def indices_stats_df(sort_size=False, with_sql=False):
"""Return statistics on indices.
See https://www.postgresql.org/docs/current/monitoring-stats.html
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
pt.tablename AS TableName,
t.indexname AS IndexName,
pc.reltuples AS TotalRows,
pg_relation_size(quote_ident(pt.tablename)::text) AS TableSize,
pg_relation_size(quote_ident(t.indexrelname)::text) AS IndexSize,
t.idx_scan AS TotalNumberOfScan,
t.idx_tup_read AS TotalTupleRead,
t.idx_tup_fetch AS TotalTupleFetched,
pgi.indexdef AS IndexDef
FROM pg_tables AS pt
LEFT OUTER JOIN pg_class AS pc
ON pt.tablename=pc.relname
LEFT OUTER JOIN
(
SELECT
pc.relname AS TableName,
pc2.relname AS IndexName,
psai.idx_scan,
psai.idx_tup_read,
psai.idx_tup_fetch,
psai.indexrelname
FROM
pg_index AS pi
JOIN pg_class AS pc
ON pc.oid = pi.indrelid
JOIN pg_class AS pc2
ON pc2.oid = pi.indexrelid
JOIN pg_stat_all_indexes AS psai
ON pi.indexrelid = psai.indexrelid
) AS T
ON pt.tablename = T.TableName
LEFT OUTER JOIN pg_indexes as pgi
ON T.indexname = pgi.indexname
WHERE pt.schemaname='public'
ORDER BY 1;
"""
)
columns = [
"table",
"index",
"rows",
"table_size_mb",
"index_size_mb",
# Number of index scans initiated on this index
"scans",
# Number of index entries returned by scans on this index
"read",
# Number of live rows fetched by index scans
"fetched",
"sql",
]
df = pd.DataFrame(result, columns=columns)
df.set_index(["table", "index"], inplace=True)
df["table_size_mb"] = df.table_size_mb * 10e-6
df["index_size_mb"] = df.index_size_mb * 10e-6
if not with_sql:
df.drop("sql", axis=1, inplace=True)
if sort_size:
df.sort_values("index_size_mb", ascending=False, inplace=True)
else:
df.sort_index(axis=0, inplace=True)
return df
def indices_check_df(min_size_mb=0.1):
"""Check for tables that may require an index."""
import pandas as pd
result = execute_raw(
r"""
SELECT
relname,
seq_scan,
idx_scan,
pg_relation_size(relname::regclass) AS rel_size,
n_live_tup
FROM pg_stat_all_tables
WHERE schemaname='public' AND pg_relation_size(relname::regclass)>{min_size};
""".format(
min_size=int(min_size_mb * 1e6)
)
)
df = pd.DataFrame(
result,
columns=[
"table",
# Number of sequential scans initiated on this table
"seq_scans",
# Number of index scans initiated on this table
"idx_scans",
"size_mb",
"live_rows",
],
)
df["idx_usage"] = 100 * df.idx_scans / (df.seq_scans + df.idx_scans)
df["idx_required"] = (df.seq_scans - df.idx_scans) > 0
df["size_mb"] = df["size_mb"] * 1e-6
df.set_index("table", inplace=True)
return df
# --------------------
# -- Data Integrity --
# --------------------
def cache_hit_ratio():
"""Ideally hit_ration should be > 90%"""
result = execute_raw(
r"""
SELECT
sum(blks_hit)*100/sum(blks_hit+blks_read) as hit_ratio
from pg_stat_database;
"""
)
return float(result[0][0])
def anomalies_df():
"""
- c_commit_ratio should be > 95%
- c_rollback_ratio should be < 5%
- deadlocks should be close to 0
- conflicts should be close to 0
- temp_files and temp_bytes watch out for them
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
datname,
(xact_commit*100)/nullif(xact_commit+xact_rollback,0) as c_commit_ratio,
(xact_rollback*100)/nullif(xact_commit+xact_rollback, 0) as c_rollback_ratio,
deadlocks,
conflicts,
temp_files,
temp_bytes
FROM pg_stat_database;
"""
)
df = pd.DataFrame(
result,
columns=[
"database",
"commit_ratio",
"rollback_ratio",
"deadlocks",
"conflicts",
"temp_files",
"temp_size_mb",
],
)
df["temp_size_mb"] = df["temp_size_mb"] * 1e-6
return df
def write_activity_df(limit=50):
"""
hot_rate = rows HOT updated / total rows updated
(Heap Only Tuple means with no separate index update required)
Heap Only Tuple (HOT) means, creating a new update tuple if possible on the same page as the old tuple.
Ideally hot_rate should be close to 100.
You might be blocking HOT updates with indexes on updated columns. If those are expendable, you might get better overall performance without them.
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
s.relname,
pg_relation_size(relid),
coalesce(n_tup_ins,0) + 2 * coalesce(n_tup_upd,0) -
coalesce(n_tup_hot_upd,0) + coalesce(n_tup_del,0) AS total_writes,
(coalesce(n_tup_hot_upd,0)::float * 100 / (case when n_tup_upd > 0 then n_tup_upd else 1 end)::float) AS hot_rate
/* This returns None
(SELECT v[1] FROM regexp_matches(reloptions::text,E'fillfactor=(d+)') as r(v) limit 1) AS fillfactor
*/
from pg_stat_all_tables
s join pg_class c ON c.oid=relid
order by total_writes desc
limit {limit};
""".format(
limit=limit
)
)
columns = [
"table",
"size_mb",
"writes",
"hot_rate",
# "fill_factor"
]
df = pd.DataFrame(result, columns=columns)
df["size_mb"] = df["size_mb"] * 1e-6
df.set_index("table", inplace=True)
return df
# How many indexes are in cache
def cached_indices():
result = execute_raw(
r"""
SELECT
sum(idx_blks_read) as idx_read,
sum(idx_blks_hit) as idx_hit,
(sum(idx_blks_hit) - sum(idx_blks_read)) / sum(idx_blks_hit) as ratio
FROM pg_statio_user_indexes;
"""
)
return cached_indices
def dirty_pages():
"""maxwritten_clean and buffers_backend_fsyn should be 0"""
import pandas as pd
result = execute_raw(
r"""
SELECT buffers_clean, maxwritten_clean, buffers_backend_fsync from pg_stat_bgwriter;
"""
)
return pd.Series(
dict(
zip(
("buffers_clean", "maxwritten_clean", "buffers_backend_fsync"),
result[0],
)
)
)
# -------------
# -- Queries --
# -------------
def requires_pg_stat(func):
@wraps(func)
def wrapper(*args, **kwds):
try:
return func(*args, **kwds)
except Exception as err:
if 'relation "pg_stat_statements" does not exist' in str(err):
raise RuntimeError(
"This function requires that the pg_stat_statements extension is initialised on your database"
)
raise
return wrapper
@requires_pg_stat
def query_reset_stats():
return execute_raw("select pg_stat_statements_reset();")
@requires_pg_stat
def query_stats_df(limit=100):
"""Return most CPU intensive queries
See: https://www.postgresql.org/docs/9.4/pgstatstatements.html
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
query,
round(total_time::numeric, 2) AS total_time,
calls,
rows,
round((100 * total_time / sum(total_time::numeric) OVER ())::numeric, 2) AS percentage_cpu
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT {limit};
""".format(
limit=limit
)
)
# avg_time = total_time / calls
df = pd.DataFrame(
result, columns=["sql", "time_seconds", "calls", "rows", "cpu_percent"]
)
df["time_seconds"] = df["time_seconds"].astype(float) * 1e-6
df["type"] = df.sql.apply(lambda s: s.split()[0].upper())
return df
@requires_pg_stat
def query_write_df():
"""Return most writing (to shared_buffers) queries
See: https://www.postgresql.org/docs/9.4/pgstatstatements.html
"""
import pandas as pd
result = execute_raw(
r"""
SELECT
query,
shared_blks_dirtied
from pg_stat_statements
where shared_blks_dirtied > 0
order by 2 desc;
"""
)
return pd.DataFrame(result, columns=["sql", "blocks_written"])
if __name__ == "__main__":
import argparse, os
parser = argparse.ArgumentParser()
parser.add_argument("commands", choices=["queries", "indices", "reset"], nargs='+')
parser.add_argument("-n", "--name", default="test")
parser.add_argument("-p", "--path", default=os.getcwd())
args = parser.parse_args()
for _command in args.commands:
if _command == "queries":
Path(args.path).joinpath(args.name + "_queries.html").write_text(query_stats_df().to_html())
if _command == "indices":
Path(args.path).joinpath(args.name + "_indices.html").write_text(indices_stats_df().to_html())
elif _command == "reset":
query_reset_stats()
| 27.67316 | 159 | 0.600078 | from functools import wraps
from pathlib import Path
def execute_raw(raw):
from aiida.manage.manager import get_manager
backend = get_manager()._load_backend(schema_check=False)
return backend.execute_raw(raw)
def memory_db_df():
import pandas as pd
result = execute_raw(
r"""
SELECT
datname,
pg_database_size(datname)
from pg_database
order by pg_database_size(datname);
"""
)
df = pd.DataFrame(result, columns=["database", "size_mb"])
df["size_mb"] = df["size_mb"] * 1e-6
return df
def memory_pg_classes_df():
import pandas as pd
result = execute_raw(
r"""
SELECT
sum(pg_relation_size(pg_class.oid))::bigint,
nspname,
CASE pg_class.relkind
WHEN 'r' THEN 'table'
WHEN 'i' THEN 'index'
WHEN 'S' THEN 'sequence'
WHEN 'v' THEN 'view'
WHEN 't' THEN 'toast'
ELSE pg_class.relkind::text
END
FROM pg_class
LEFT OUTER JOIN pg_namespace ON (pg_namespace.oid = pg_class.relnamespace)
GROUP BY pg_class.relkind, nspname
ORDER BY sum(pg_relation_size(pg_class.oid)) DESC;
"""
)
df = pd.DataFrame(result, columns=["size_mb", "namespace", "relkind"])
df.sort_index(axis=1, inplace=True)
df["size_mb"] = df.size_mb * 1e-6
return df
def memory_tables_df():
import pandas as pd
result = execute_raw(
r"""
select
relname,
pg_relation_size(relname::regclass) as table_size,
pg_total_relation_size(relname::regclass) - pg_relation_size(relname::regclass) as index_size,
pg_total_relation_size(relname::regclass) as total_size
from pg_stat_user_tables
"""
)
df = pd.DataFrame(result, columns=["name", "table_mb", "indices_mb", "total_mb"])
df.set_index("name", inplace=True)
df = df * 1e-6
df.sort_values("total_mb", ascending=False, inplace=True)
return df
def indices_list_df():
import pandas as pd
result = execute_raw(
r"""
select
t.relname as table_name,
i.relname as index_name,
string_agg(a.attname, ',') as column_name
from
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
where
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
and t.relkind = 'r'
and t.relname not like 'pg_%'
group by
t.relname,
i.relname
order by
t.relname,
i.relname;
"""
)
df = pd.DataFrame(result, columns=["table", "index", "columns"])
df.set_index(["table", "columns"], inplace=True)
return df
def indices_stats_df(sort_size=False, with_sql=False):
import pandas as pd
result = execute_raw(
r"""
SELECT
pt.tablename AS TableName,
t.indexname AS IndexName,
pc.reltuples AS TotalRows,
pg_relation_size(quote_ident(pt.tablename)::text) AS TableSize,
pg_relation_size(quote_ident(t.indexrelname)::text) AS IndexSize,
t.idx_scan AS TotalNumberOfScan,
t.idx_tup_read AS TotalTupleRead,
t.idx_tup_fetch AS TotalTupleFetched,
pgi.indexdef AS IndexDef
FROM pg_tables AS pt
LEFT OUTER JOIN pg_class AS pc
ON pt.tablename=pc.relname
LEFT OUTER JOIN
(
SELECT
pc.relname AS TableName,
pc2.relname AS IndexName,
psai.idx_scan,
psai.idx_tup_read,
psai.idx_tup_fetch,
psai.indexrelname
FROM
pg_index AS pi
JOIN pg_class AS pc
ON pc.oid = pi.indrelid
JOIN pg_class AS pc2
ON pc2.oid = pi.indexrelid
JOIN pg_stat_all_indexes AS psai
ON pi.indexrelid = psai.indexrelid
) AS T
ON pt.tablename = T.TableName
LEFT OUTER JOIN pg_indexes as pgi
ON T.indexname = pgi.indexname
WHERE pt.schemaname='public'
ORDER BY 1;
"""
)
columns = [
"table",
"index",
"rows",
"table_size_mb",
"index_size_mb",
"scans",
"read",
"fetched",
"sql",
]
df = pd.DataFrame(result, columns=columns)
df.set_index(["table", "index"], inplace=True)
df["table_size_mb"] = df.table_size_mb * 10e-6
df["index_size_mb"] = df.index_size_mb * 10e-6
if not with_sql:
df.drop("sql", axis=1, inplace=True)
if sort_size:
df.sort_values("index_size_mb", ascending=False, inplace=True)
else:
df.sort_index(axis=0, inplace=True)
return df
def indices_check_df(min_size_mb=0.1):
import pandas as pd
result = execute_raw(
r"""
SELECT
relname,
seq_scan,
idx_scan,
pg_relation_size(relname::regclass) AS rel_size,
n_live_tup
FROM pg_stat_all_tables
WHERE schemaname='public' AND pg_relation_size(relname::regclass)>{min_size};
""".format(
min_size=int(min_size_mb * 1e6)
)
)
df = pd.DataFrame(
result,
columns=[
"table",
"seq_scans",
"idx_scans",
"size_mb",
"live_rows",
],
)
df["idx_usage"] = 100 * df.idx_scans / (df.seq_scans + df.idx_scans)
df["idx_required"] = (df.seq_scans - df.idx_scans) > 0
df["size_mb"] = df["size_mb"] * 1e-6
df.set_index("table", inplace=True)
return df
def cache_hit_ratio():
result = execute_raw(
r"""
SELECT
sum(blks_hit)*100/sum(blks_hit+blks_read) as hit_ratio
from pg_stat_database;
"""
)
return float(result[0][0])
def anomalies_df():
import pandas as pd
result = execute_raw(
r"""
SELECT
datname,
(xact_commit*100)/nullif(xact_commit+xact_rollback,0) as c_commit_ratio,
(xact_rollback*100)/nullif(xact_commit+xact_rollback, 0) as c_rollback_ratio,
deadlocks,
conflicts,
temp_files,
temp_bytes
FROM pg_stat_database;
"""
)
df = pd.DataFrame(
result,
columns=[
"database",
"commit_ratio",
"rollback_ratio",
"deadlocks",
"conflicts",
"temp_files",
"temp_size_mb",
],
)
df["temp_size_mb"] = df["temp_size_mb"] * 1e-6
return df
def write_activity_df(limit=50):
import pandas as pd
result = execute_raw(
r"""
SELECT
s.relname,
pg_relation_size(relid),
coalesce(n_tup_ins,0) + 2 * coalesce(n_tup_upd,0) -
coalesce(n_tup_hot_upd,0) + coalesce(n_tup_del,0) AS total_writes,
(coalesce(n_tup_hot_upd,0)::float * 100 / (case when n_tup_upd > 0 then n_tup_upd else 1 end)::float) AS hot_rate
/* This returns None
(SELECT v[1] FROM regexp_matches(reloptions::text,E'fillfactor=(d+)') as r(v) limit 1) AS fillfactor
*/
from pg_stat_all_tables
s join pg_class c ON c.oid=relid
order by total_writes desc
limit {limit};
""".format(
limit=limit
)
)
columns = [
"table",
"size_mb",
"writes",
"hot_rate",
]
df = pd.DataFrame(result, columns=columns)
df["size_mb"] = df["size_mb"] * 1e-6
df.set_index("table", inplace=True)
return df
def cached_indices():
result = execute_raw(
r"""
SELECT
sum(idx_blks_read) as idx_read,
sum(idx_blks_hit) as idx_hit,
(sum(idx_blks_hit) - sum(idx_blks_read)) / sum(idx_blks_hit) as ratio
FROM pg_statio_user_indexes;
"""
)
return cached_indices
def dirty_pages():
import pandas as pd
result = execute_raw(
r"""
SELECT buffers_clean, maxwritten_clean, buffers_backend_fsync from pg_stat_bgwriter;
"""
)
return pd.Series(
dict(
zip(
("buffers_clean", "maxwritten_clean", "buffers_backend_fsync"),
result[0],
)
)
)
def requires_pg_stat(func):
@wraps(func)
def wrapper(*args, **kwds):
try:
return func(*args, **kwds)
except Exception as err:
if 'relation "pg_stat_statements" does not exist' in str(err):
raise RuntimeError(
"This function requires that the pg_stat_statements extension is initialised on your database"
)
raise
return wrapper
@requires_pg_stat
def query_reset_stats():
return execute_raw("select pg_stat_statements_reset();")
@requires_pg_stat
def query_stats_df(limit=100):
import pandas as pd
result = execute_raw(
r"""
SELECT
query,
round(total_time::numeric, 2) AS total_time,
calls,
rows,
round((100 * total_time / sum(total_time::numeric) OVER ())::numeric, 2) AS percentage_cpu
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT {limit};
""".format(
limit=limit
)
)
df = pd.DataFrame(
result, columns=["sql", "time_seconds", "calls", "rows", "cpu_percent"]
)
df["time_seconds"] = df["time_seconds"].astype(float) * 1e-6
df["type"] = df.sql.apply(lambda s: s.split()[0].upper())
return df
@requires_pg_stat
def query_write_df():
import pandas as pd
result = execute_raw(
r"""
SELECT
query,
shared_blks_dirtied
from pg_stat_statements
where shared_blks_dirtied > 0
order by 2 desc;
"""
)
return pd.DataFrame(result, columns=["sql", "blocks_written"])
if __name__ == "__main__":
import argparse, os
parser = argparse.ArgumentParser()
parser.add_argument("commands", choices=["queries", "indices", "reset"], nargs='+')
parser.add_argument("-n", "--name", default="test")
parser.add_argument("-p", "--path", default=os.getcwd())
args = parser.parse_args()
for _command in args.commands:
if _command == "queries":
Path(args.path).joinpath(args.name + "_queries.html").write_text(query_stats_df().to_html())
if _command == "indices":
Path(args.path).joinpath(args.name + "_indices.html").write_text(indices_stats_df().to_html())
elif _command == "reset":
query_reset_stats()
| true | true |
f71b7a6ea431a910f31292019a4e71bb636c92dd | 1,429 | py | Python | NinjaBandSPADE/SPADE-agents/night_stand_agent.py | PaMeSa/NinjaBandSPADE | e98dda62d8c7a4559a0a45d0bab5351aa47efcfa | [
"Apache-2.0"
] | null | null | null | NinjaBandSPADE/SPADE-agents/night_stand_agent.py | PaMeSa/NinjaBandSPADE | e98dda62d8c7a4559a0a45d0bab5351aa47efcfa | [
"Apache-2.0"
] | null | null | null | NinjaBandSPADE/SPADE-agents/night_stand_agent.py | PaMeSa/NinjaBandSPADE | e98dda62d8c7a4559a0a45d0bab5351aa47efcfa | [
"Apache-2.0"
] | null | null | null | import time, sys
import httplib, urllib
#ip_address='192.168.0.100'
ip_address='10.12.19.67'
#ip_address='10.20.218.197'
cost='25'
l_amount='100'
sys.path.append('../..')
import spade
in_use=False
name="night_stand_agent"
class MyAgent(spade.Agent.Agent):
def _setup(self):
template = spade.Behaviour.ACLTemplate()
template.setSender(spade.AID.aid("control_agent@"+ip_address,["xmpp://control_agent@"+ip_address]))
template.setOntology("auction")
t = spade.Behaviour.MessageTemplate(template)
self.addBehaviour(self.RecBehav(),t)
print "Receiver Light template behaviour just started!"
class RecBehav(spade.Behaviour.EventBehaviour):
def _process(self):
global in_use
msg = self._receive(block=False,timeout=10)
print name+" has received a CFP:"
try:
m_content=int(msg.getContent())
except ValueError:
print "Not a number"
light_sensed=m_content
if not in_use:
msg = spade.ACLMessage.ACLMessage()
msg.setPerformative("propose")
msg.setOntology("auction")
msg.addReceiver(spade.AID.aid("control_agent@"+ip_address,["xmpp://control_agent@"+ip_address]))
msg.setContent(cost+" "+l_amount+" "+name)
self.myAgent.send(msg)
print name+" has sent a proposal to the control_agent:"
a = MyAgent(name+"@"+ip_address, "secret")
a.start()
alive = True
while alive:
try:
time.sleep(1)
except KeyboardInterrupt:
alive=False
a.stop()
sys.exit(0)
| 25.981818 | 101 | 0.714486 | import time, sys
import httplib, urllib
ip_address='10.12.19.67'
cost='25'
l_amount='100'
sys.path.append('../..')
import spade
in_use=False
name="night_stand_agent"
class MyAgent(spade.Agent.Agent):
def _setup(self):
template = spade.Behaviour.ACLTemplate()
template.setSender(spade.AID.aid("control_agent@"+ip_address,["xmpp://control_agent@"+ip_address]))
template.setOntology("auction")
t = spade.Behaviour.MessageTemplate(template)
self.addBehaviour(self.RecBehav(),t)
print "Receiver Light template behaviour just started!"
class RecBehav(spade.Behaviour.EventBehaviour):
def _process(self):
global in_use
msg = self._receive(block=False,timeout=10)
print name+" has received a CFP:"
try:
m_content=int(msg.getContent())
except ValueError:
print "Not a number"
light_sensed=m_content
if not in_use:
msg = spade.ACLMessage.ACLMessage()
msg.setPerformative("propose")
msg.setOntology("auction")
msg.addReceiver(spade.AID.aid("control_agent@"+ip_address,["xmpp://control_agent@"+ip_address]))
msg.setContent(cost+" "+l_amount+" "+name)
self.myAgent.send(msg)
print name+" has sent a proposal to the control_agent:"
a = MyAgent(name+"@"+ip_address, "secret")
a.start()
alive = True
while alive:
try:
time.sleep(1)
except KeyboardInterrupt:
alive=False
a.stop()
sys.exit(0)
| false | true |
f71b7bba9bd0bdbe0b8034d90c61427bb3dc3f64 | 16,878 | py | Python | optbinning/binning/piecewise/continuous_binning.py | mnicstruwig/optbinning | 6ce991e1ca75b4d41835f3b3bf8e0f294f6ba780 | [
"Apache-2.0"
] | 1 | 2021-02-09T02:49:32.000Z | 2021-02-09T02:49:32.000Z | optbinning/binning/piecewise/continuous_binning.py | mnicstruwig/optbinning | 6ce991e1ca75b4d41835f3b3bf8e0f294f6ba780 | [
"Apache-2.0"
] | null | null | null | optbinning/binning/piecewise/continuous_binning.py | mnicstruwig/optbinning | 6ce991e1ca75b4d41835f3b3bf8e0f294f6ba780 | [
"Apache-2.0"
] | null | null | null | """
Optimal piecewise binning for continuous target.
"""
# Guillermo Navas-Palencia <g.navas.palencia@gmail.com>
# Copyright (C) 2020
import time
import numpy as np
from .base import _check_parameters
from .base import BasePWBinning
from .binning_statistics import PWContinuousBinningTable
from .metrics import continuous_metrics
from .transformations import transform_continuous_target
class ContinuousOptimalPWBinning(BasePWBinning):
"""Optimal Piecewise binning of a numerical variable with respect to a
binary target.
Parameters
----------
name : str, optional (default="")
The variable name.
objective : str, optional (default="l2")
The objective function. Supported objectives are "l2", "l1", "huber"
and "quantile". Note that "l1", "huber" and "quantile" are robust
objective functions.
degree : int (default=1)
The degree of the polynomials.
* degree = 0: piecewise constant functions.
* degree = 1: piecewise linear functions.
* degree > 1: piecewise polynomial functions.
continuous : bool (default=True)
Whether to fit a continuous or discontinuous piecewise regression.
prebinning_method : str, optional (default="cart")
The pre-binning method. Supported methods are "cart" for a CART
decision tree, "quantile" to generate prebins with approximately same
frequency and "uniform" to generate prebins with equal width. Method
"cart" uses `sklearn.tree.DecistionTreeClassifier
<https://scikit-learn.org/stable/modules/generated/sklearn.tree.
DecisionTreeClassifier.html>`_.
max_n_prebins : int (default=20)
The maximum number of bins after pre-binning (prebins).
min_prebin_size : float (default=0.05)
The fraction of mininum number of records for each prebin.
min_n_bins : int or None, optional (default=None)
The minimum number of bins. If None, then ``min_n_bins`` is
a value in ``[0, max_n_prebins]``.
max_n_bins : int or None, optional (default=None)
The maximum number of bins. If None, then ``max_n_bins`` is
a value in ``[0, max_n_prebins]``.
min_bin_size : float or None, optional (default=None)
The fraction of minimum number of records for each bin. If None,
``min_bin_size = min_prebin_size``.
max_bin_size : float or None, optional (default=None)
The fraction of maximum number of records for each bin. If None,
``max_bin_size = 1.0``.
monotonic_trend : str or None, optional (default="auto")
The monotonic trend. Supported trends are “auto”, "auto_heuristic" and
"auto_asc_desc" to automatically determine the trend maximizing IV
using a machine learning classifier, "ascending", "descending",
"concave", "convex", "peak" and "peak_heuristic" to allow a peak change
point, and "valley" and "valley_heuristic" to allow a valley change
point. Trends "auto_heuristic", "peak_heuristic" and "valley_heuristic"
use a heuristic to determine the change point, and are significantly
faster for large size instances (``max_n_prebins > 20``). Trend
"auto_asc_desc" is used to automatically select the best monotonic
trend between "ascending" and "descending". If None, then the
monotonic constraint is disabled.
n_subsamples : int or None (default=None)
Number of subsamples to fit the piecewise regression algorithm. If
None, all values are considered.
max_pvalue : float or None, optional (default=0.05)
The maximum p-value among bins. The Z-test is used to detect bins
not satisfying the p-value constraint. Option supported by solvers
"cp" and "mip".
max_pvalue_policy : str, optional (default="consecutive")
The method to determine bins not satisfying the p-value constraint.
Supported methods are "consecutive" to compare consecutive bins and
"all" to compare all bins.
outlier_detector : str or None, optional (default=None)
The outlier detection method. Supported methods are "range" to use
the interquartile range based method or "zcore" to use the modified
Z-score method.
outlier_params : dict or None, optional (default=None)
Dictionary of parameters to pass to the outlier detection method.
user_splits : array-like or None, optional (default=None)
The list of pre-binning split points when ``dtype`` is "numerical" or
the list of prebins when ``dtype`` is "categorical".
user_splits_fixed : array-like or None (default=None)
The list of pre-binning split points that must be fixed.
special_codes : array-like or None, optional (default=None)
List of special codes. Use special codes to specify the data values
that must be treated separately.
split_digits : int or None, optional (default=None)
The significant digits of the split points. If ``split_digits`` is set
to 0, the split points are integers. If None, then all significant
digits in the split points are considered.
solver : str, optional (default="auto")
The optimizer to solve the underlying mathematical optimization
problem. Supported solvers are `"ecos"
<https://github.com/embotech/ecos>`_, `"osqp"
<https://github.com/oxfordcontrol/osqp>`_, "direct", to choose the
direct solver, and "auto", to choose the most appropriate solver for
the problem.
h_epsilon: float (default=1.35)
The parameter h_epsilon used when ``objective="huber"``, controls the
number of samples that should be classified as outliers.
quantile : float (default=0.5)
The parameter quantile is the q-th quantile to be used when
``objective="quantile"``.
regularization: str or None (default=None)
Type of regularization. Supported regularization are "l1" (Lasso) and
"l2" (Ridge). If None, no regularization is applied.
reg_l1 : float (default=1.0)
L1 regularization term. Increasing this value will smooth the
regression model. Only applicable if ``regularization="l1"``.
reg_l2 : float (default=1.0)
L2 regularization term. Increasing this value will smooth the
regression model. Only applicable if ``regularization="l2"``.
random_state : int, RandomState instance or None, (default=None)
If ``n_subsamples < n_samples``, controls the shuffling applied to the
data before applying the split.
verbose : bool (default=False)
Enable verbose output.
"""
def __init__(self, name="", objective="l2", degree=1,
continuous=True, prebinning_method="cart", max_n_prebins=20,
min_prebin_size=0.05, min_n_bins=None, max_n_bins=None,
min_bin_size=None, max_bin_size=None, monotonic_trend="auto",
n_subsamples=None, max_pvalue=None,
max_pvalue_policy="consecutive", outlier_detector=None,
outlier_params=None, user_splits=None, user_splits_fixed=None,
special_codes=None, split_digits=None, solver="auto",
h_epsilon=1.35, quantile=0.5, regularization=None, reg_l1=1.0,
reg_l2=1.0, random_state=None, verbose=False):
super().__init__(name, None, objective, degree, continuous,
prebinning_method, max_n_prebins, min_prebin_size,
min_n_bins, max_n_bins, min_bin_size, max_bin_size,
monotonic_trend, n_subsamples, max_pvalue,
max_pvalue_policy, outlier_detector, outlier_params,
user_splits, user_splits_fixed, special_codes,
split_digits, solver, h_epsilon, quantile,
regularization, reg_l1, reg_l2, random_state, verbose)
self._problem_type = "regression"
self._n_records_missing = None
self._n_records_special = None
self._sum_special = None
self._sum_missing = None
self._std_special = None
self._std_missing = None
self._min_target_missing = None
self._min_target_special = None
self._max_target_missing = None
self._max_target_special = None
self._n_zeros_missing = None
self._n_zeros_special = None
def fit_transform(self, x, y, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
"""Fit the optimal piecewise binning according to the given training
data, then transform it.
Parameters
----------
x : array-like, shape = (n_samples,)
Training vector, where n_samples is the number of samples.
y : array-like, shape = (n_samples,)
Target vector relative to x.
metric_special : float or str (default=0)
The metric value to transform special codes in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
metric_missing : float or str (default=0)
The metric value to transform missing values in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
lb : float or None (default=None)
Avoid values below the lower bound lb.
ub : float or None (default=None)
Avoid values above the upper bound ub.
check_input : bool (default=False)
Whether to check input arrays.
Returns
-------
x_new : numpy array, shape = (n_samples,)
Transformed array.
"""
return self.fit(x, y, check_input).transform(
x, metric_special, metric_missing, lb, ub, check_input)
def transform(self, x, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
"""Transform given data using bins from the fitted optimal piecewise
binning.
Parameters
----------
x : array-like, shape = (n_samples,)
Training vector, where n_samples is the number of samples.
metric_special : float or str (default=0)
The metric value to transform special codes in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
metric_missing : float or str (default=0)
The metric value to transform missing values in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
lb : float or None (default=None)
Avoid values below the lower bound lb.
ub : float or None (default=None)
Avoid values above the upper bound ub.
check_input : bool (default=False)
Whether to check input arrays.
Returns
-------
x_new : numpy array, shape = (n_samples,)
Transformed array.
"""
self._check_is_fitted()
return transform_continuous_target(
self._optb.splits, x, self._c, lb, ub, self._n_records_special,
self._sum_special, self._n_records_missing, self._sum_missing,
self.special_codes, metric_special, metric_missing, check_input)
def _fit(self, x, y, lb, ub, check_input):
time_init = time.perf_counter()
if self.verbose:
self._logger.info("Optimal piecewise binning started.")
self._logger.info("Options: check parameters.")
_check_parameters(**self.get_params(deep=False), estimator=None,
problem_type=self._problem_type)
# Pre-processing
if self.verbose:
self._logger.info("Pre-processing started.")
self._n_samples = len(x)
if self.verbose:
self._logger.info("Pre-processing: number of samples: {}"
.format(self._n_samples))
time_preprocessing = time.perf_counter()
[x_clean, y_clean, x_missing, y_missing, x_special, y_special,
_, _, _, _, _, _, _] = self._fit_preprocessing(x, y, check_input)
self._time_preprocessing = time.perf_counter() - time_preprocessing
if self.verbose:
n_clean = len(x_clean)
n_missing = len(x_missing)
n_special = len(x_special)
self._logger.info("Pre-processing: number of clean samples: {}"
.format(n_clean))
self._logger.info("Pre-processing: number of missing samples: {}"
.format(n_missing))
self._logger.info("Pre-processing: number of special samples: {}"
.format(n_special))
if self.outlier_detector is not None:
n_outlier = self._n_samples-(n_clean + n_missing + n_special)
self._logger.info("Pre-processing: number of outlier samples: "
"{}".format(n_outlier))
self._logger.info("Pre-processing terminated. Time: {:.4f}s"
.format(self._time_preprocessing))
# Pre-binning
self._time_estimator = 0
# Fit optimal binning algorithm for continuous target. Use optimal
# split points to compute optimal piecewise functions
self._fit_binning(x_clean, y_clean, y_clean, lb, ub)
# Post-processing
if self.verbose:
self._logger.info("Post-processing started.")
self._logger.info("Post-processing: compute binning information.")
time_postprocessing = time.perf_counter()
# Compute n_records and sum for special and missing
self._n_records_special = len(y_special)
self._sum_special = np.sum(y_special)
self._n_zeros_special = np.count_nonzero(y_special == 0)
if len(y_special):
self._std_special = np.std(y_special)
self._min_target_special = np.min(y_special)
self._max_target_special = np.max(y_special)
self._n_records_missing = len(y_missing)
self._sum_missing = np.sum(y_missing)
self._n_zeros_missing = np.count_nonzero(y_missing == 0)
if len(y_missing):
self._std_missing = np.std(y_missing)
self._min_target_missing = np.min(y_missing)
self._max_target_missing = np.max(y_missing)
bt = self._optb.binning_table.build(add_totals=False)
n_records = bt["Count"].values
sums = bt["Sum"].values
stds = bt["Std"].values
min_target = bt["Min"].values
max_target = bt["Max"].values
n_zeros = bt["Zeros count"].values
n_records[self._n_bins] = self._n_records_special
n_records[self._n_bins + 1] = self._n_records_missing
sums[self._n_bins] = self._sum_special
sums[self._n_bins + 1] = self._sum_missing
stds[self._n_bins] = self._std_special
stds[self._n_bins + 1] = self._std_missing
min_target[self._n_bins] = self._min_target_special
min_target[self._n_bins + 1] = self._min_target_missing
max_target[self._n_bins] = self._max_target_special
max_target[self._n_bins + 1] = self._max_target_missing
n_zeros[self._n_bins] = self._n_zeros_special
n_zeros[self._n_bins + 1] = self._n_zeros_missing
# Compute metrics
if self.verbose:
self._logger.info("Post-processing: compute performance metrics.")
d_metrics = continuous_metrics(
x_clean, y_clean, self._optb.splits, self._c, lb, ub,
self._n_records_special, self._sum_special,
self._n_records_missing, self._sum_missing, self.special_codes)
# Binning table
self._binning_table = PWContinuousBinningTable(
self.name, self._optb.splits, self._c, n_records, sums, stds,
min_target, max_target, n_zeros, lb, ub, x_clean.min(),
x_clean.max(), d_metrics)
self._time_postprocessing = time.perf_counter() - time_postprocessing
if self.verbose:
self._logger.info("Post-processing terminated. Time: {:.4f}s"
.format(self._time_postprocessing))
self._time_total = time.perf_counter() - time_init
if self.verbose:
self._logger.info("Optimal piecewise binning terminated. "
"Status: {}. Time: {:.4f}s"
.format(self._status, self._time_total))
# Completed successfully
self._class_logger.close()
self._is_fitted = True
return self
| 41.266504 | 79 | 0.640656 |
import time
import numpy as np
from .base import _check_parameters
from .base import BasePWBinning
from .binning_statistics import PWContinuousBinningTable
from .metrics import continuous_metrics
from .transformations import transform_continuous_target
class ContinuousOptimalPWBinning(BasePWBinning):
def __init__(self, name="", objective="l2", degree=1,
continuous=True, prebinning_method="cart", max_n_prebins=20,
min_prebin_size=0.05, min_n_bins=None, max_n_bins=None,
min_bin_size=None, max_bin_size=None, monotonic_trend="auto",
n_subsamples=None, max_pvalue=None,
max_pvalue_policy="consecutive", outlier_detector=None,
outlier_params=None, user_splits=None, user_splits_fixed=None,
special_codes=None, split_digits=None, solver="auto",
h_epsilon=1.35, quantile=0.5, regularization=None, reg_l1=1.0,
reg_l2=1.0, random_state=None, verbose=False):
super().__init__(name, None, objective, degree, continuous,
prebinning_method, max_n_prebins, min_prebin_size,
min_n_bins, max_n_bins, min_bin_size, max_bin_size,
monotonic_trend, n_subsamples, max_pvalue,
max_pvalue_policy, outlier_detector, outlier_params,
user_splits, user_splits_fixed, special_codes,
split_digits, solver, h_epsilon, quantile,
regularization, reg_l1, reg_l2, random_state, verbose)
self._problem_type = "regression"
self._n_records_missing = None
self._n_records_special = None
self._sum_special = None
self._sum_missing = None
self._std_special = None
self._std_missing = None
self._min_target_missing = None
self._min_target_special = None
self._max_target_missing = None
self._max_target_special = None
self._n_zeros_missing = None
self._n_zeros_special = None
def fit_transform(self, x, y, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
return self.fit(x, y, check_input).transform(
x, metric_special, metric_missing, lb, ub, check_input)
def transform(self, x, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
self._check_is_fitted()
return transform_continuous_target(
self._optb.splits, x, self._c, lb, ub, self._n_records_special,
self._sum_special, self._n_records_missing, self._sum_missing,
self.special_codes, metric_special, metric_missing, check_input)
def _fit(self, x, y, lb, ub, check_input):
time_init = time.perf_counter()
if self.verbose:
self._logger.info("Optimal piecewise binning started.")
self._logger.info("Options: check parameters.")
_check_parameters(**self.get_params(deep=False), estimator=None,
problem_type=self._problem_type)
if self.verbose:
self._logger.info("Pre-processing started.")
self._n_samples = len(x)
if self.verbose:
self._logger.info("Pre-processing: number of samples: {}"
.format(self._n_samples))
time_preprocessing = time.perf_counter()
[x_clean, y_clean, x_missing, y_missing, x_special, y_special,
_, _, _, _, _, _, _] = self._fit_preprocessing(x, y, check_input)
self._time_preprocessing = time.perf_counter() - time_preprocessing
if self.verbose:
n_clean = len(x_clean)
n_missing = len(x_missing)
n_special = len(x_special)
self._logger.info("Pre-processing: number of clean samples: {}"
.format(n_clean))
self._logger.info("Pre-processing: number of missing samples: {}"
.format(n_missing))
self._logger.info("Pre-processing: number of special samples: {}"
.format(n_special))
if self.outlier_detector is not None:
n_outlier = self._n_samples-(n_clean + n_missing + n_special)
self._logger.info("Pre-processing: number of outlier samples: "
"{}".format(n_outlier))
self._logger.info("Pre-processing terminated. Time: {:.4f}s"
.format(self._time_preprocessing))
self._time_estimator = 0
self._fit_binning(x_clean, y_clean, y_clean, lb, ub)
if self.verbose:
self._logger.info("Post-processing started.")
self._logger.info("Post-processing: compute binning information.")
time_postprocessing = time.perf_counter()
self._n_records_special = len(y_special)
self._sum_special = np.sum(y_special)
self._n_zeros_special = np.count_nonzero(y_special == 0)
if len(y_special):
self._std_special = np.std(y_special)
self._min_target_special = np.min(y_special)
self._max_target_special = np.max(y_special)
self._n_records_missing = len(y_missing)
self._sum_missing = np.sum(y_missing)
self._n_zeros_missing = np.count_nonzero(y_missing == 0)
if len(y_missing):
self._std_missing = np.std(y_missing)
self._min_target_missing = np.min(y_missing)
self._max_target_missing = np.max(y_missing)
bt = self._optb.binning_table.build(add_totals=False)
n_records = bt["Count"].values
sums = bt["Sum"].values
stds = bt["Std"].values
min_target = bt["Min"].values
max_target = bt["Max"].values
n_zeros = bt["Zeros count"].values
n_records[self._n_bins] = self._n_records_special
n_records[self._n_bins + 1] = self._n_records_missing
sums[self._n_bins] = self._sum_special
sums[self._n_bins + 1] = self._sum_missing
stds[self._n_bins] = self._std_special
stds[self._n_bins + 1] = self._std_missing
min_target[self._n_bins] = self._min_target_special
min_target[self._n_bins + 1] = self._min_target_missing
max_target[self._n_bins] = self._max_target_special
max_target[self._n_bins + 1] = self._max_target_missing
n_zeros[self._n_bins] = self._n_zeros_special
n_zeros[self._n_bins + 1] = self._n_zeros_missing
if self.verbose:
self._logger.info("Post-processing: compute performance metrics.")
d_metrics = continuous_metrics(
x_clean, y_clean, self._optb.splits, self._c, lb, ub,
self._n_records_special, self._sum_special,
self._n_records_missing, self._sum_missing, self.special_codes)
self._binning_table = PWContinuousBinningTable(
self.name, self._optb.splits, self._c, n_records, sums, stds,
min_target, max_target, n_zeros, lb, ub, x_clean.min(),
x_clean.max(), d_metrics)
self._time_postprocessing = time.perf_counter() - time_postprocessing
if self.verbose:
self._logger.info("Post-processing terminated. Time: {:.4f}s"
.format(self._time_postprocessing))
self._time_total = time.perf_counter() - time_init
if self.verbose:
self._logger.info("Optimal piecewise binning terminated. "
"Status: {}. Time: {:.4f}s"
.format(self._status, self._time_total))
self._class_logger.close()
self._is_fitted = True
return self
| true | true |
f71b7bd3333e78e80ac35643dea7e4992006e7c1 | 5,065 | py | Python | a3c_train.py | mmwebster/DeepRL-Grounding | aa7fa63fbc26e8b0fa3fe289a5fe5a00ef3e6278 | [
"MIT"
] | null | null | null | a3c_train.py | mmwebster/DeepRL-Grounding | aa7fa63fbc26e8b0fa3fe289a5fe5a00ef3e6278 | [
"MIT"
] | null | null | null | a3c_train.py | mmwebster/DeepRL-Grounding | aa7fa63fbc26e8b0fa3fe289a5fe5a00ef3e6278 | [
"MIT"
] | null | null | null | import torch.optim as optim
import env as grounding_env
from models import *
from torch.autograd import Variable
import logging
def ensure_shared_grads(model, shared_model):
for param, shared_param in zip(model.parameters(),
shared_model.parameters()):
if shared_param.grad is not None:
return
shared_param._grad = param.grad
def train(rank, args, shared_model):
torch.manual_seed(args.seed + rank)
env = grounding_env.GroundingEnv(args)
env.game_init()
model = A3C_LSTM_GA(args)
if (args.load != "0"):
print(str(rank) + " Loading model ... "+args.load)
model.load_state_dict(
torch.load(args.load, map_location=lambda storage, loc: storage))
model.train()
optimizer = optim.SGD(shared_model.parameters(), lr=args.lr)
p_losses = []
v_losses = []
(image, instruction), _, _, _ = env.reset()
instruction_idx = []
for word in instruction.split(" "):
instruction_idx.append(env.word_to_idx[word])
instruction_idx = np.array(instruction_idx)
image = torch.from_numpy(image).float()/255.0
instruction_idx = torch.from_numpy(instruction_idx).view(1, -1)
done = True
episode_length = 0
num_iters = 0
while True:
# Sync with the shared model
model.load_state_dict(shared_model.state_dict())
if done:
episode_length = 0
cx = Variable(torch.zeros(1, 256))
hx = Variable(torch.zeros(1, 256))
else:
cx = Variable(cx.data)
hx = Variable(hx.data)
values = []
log_probs = []
rewards = []
entropies = []
for step in range(args.num_steps):
episode_length += 1
tx = Variable(torch.from_numpy(np.array([episode_length])).long())
value, logit, (hx, cx) = model((Variable(image.unsqueeze(0)),
Variable(instruction_idx),
(tx, hx, cx)))
prob = F.softmax(logit)
log_prob = F.log_softmax(logit)
entropy = -(log_prob * prob).sum(1)
entropies.append(entropy)
action = prob.multinomial(num_samples=1).data
log_prob = log_prob.gather(1, Variable(action))
action = action.numpy()[0, 0]
(image, _), reward, done, _ = env.step(action)
done = done or episode_length >= args.max_episode_length
if done:
(image, instruction), _, _, _ = env.reset()
instruction_idx = []
for word in instruction.split(" "):
instruction_idx.append(env.word_to_idx[word])
instruction_idx = np.array(instruction_idx)
instruction_idx = torch.from_numpy(
instruction_idx).view(1, -1)
image = torch.from_numpy(image).float()/255.0
values.append(value)
log_probs.append(log_prob)
rewards.append(reward)
if done:
break
R = torch.zeros(1, 1)
if not done:
tx = Variable(torch.from_numpy(np.array([episode_length])).long())
value, _, _ = model((Variable(image.unsqueeze(0)),
Variable(instruction_idx), (tx, hx, cx)))
R = value.data
values.append(Variable(R))
policy_loss = 0
value_loss = 0
R = Variable(R)
gae = torch.zeros(1, 1)
for i in reversed(range(len(rewards))):
R = args.gamma * R + rewards[i]
advantage = R - values[i]
value_loss = value_loss + 0.5 * advantage.pow(2)
# Generalized Advantage Estimataion
delta_t = rewards[i] + args.gamma * \
values[i + 1].data - values[i].data
gae = gae * args.gamma * args.tau + delta_t
policy_loss = policy_loss - \
log_probs[i] * Variable(gae) - 0.01 * entropies[i]
optimizer.zero_grad()
p_losses.append(policy_loss.data[0, 0])
v_losses.append(value_loss.data[0, 0])
if(len(p_losses) > 1000):
num_iters += 1
print(" ".join([
"Training thread: {}".format(rank),
"Num iters: {}K".format(num_iters),
"Avg policy loss: {}".format(np.mean(p_losses)),
"Avg value loss: {}".format(np.mean(v_losses))]))
logging.info(" ".join([
"Training thread: {}".format(rank),
"Num iters: {}K".format(num_iters),
"Avg policy loss: {}".format(np.mean(p_losses)),
"Avg value loss: {}".format(np.mean(v_losses))]))
p_losses = []
v_losses = []
(policy_loss + 0.5 * value_loss).backward()
torch.nn.utils.clip_grad_norm(model.parameters(), 40)
ensure_shared_grads(model, shared_model)
optimizer.step()
| 32.261146 | 78 | 0.541165 | import torch.optim as optim
import env as grounding_env
from models import *
from torch.autograd import Variable
import logging
def ensure_shared_grads(model, shared_model):
for param, shared_param in zip(model.parameters(),
shared_model.parameters()):
if shared_param.grad is not None:
return
shared_param._grad = param.grad
def train(rank, args, shared_model):
torch.manual_seed(args.seed + rank)
env = grounding_env.GroundingEnv(args)
env.game_init()
model = A3C_LSTM_GA(args)
if (args.load != "0"):
print(str(rank) + " Loading model ... "+args.load)
model.load_state_dict(
torch.load(args.load, map_location=lambda storage, loc: storage))
model.train()
optimizer = optim.SGD(shared_model.parameters(), lr=args.lr)
p_losses = []
v_losses = []
(image, instruction), _, _, _ = env.reset()
instruction_idx = []
for word in instruction.split(" "):
instruction_idx.append(env.word_to_idx[word])
instruction_idx = np.array(instruction_idx)
image = torch.from_numpy(image).float()/255.0
instruction_idx = torch.from_numpy(instruction_idx).view(1, -1)
done = True
episode_length = 0
num_iters = 0
while True:
model.load_state_dict(shared_model.state_dict())
if done:
episode_length = 0
cx = Variable(torch.zeros(1, 256))
hx = Variable(torch.zeros(1, 256))
else:
cx = Variable(cx.data)
hx = Variable(hx.data)
values = []
log_probs = []
rewards = []
entropies = []
for step in range(args.num_steps):
episode_length += 1
tx = Variable(torch.from_numpy(np.array([episode_length])).long())
value, logit, (hx, cx) = model((Variable(image.unsqueeze(0)),
Variable(instruction_idx),
(tx, hx, cx)))
prob = F.softmax(logit)
log_prob = F.log_softmax(logit)
entropy = -(log_prob * prob).sum(1)
entropies.append(entropy)
action = prob.multinomial(num_samples=1).data
log_prob = log_prob.gather(1, Variable(action))
action = action.numpy()[0, 0]
(image, _), reward, done, _ = env.step(action)
done = done or episode_length >= args.max_episode_length
if done:
(image, instruction), _, _, _ = env.reset()
instruction_idx = []
for word in instruction.split(" "):
instruction_idx.append(env.word_to_idx[word])
instruction_idx = np.array(instruction_idx)
instruction_idx = torch.from_numpy(
instruction_idx).view(1, -1)
image = torch.from_numpy(image).float()/255.0
values.append(value)
log_probs.append(log_prob)
rewards.append(reward)
if done:
break
R = torch.zeros(1, 1)
if not done:
tx = Variable(torch.from_numpy(np.array([episode_length])).long())
value, _, _ = model((Variable(image.unsqueeze(0)),
Variable(instruction_idx), (tx, hx, cx)))
R = value.data
values.append(Variable(R))
policy_loss = 0
value_loss = 0
R = Variable(R)
gae = torch.zeros(1, 1)
for i in reversed(range(len(rewards))):
R = args.gamma * R + rewards[i]
advantage = R - values[i]
value_loss = value_loss + 0.5 * advantage.pow(2)
delta_t = rewards[i] + args.gamma * \
values[i + 1].data - values[i].data
gae = gae * args.gamma * args.tau + delta_t
policy_loss = policy_loss - \
log_probs[i] * Variable(gae) - 0.01 * entropies[i]
optimizer.zero_grad()
p_losses.append(policy_loss.data[0, 0])
v_losses.append(value_loss.data[0, 0])
if(len(p_losses) > 1000):
num_iters += 1
print(" ".join([
"Training thread: {}".format(rank),
"Num iters: {}K".format(num_iters),
"Avg policy loss: {}".format(np.mean(p_losses)),
"Avg value loss: {}".format(np.mean(v_losses))]))
logging.info(" ".join([
"Training thread: {}".format(rank),
"Num iters: {}K".format(num_iters),
"Avg policy loss: {}".format(np.mean(p_losses)),
"Avg value loss: {}".format(np.mean(v_losses))]))
p_losses = []
v_losses = []
(policy_loss + 0.5 * value_loss).backward()
torch.nn.utils.clip_grad_norm(model.parameters(), 40)
ensure_shared_grads(model, shared_model)
optimizer.step()
| true | true |
f71b7c3e0333f4799644586439f574a601d048f9 | 942 | py | Python | tema1/gym-master/gym/envs/tests/spec_list.py | oscarramos2001/Oscar-Marino-Ramos | c05e497b467aab4572f3578f1b9068d4585106d2 | [
"MIT"
] | 112 | 2018-11-19T17:23:40.000Z | 2022-03-29T05:36:14.000Z | tema1/gym-master/gym/envs/tests/spec_list.py | BrujitoOz/ia-course | c05e497b467aab4572f3578f1b9068d4585106d2 | [
"MIT"
] | 2 | 2020-03-23T01:17:45.000Z | 2020-07-02T07:01:06.000Z | tema1/gym-master/gym/envs/tests/spec_list.py | BrujitoOz/ia-course | c05e497b467aab4572f3578f1b9068d4585106d2 | [
"MIT"
] | 187 | 2018-11-28T11:38:02.000Z | 2022-03-16T11:18:39.000Z | from gym import envs, logger
import os
def should_skip_env_spec_for_tests(spec):
# We skip tests for envs that require dependencies or are otherwise
# troublesome to run frequently
ep = spec._entry_point
# Skip mujoco tests for pull request CI
skip_mujoco = not (os.environ.get('MUJOCO_KEY_BUNDLE') or os.path.exists(os.path.expanduser('~/.mujoco/mjkey.txt')))
if skip_mujoco and (ep.startswith('gym.envs.mujoco:') or ep.startswith('gym.envs.robotics:')):
return True
if ( 'GoEnv' in ep or
'HexEnv' in ep or
(ep.startswith("gym.envs.atari") and not spec.id.startswith("Pong") and not spec.id.startswith("Seaquest"))
):
logger.warn("Skipping tests for env {}".format(ep))
return True
return False
spec_list = [spec for spec in sorted(envs.registry.all(), key=lambda x: x.id) if spec._entry_point is not None and not should_skip_env_spec_for_tests(spec)]
| 44.857143 | 156 | 0.691083 | from gym import envs, logger
import os
def should_skip_env_spec_for_tests(spec):
ep = spec._entry_point
skip_mujoco = not (os.environ.get('MUJOCO_KEY_BUNDLE') or os.path.exists(os.path.expanduser('~/.mujoco/mjkey.txt')))
if skip_mujoco and (ep.startswith('gym.envs.mujoco:') or ep.startswith('gym.envs.robotics:')):
return True
if ( 'GoEnv' in ep or
'HexEnv' in ep or
(ep.startswith("gym.envs.atari") and not spec.id.startswith("Pong") and not spec.id.startswith("Seaquest"))
):
logger.warn("Skipping tests for env {}".format(ep))
return True
return False
spec_list = [spec for spec in sorted(envs.registry.all(), key=lambda x: x.id) if spec._entry_point is not None and not should_skip_env_spec_for_tests(spec)]
| true | true |
f71b7dce623850ef58b71a5f7bfbb56a6401aee0 | 495 | py | Python | python/concurrency/async_hello.py | cbare/Etudes | 8a803621f2abd20966843ccec696aec397d3c9f9 | [
"Apache-2.0"
] | null | null | null | python/concurrency/async_hello.py | cbare/Etudes | 8a803621f2abd20966843ccec696aec397d3c9f9 | [
"Apache-2.0"
] | null | null | null | python/concurrency/async_hello.py | cbare/Etudes | 8a803621f2abd20966843ccec696aec397d3c9f9 | [
"Apache-2.0"
] | null | null | null | import asyncio
async def upper_cased(value: str) -> str:
await asyncio.sleep(1)
return value.upper()
coroutines = [
upper_cased("h"),
upper_cased("e"),
upper_cased("l"),
upper_cased("l"),
upper_cased("o"),
upper_cased(" "),
upper_cased("w"),
upper_cased("o"),
upper_cased("r"),
upper_cased("l"),
upper_cased("d"),
]
async def main():
print("".join(await asyncio.gather(*coroutines)))
if __name__ == '__main__':
asyncio.run(main())
| 19.038462 | 53 | 0.60404 | import asyncio
async def upper_cased(value: str) -> str:
await asyncio.sleep(1)
return value.upper()
coroutines = [
upper_cased("h"),
upper_cased("e"),
upper_cased("l"),
upper_cased("l"),
upper_cased("o"),
upper_cased(" "),
upper_cased("w"),
upper_cased("o"),
upper_cased("r"),
upper_cased("l"),
upper_cased("d"),
]
async def main():
print("".join(await asyncio.gather(*coroutines)))
if __name__ == '__main__':
asyncio.run(main())
| true | true |
f71b7ec3e0cca942b7e4bde811a35de1811454fb | 186 | py | Python | knncommand.py | harishpichukala/Anomaly | e649fd8818826a2c29b2391c2d732a2758007f7b | [
"MIT"
] | 1 | 2015-04-08T06:29:39.000Z | 2015-04-08T06:29:39.000Z | knncommand.py | harishpichukala/Anomaly | e649fd8818826a2c29b2391c2d732a2758007f7b | [
"MIT"
] | null | null | null | knncommand.py | harishpichukala/Anomaly | e649fd8818826a2c29b2391c2d732a2758007f7b | [
"MIT"
] | null | null | null | from knn import compare
from Knndisplay import display_knn
import time
def get_knn():
start_time=time.time()
compare()
display_knn()
end_time=time.time()
print end_time-start_time
| 18.6 | 34 | 0.784946 | from knn import compare
from Knndisplay import display_knn
import time
def get_knn():
start_time=time.time()
compare()
display_knn()
end_time=time.time()
print end_time-start_time
| false | true |
f71b7f85ca2d04fe797bbe93b9985f9eedf2ad7c | 2,785 | py | Python | main.py | mwojcik96/dtw-utterance-recognition | 9371393dfe92abb5b85c40828d099ceca599aa89 | [
"MIT"
] | null | null | null | main.py | mwojcik96/dtw-utterance-recognition | 9371393dfe92abb5b85c40828d099ceca599aa89 | [
"MIT"
] | null | null | null | main.py | mwojcik96/dtw-utterance-recognition | 9371393dfe92abb5b85c40828d099ceca599aa89 | [
"MIT"
] | null | null | null | import glob
import struct
import wave
from collections import Counter
from operator import itemgetter
import librosa
import numpy as np
from tslearn.metrics import dtw
def compute_mfcc_from_file(file):
time_characteristic = create_time_characteristics_of_a_file(file)
mfcc = librosa.feature.mfcc(y=time_characteristic, sr=16000, n_mfcc=13)
return mfcc
def create_time_characteristics_of_a_file(file):
wave_file = wave.open(file, 'r')
# rate = wave_file.getframerate()
length = wave_file.getnframes()
time_plot = []
for i in range(0, length):
wave_data = wave_file.readframes(1)
data = struct.unpack("<h", wave_data)
time_plot.append(int(data[0]))
return np.array(time_plot, dtype=np.float32)
def compute_spectral_roloff(file):
chars = create_time_characteristics_of_a_file(file)
return librosa.feature.spectral_rolloff(chars, sr=16000)[0]
def calculate_dict(mfcc_values, rolloff_values, names, labels):
final_dict = dict()
for i in names:
final_dict[i] = []
for id1, (mf1, ro1, nm1, lb1) in enumerate(zip(mfcc_values, rolloff_values, names, labels)):
for id2, (mf2, ro2, nm2, lb2) in enumerate(zip(mfcc_values, rolloff_values, names, labels)):
if id1 < id2:
current_dtw = dtw(mf1, mf2)
# current_dtw = dtw(mf1 + ro1, mf2 + ro2)
final_dict[nm1].append({"name": nm2, "label": lb2, "distance": current_dtw})
final_dict[nm2].append({"name": nm1, "label": lb1, "distance": current_dtw})
for final_key, final_item in final_dict.items():
final_dict[final_key] = sorted(final_item, key=itemgetter('distance'))
# print(key, len(final_dict[key]))
return final_dict
def recognize_speech(vector, k=1):
nearest_neighbours = Counter(elem["label"] for elem in vector[:k])
return nearest_neighbours.most_common(1)[0][0]
if __name__ == '__main__':
mfcc_list = []
rolloff_list = []
name_list = []
label_list = []
for wav_name in glob.glob("./*/*.WAV"):
mfcc_list.append(compute_mfcc_from_file(wav_name).T)
rolloff_list.append(compute_spectral_roloff(wav_name))
name_list.append(wav_name.split("/")[-1])
label_list.append(wav_name.split("/")[-2])
dist_dict = calculate_dict(mfcc_list, rolloff_list, name_list, label_list)
for n in range(1, 11):
accuracy = 0
print("KNN for k =", n)
for key, item in dist_dict.items():
real = label_list[name_list.index(key)]
predicted = recognize_speech(item, n)
# print(key, "Real:", real, "Predicted:", predicted)
if real == predicted:
accuracy += 1
print("Accuracy:", accuracy / len(name_list))
| 35.705128 | 100 | 0.656732 | import glob
import struct
import wave
from collections import Counter
from operator import itemgetter
import librosa
import numpy as np
from tslearn.metrics import dtw
def compute_mfcc_from_file(file):
time_characteristic = create_time_characteristics_of_a_file(file)
mfcc = librosa.feature.mfcc(y=time_characteristic, sr=16000, n_mfcc=13)
return mfcc
def create_time_characteristics_of_a_file(file):
wave_file = wave.open(file, 'r')
length = wave_file.getnframes()
time_plot = []
for i in range(0, length):
wave_data = wave_file.readframes(1)
data = struct.unpack("<h", wave_data)
time_plot.append(int(data[0]))
return np.array(time_plot, dtype=np.float32)
def compute_spectral_roloff(file):
chars = create_time_characteristics_of_a_file(file)
return librosa.feature.spectral_rolloff(chars, sr=16000)[0]
def calculate_dict(mfcc_values, rolloff_values, names, labels):
final_dict = dict()
for i in names:
final_dict[i] = []
for id1, (mf1, ro1, nm1, lb1) in enumerate(zip(mfcc_values, rolloff_values, names, labels)):
for id2, (mf2, ro2, nm2, lb2) in enumerate(zip(mfcc_values, rolloff_values, names, labels)):
if id1 < id2:
current_dtw = dtw(mf1, mf2)
final_dict[nm1].append({"name": nm2, "label": lb2, "distance": current_dtw})
final_dict[nm2].append({"name": nm1, "label": lb1, "distance": current_dtw})
for final_key, final_item in final_dict.items():
final_dict[final_key] = sorted(final_item, key=itemgetter('distance'))
return final_dict
def recognize_speech(vector, k=1):
nearest_neighbours = Counter(elem["label"] for elem in vector[:k])
return nearest_neighbours.most_common(1)[0][0]
if __name__ == '__main__':
mfcc_list = []
rolloff_list = []
name_list = []
label_list = []
for wav_name in glob.glob("./*/*.WAV"):
mfcc_list.append(compute_mfcc_from_file(wav_name).T)
rolloff_list.append(compute_spectral_roloff(wav_name))
name_list.append(wav_name.split("/")[-1])
label_list.append(wav_name.split("/")[-2])
dist_dict = calculate_dict(mfcc_list, rolloff_list, name_list, label_list)
for n in range(1, 11):
accuracy = 0
print("KNN for k =", n)
for key, item in dist_dict.items():
real = label_list[name_list.index(key)]
predicted = recognize_speech(item, n)
if real == predicted:
accuracy += 1
print("Accuracy:", accuracy / len(name_list))
| true | true |
f71b7feab878e3386680bd41b4a9588ddf08c6c1 | 308 | py | Python | Main.py | MynorSaban1906/vacas | 5ca5b483b48088a409cb75cb5d18603a09274498 | [
"MIT"
] | null | null | null | Main.py | MynorSaban1906/vacas | 5ca5b483b48088a409cb75cb5d18603a09274498 | [
"MIT"
] | null | null | null | Main.py | MynorSaban1906/vacas | 5ca5b483b48088a409cb75cb5d18603a09274498 | [
"MIT"
] | null | null | null | import tkinter as tk
from Windows import StorageGui, NavBar
class Main:
root = tk.Tk()
root.geometry("1000x600")
root.title(" [EDD] Fase-1" )
app = StorageGui(master=root)
app.configure(bg='#2C3E50')
app.place(x=200,width=200,height=200)
app.mainloop()
start = Main() | 18.117647 | 41 | 0.636364 | import tkinter as tk
from Windows import StorageGui, NavBar
class Main:
root = tk.Tk()
root.geometry("1000x600")
root.title(" [EDD] Fase-1" )
app = StorageGui(master=root)
app.configure(bg='#2C3E50')
app.place(x=200,width=200,height=200)
app.mainloop()
start = Main() | true | true |
f71b801eb247a574b85aeca0cc7b8ec2789deb6f | 37,260 | py | Python | src/azure-cli/azure/cli/command_modules/servicefabric/_help.py | zackliu/azure-cli | 680f8339ac010a89d4063566fabc5991abc8a4c2 | [
"MIT"
] | 2 | 2021-03-24T21:06:25.000Z | 2021-03-24T21:07:59.000Z | src/azure-cli/azure/cli/command_modules/servicefabric/_help.py | zackliu/azure-cli | 680f8339ac010a89d4063566fabc5991abc8a4c2 | [
"MIT"
] | null | null | null | src/azure-cli/azure/cli/command_modules/servicefabric/_help.py | zackliu/azure-cli | 680f8339ac010a89d4063566fabc5991abc8a4c2 | [
"MIT"
] | 9 | 2020-02-12T22:53:00.000Z | 2021-06-09T18:59:41.000Z | # coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from knack.help_files import helps # pylint: disable=unused-import
# pylint: disable=line-too-long, too-many-lines
helps['sf'] = """
type: group
short-summary: Manage and administer Azure Service Fabric clusters.
"""
helps['sf application'] = """
type: group
short-summary: Manage applications running on an Azure Service Fabric cluster. Only support ARM deployed applications.
"""
helps['sf application create'] = """
type: command
short-summary: Create a new application on an Azure Service Fabric cluster.
examples:
- name: Create application "testApp" with parameters. The application type "TestAppType" version "v1" should already exist in the cluster, and the application parameters should be defined in the application manifest.
text: >
az sf application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --application-parameters key0=value0
- name: Create application "testApp" and app type version using the package url provided.
text: >
az sf application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg" \\
--application-parameters key0=value0
"""
helps['sf application update'] = """
type: command
short-summary: Update a Azure Service Fabric application. This allows updating the application parameters and/or upgrade the application type version which will trigger an application upgrade.
examples:
- name: Update application parameters and upgreade policy values and app type version to v2.
text: >
az sf application update -g testRG -c testCluster --application-name testApp --application-type-version v2 \\
--application-parameters key0=value0 --health-check-stable-duration 0 --health-check-wait-duration 0 --health-check-retry-timeout 0 \\
--upgrade-domain-timeout 5000 --upgrade-timeout 7000 --failure-action Rollback --upgrade-replica-set-check-timeout 300 --force-restart
- name: Update application minimum and maximum nodes.
text: >
az sf application update -g testRG -c testCluster --application-name testApp --minimum-nodes 1 --maximum-nodes 3
"""
helps['sf application certificate'] = """
type: group
short-summary: Manage the certificate of an application.
"""
helps['sf application certificate add'] = """
type: command
short-summary: Add a new certificate to the Virtual Machine Scale Sets that make up the cluster to be used by hosted applications.
examples:
- name: Add an application certificate.
text: >
az sf application certificate add -g group-name -c cluster1 --secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}'
"""
helps['sf application show'] = """
type: command
short-summary: Show the properties of an application on an Azure Service Fabric cluster.
examples:
- name: Get application.
text: >
az sf application show -g testRG -c testCluster --application-name testApp
"""
helps['sf application list'] = """
type: command
short-summary: List applications of a given cluster.
examples:
- name: List applications for a given cluster.
text: >
az sf application list -g testRG -c testCluster
"""
helps['sf application delete'] = """
type: command
short-summary: Delete an application.
examples:
- name: Delete application.
text: >
az sf application delete -g testRG -c testCluster --application-name testApp
"""
helps['sf application-type'] = """
type: group
short-summary: Manage applications types and its versions running on an Azure Service Fabric cluster. Only support ARM deployed application types.
"""
helps['sf application-type'] = """
type: group
short-summary: Manage application types on an Azure Service Fabric cluster.
"""
helps['sf application-type create'] = """
type: command
short-summary: Create a new application type on an Azure Service Fabric cluster.
examples:
- name: Create new application type.
text: >
az sf application-type create -g testRG -c testCluster --application-type-name testAppType
"""
helps['sf application-type show'] = """
type: command
short-summary: Show the properties of an application type on an Azure Service Fabric cluster.
examples:
- name: Get application type.
text: >
az sf application-type show -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type list'] = """
type: command
short-summary: List application types of a given cluster.
examples:
- name: List application types for a given cluster.
text: >
az sf application-type list -g testRG -c testCluster
"""
helps['sf application-type delete'] = """
type: command
short-summary: Delete an application type.
examples:
- name: Delete application type.
text: >
az sf application-type delete -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type version'] = """
type: group
short-summary: Manage application type versions on an Azure Service Fabric cluster. Only support ARM deployed application type versions.
"""
helps['sf application-type version create'] = """
type: command
short-summary: Create a new application type on an Azure Service Fabric cluster.
examples:
- name: Create new application type version using the provided package url. The version in the application manifest contained in the package should have the same version as the one specified in --version.
text: >
az sf application-type version create -g testRG -c testCluster --application-type-name testAppType \\
--version 1.0 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg"
"""
helps['sf application-type version show'] = """
type: command
short-summary: Show the properties of an application type version on an Azure Service Fabric cluster.
examples:
- name: Show the properties of an application type version on an Azure Service Fabric cluster.
text: >
az sf application-type version show -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf application-type version list'] = """
type: command
short-summary: List version of a given application type.
examples:
- name: List versions for a particular application type.
text: >
az sf application-type version list -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type version delete'] = """
type: command
short-summary: Delete an application type version.
examples:
- name: Delete application type version.
text: >
az sf application-type version delete -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf service'] = """
type: group
short-summary: Manage services running on an Azure Service Fabric cluster. Only support ARM deployed services.
"""
helps['sf service create'] = """
type: command
short-summary: Create a new service on an Azure Service Fabric cluster.
examples:
- name: Create a new stateless service "testApp~testService1" with instance count -1 (on all the nodes).
text: >
az sf service create -g testRG -c testCluster --application-name testApp --state stateless --service-name testApp~testService \\
--service-type testStateless --instance-count -1 --partition-scheme singleton
- name: Create a new stateful service "testApp~testService2" with a target of 5 nodes.
text: >
az sf service create -g testRG -c testCluster --application-name testApp --state stateful --service-name testApp~testService2 \\
--service-type testStatefulType --min-replica-set-size 3 --target-replica-set-size 5
"""
helps['sf service show'] = """
type: command
short-summary: Get a service.
examples:
- name: Show the properties of a service on an Azure Service Fabric cluster.
text: >
az sf service show -g testRG -c testCluster --application-name testApp --service-name testApp~testService
"""
helps['sf service list'] = """
type: command
short-summary: List services of a given application.
examples:
- name: List services.
text: >
az sf service list -g testRG -c testCluster --application-name testApp
"""
helps['sf service delete'] = """
type: command
short-summary: Delete a service.
examples:
- name: Delete service.
text: >
az sf service delete -g testRG -c testCluster --application-name testApp --service-name testApp~testService
"""
helps['sf cluster'] = """
type: group
short-summary: Manage an Azure Service Fabric cluster.
"""
helps['sf cluster certificate'] = """
type: group
short-summary: Manage a cluster certificate.
"""
helps['sf cluster certificate add'] = """
type: command
short-summary: Add a secondary cluster certificate to the cluster.
examples:
- name: Add a certificate to a cluster using a keyvault secret identifier.
text: |
az sf cluster certificate add -g group-name -c cluster1 \\
--secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}'
- name: Add a self-signed certificate to a cluster.
text: >
az sf cluster certificate add -g group-name -c cluster1 --certificate-subject-name test.com
- name: Add a secondary cluster certificate to the cluster. (autogenerated)
text: az sf cluster certificate add --cluster-name cluster1 --resource-group group-name --secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}' --vault-name MyVault
crafted: true
"""
helps['sf cluster certificate remove'] = """
type: command
short-summary: Remove a certificate from a cluster.
examples:
- name: Remove a certificate by thumbprint.
text: >
az sf cluster certificate remove -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster client-certificate'] = """
type: group
short-summary: Manage the client certificate of a cluster.
"""
helps['sf cluster client-certificate add'] = """
type: command
short-summary: Add a common name or certificate thumbprint to the cluster for client authentication.
examples:
- name: Add client certificate by thumbprint
text: >
az sf cluster client-certificate add -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster client-certificate remove'] = """
type: command
short-summary: Remove client certificates or subject names used for authentication.
examples:
- name: Remove a client certificate by thumbprint.
text: >
az sf cluster client-certificate remove -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster create'] = """
type: command
short-summary: Create a new Azure Service Fabric cluster.
examples:
- name: Create a cluster with a given size and self-signed certificate that is downloaded locally.
text: >
az sf cluster create -g group-name -c cluster1 -l westus --cluster-size 4 --vm-password Password#1234 --certificate-output-folder MyCertificates --certificate-subject-name cluster1
- name: Use a keyvault certificate and custom template to deploy a cluster.
text: >
az sf cluster create -g group-name -c cluster1 -l westus --template-file template.json \\
--parameter-file parameter.json --secret-identifier https://{KeyVault}.vault.azure.net:443/secrets/{MyCertificate}
"""
helps['sf cluster durability'] = """
type: group
short-summary: Manage the durability of a cluster.
"""
helps['sf cluster durability update'] = """
type: command
short-summary: Update the durability tier or VM SKU of a node type in the cluster.
examples:
- name: Change the cluster durability level to 'Silver'.
text: >
az sf cluster durability update -g group-name -c cluster1 --durability-level Silver --node-type nt1
"""
helps['sf cluster list'] = """
type: command
short-summary: List cluster resources.
"""
helps['sf cluster node'] = """
type: group
short-summary: Manage the node instance of a cluster.
"""
helps['sf cluster node add'] = """
type: command
short-summary: Add nodes to a node type in a cluster.
examples:
- name: Add 2 'nt1' nodes to a cluster.
text: >
az sf cluster node add -g group-name -c cluster1 --number-of-nodes-to-add 2 --node-type 'nt1'
"""
helps['sf cluster node remove'] = """
type: command
short-summary: Remove nodes from a node type in a cluster.
examples:
- name: Remove 2 'nt1' nodes from a cluster.
text: >
az sf cluster node remove -g group-name -c cluster1 --node-type 'nt1' --number-of-nodes-to-remove 2
"""
helps['sf cluster node-type'] = """
type: group
short-summary: Manage the node-type of a cluster.
"""
helps['sf cluster node-type add'] = """
type: command
short-summary: Add a new node type to a cluster.
examples:
- name: Add a new node type to a cluster.
text: >
az sf cluster node-type add -g group-name -c cluster1 --node-type 'n2' --capacity 5 --vm-user-name 'adminName' --vm-password testPassword0
"""
helps['sf cluster reliability'] = """
type: group
short-summary: Manage the reliability of a cluster.
"""
helps['sf cluster reliability update'] = """
type: command
short-summary: Update the reliability tier for the primary node in a cluster.
examples:
- name: Change the cluster reliability level to 'Silver'.
text: >
az sf cluster reliability update -g group-name -c cluster1 --reliability-level Silver
"""
helps['sf cluster setting'] = """
type: group
short-summary: Manage a cluster's settings.
"""
helps['sf cluster setting remove'] = """
type: command
short-summary: Remove settings from a cluster.
examples:
- name: Remove the `MaxFileOperationTimeout` setting from a cluster.
text: >
az sf cluster setting remove -g group-name -c cluster1 --section 'NamingService' --parameter 'MaxFileOperationTimeout'
"""
helps['sf cluster setting set'] = """
type: command
short-summary: Update the settings of a cluster.
examples:
- name: Set the `MaxFileOperationTimeout` setting for a cluster to 5 seconds.
text: >
az sf cluster setting set -g group-name -c cluster1 --section 'NamingService' --parameter 'MaxFileOperationTimeout' --value 5000
"""
helps['sf cluster upgrade-type'] = """
type: group
short-summary: Manage the upgrade type of a cluster.
"""
helps['sf cluster upgrade-type set'] = """
type: command
short-summary: Change the upgrade type for a cluster.
examples:
- name: Set a cluster to use the 'Automatic' upgrade mode.
text: >
az sf cluster upgrade-type set -g group-name -c cluster1 --upgrade-mode Automatic
"""
helps['sf managed-cluster'] = """
type: group
short-summary: Manage an Azure Service Fabric managed cluster.
"""
helps['sf managed-cluster show'] = """
type: command
short-summary: Show the properties of an Azure Service Fabric managed cluster.
examples:
- name: Get cluster.
text: >
az sf managed-cluster show -g testRG -c testCluster
"""
helps['sf managed-cluster list'] = """
type: command
short-summary: List managed clusters.
examples:
- name: List clusters by resource group.
text: >
az sf managed-cluster list -g testRG
- name: List clusters by subscription.
text: >
az sf managed-cluster list
"""
helps['sf managed-cluster create'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Create cluster with standard sku and client cert by thumbprint.
text: >
az sf managed-cluster create -g testRG -c testCluster -l eastus2 --cert-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --cert-is-admin --admin-password PassTest123@ --sku Standard
- name: Create cluster with standard sku and client cert by common name.
text: >
az sf managed-cluster create -g testRG -c testCluster -l eastus2 --cert-common-name Contoso.com --cert-issuer-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --cert-is-admin --admin-password PassTest123@ --sku Standard
"""
helps['sf managed-cluster update'] = """
type: command
short-summary: Update a managed cluster.
examples:
- name: Update cluster client port and dns name.
text: >
az sf managed-cluster update -g testRG -c testCluster --client-port 50000 --dns-name testnewdns
"""
helps['sf managed-cluster delete'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Delete cluster.
text: >
az sf managed-cluster delete -g testRG -c testCluster
"""
helps['sf managed-cluster client-certificate'] = """
type: group
short-summary: Manage client certificates of a manged cluster.
"""
helps['sf managed-cluster client-certificate add'] = """
type: command
short-summary: Add a new client certificate to the managed cluster.
examples:
- name: Add admin client certificate by thumbprint.
text: >
az sf managed-cluster client-certificate add -g testRG -c testCluster --thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --is-admin
- name: Add non admin client certificate by common name.
text: >
az sf managed-cluster client-certificate add -g testRG -c testCluster --common-name Contoso.com --issuer-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
"""
helps['sf managed-cluster client-certificate delete'] = """
type: command
short-summary: Delete a client certificate from the managed cluster.
examples:
- name: Delete client certificate by thumbprint.
text: >
az sf managed-cluster client-certificate delete -g testRG -c testCluster --thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- name: Delete client certificate by common name.
text: >
az sf managed-cluster client-certificate delete -g testRG -c testCluster --common-name Contoso.com
"""
helps['sf managed-node-type'] = """
type: group
short-summary: Manage a node type of an Azure Service Fabric managed cluster.
"""
helps['sf managed-node-type show'] = """
type: command
short-summary: Show the properties of a node type.
examples:
- name: Get node type.
text: >
az sf managed-node-type show -g testRG -c testCluster -n pnt
"""
helps['sf managed-node-type list'] = """
type: command
short-summary: List node types of a managed cluster.
examples:
- name: List node types by cluster.
text: >
az sf managed-node-type list -g testRG -c testCluster
"""
helps['sf managed-node-type create'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Create primary node type with 5 nodes.
text: >
az sf managed-node-type create -g testRG -c testCluster -n pnt --instance-count 5 --primary
- name: Create non primary node type with placement properities, capacities and ports.
text: >
az sf managed-node-type create -g testRG -c testCluster -n snt --instance-count 5 --placement-property NodeColor=Green SomeProperty=5 --capacity ClientConnections=65536 --app-start-port 20575 --app-end-port 20605 --ephemeral-start-port 20606 --ephemeral-end-port 20861
"""
helps['sf managed-node-type update'] = """
type: command
short-summary: Update a managed cluster.
examples:
- name: Update the instance count of the node type.
text: >
az sf managed-node-type update -g testRG -c testCluster -n snt --instance-count 7
- name: Update placement properties of the node type. This will overwrite older placement properties if any.
text: >
az sf managed-node-type update -g testRG -c testCluster -n snt --placement-property NodeColor=Red SomeProperty=6
"""
helps['sf managed-node-type delete'] = """
type: command
short-summary: Delete node type from a cluster.
examples:
- name: Delete cluster.
text: >
az sf managed-node-type delete -g testRG -c testCluster -n snt
"""
helps['sf managed-node-type node'] = """
type: group
short-summary: Perform operations on nodes of a node type on managed clusters.
"""
helps['sf managed-node-type node restart'] = """
type: command
short-summary: Restart nodes of a node type.
examples:
- name: Restart 2 nodes.
text: >
az sf managed-node-type node restart -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type node reimage'] = """
type: command
short-summary: Reimage nodes of a node type.
examples:
- name: Reimage 2 nodes.
text: >
az sf managed-node-type node reimage -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type node delete'] = """
type: command
short-summary: Delete nodes of a node type.
examples:
- name: Delete 2 nodes.
text: >
az sf managed-node-type node delete -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type vm-extension'] = """
type: group
short-summary: Managed vm extension on a node type on managed clusters.
"""
helps['sf managed-node-type vm-extension add'] = """
type: command
short-summary: Add an extension to the node type.
examples:
- name: Add bg extension.
text: >
az sf managed-node-type vm-extension add -g testRG -c testCluster -n snt --extension-name csetest --publisher Microsoft.Compute --extension-type BGInfo --type-handler-version 2.1 --auto-upgrade-minor-version
"""
helps['sf managed-node-type vm-extension delete'] = """
type: command
short-summary: Delete an extension to the node type.
examples:
- name: Delete extension by name.
text: >
az sf managed-node-type vm-extension delete -g testRG -c testCluster -n snt --extension-name csetest
"""
helps['sf managed-node-type vm-secret'] = """
type: group
short-summary: Managed vm secrets on a node type on managed clusters.
"""
helps['sf managed-node-type vm-secret add'] = """
type: command
short-summary: Add a secret to the node type.
examples:
- name: Add certificate to the node type as a secret.
text: >
az sf managed-node-type vm-secret add -g testRG -c testCluster -n snt --source-vault-id /subscriptions/XXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/testRG/providers/Microsoft.KeyVault/vaults/testkv --certificate-url https://testskv.vault.azure.net:443/secrets/TestCert/xxxxxxxxxxxxxxxxxxxxxxxx --certificate-store my
"""
helps['sf managed-application'] = """
type: group
short-summary: Manage applications running on an Azure Service Fabric managed cluster. Only support ARM deployed applications.
"""
helps['sf managed-application create'] = """
type: command
short-summary: Create a new managed application on an Azure Service Fabric managed cluster.
examples:
- name: Create managed application "testApp" with parameters. The application type "TestAppType" version "v1" should already exist in the cluster, and the application parameters should be defined in the application manifest.
text: >
az sf managed-application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --application-parameters key0=value0 --tags key1=value1
- name: Create application "testApp" and app type version using the package url provided.
text: >
az sf managed-application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg" \\
--application-parameters key0=value0
"""
helps['sf managed-application update'] = """
type: command
short-summary: Update a Azure Service Fabric managed application.
long-summary: This allows for updating the tags, the application parameters, value is the application UpgradePolicy and/or upgrade the application type version which will trigger an application upgrade.
examples:
- name: Update application parameters and upgreade policy values and app type version to v2.
text: >
az sf managed-application update -g testRG -c testCluster --application-name testApp --application-type-version v2 \\
--application-parameters key0=value0 --health-check-stable-duration 0 --health-check-wait-duration 0 --health-check-retry-timeout 0 \\
--upgrade-domain-timeout 5000 --upgrade-timeout 7000 --failure-action Rollback --upgrade-replica-set-check-timeout 300 --force-restart
- name: Update managed application service type health policy map.
text: >
az sf managed-application update -g testRG -c testCluster --application-name testApp --service-type-health-policy-map \"ServiceTypeName01\"=\"5,10,5\" \"ServiceTypeName02\"=\"5,5,5\"
"""
helps['sf managed-application show'] = """
type: command
short-summary: Show the properties of a managed application on an Azure Service Fabric managed cluster.
examples:
- name: Get managed application.
text: >
az sf managed-application show -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-application list'] = """
type: command
short-summary: List managed applications of a given managed cluster.
examples:
- name: List managed applications for a given managed cluster.
text: >
az sf managed-application list -g testRG -c testCluster
"""
helps['sf managed-application delete'] = """
type: command
short-summary: Delete a managed application.
examples:
- name: Delete managed application.
text: >
az sf managed-application delete -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-application-type'] = """
type: group
short-summary: Manage applications types and its versions running on an Azure Service Fabric managed cluster. Only support ARM deployed application types.
"""
helps['sf managed-application-type'] = """
type: group
short-summary: Manage application types on an Azure Service Fabric cluster.
"""
helps['sf managed-application-type create'] = """
type: command
short-summary: Create a new managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Create new managed application type.
text: >
az sf managed-application-type create -g testRG -c testCluster --application-type-name testAppType
"""
helps['sf managed-application-type show'] = """
type: command
short-summary: Show the properties of a managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Get managed application type.
text: >
az sf managed-application-type show -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type list'] = """
type: command
short-summary: List managed application types of a given managed cluster.
examples:
- name: List managed application types for a given managed cluster.
text: >
az sf managed-application-type list -g testRG -c testCluster
"""
helps['sf managed-application-type update'] = """
type: command
short-summary: Update an managed application type.
long-summary: This allows for updating of application type tags.
examples:
- name: Update application type tags.
text: >
az sf managed-application-type update -g testRG -c testCluster --application-type-name CalcServiceApp --tags new=tags are=nice
"""
helps['sf managed-application-type delete'] = """
type: command
short-summary: Delete a managed application type.
examples:
- name: Delete managed application type.
text: >
az sf managed-application-type delete -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type version'] = """
type: group
short-summary: Manage application type versions on an Azure Service Fabric managed cluster. Only support ARM deployed application type versions.
"""
helps['sf managed-application-type version create'] = """
type: command
short-summary: Create a new managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Create new managed application type version using the provided package url. The version in the application manifest contained in the package should have the same version as the one specified in --version.
text: >
az sf managed-application-type version create -g testRG -c testCluster --application-type-name testAppType \\
--version 1.0 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg"
"""
helps['sf managed-application-type version show'] = """
type: command
short-summary: Show the properties of a managed application type version on an Azure Service Fabric managed cluster.
examples:
- name: Show the properties of a managed application type version on an Azure Service Fabric managed cluster.
text: >
az sf managed-application-type version show -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf managed-application-type version list'] = """
type: command
short-summary: List versions of a given managed application type.
examples:
- name: List versions for a particular managed application type.
text: >
az sf managed-application-type version list -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type version update'] = """
type: command
short-summary: Update a managed application type version.
long-summary: This allows for updating of application type version tags and the package url.
examples:
- name: Update managed application type version.
text: >
az sf managed-application-type version update -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0 --tags new=tags
"""
helps['sf managed-application-type version delete'] = """
type: command
short-summary: Delete a managed application type version.
examples:
- name: Delete managed application type version.
text: >
az sf managed-application-type version delete -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf managed-service'] = """
type: group
short-summary: Manage services running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service create'] = """
type: command
short-summary: Create a new managed service on an Azure Service Fabric managed cluster.
examples:
- name: Create a new stateless managed service "testService1" with instance count -1 (on all the nodes).
text: >
az sf managed-service create -g testRG -c testCluster --application-name testApp --state stateless --service-name testService \\
--service-type testStateless --instance-count -1 --partition-scheme singleton
- name: Create a new stateful service "testService2" with a target of 5 nodes.
text: >
az sf managed-service create -g testRG -c testCluster --application-name testApp --state stateful --service-name testService2 --has-persisted-state \\
--service-type testStatefulType --min-replica-set-size 3 --target-replica-set-size 5 --partition-scheme uniformint64range --partition-count 1 --low-key 0 --high-key 25
"""
helps['sf managed-service show'] = """
type: command
short-summary: Get a service.
examples:
- name: Show the properties of a managed service on an Azure Service Fabric managed cluster.
text: >
az sf managed-service show -g testRG -c testCluster --application-name testApp --service-name testService
"""
helps['sf managed-service list'] = """
type: command
short-summary: List managed services of a given managed application.
examples:
- name: List managed services.
text: >
az sf managed-service list -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-service update'] = """
type: command
short-summary: Update a managed service.
examples:
- name: Update managed stateless service.
text: >
az sf managed-service update -g testRG -c testCluster --application-name testApp --service-name testService --min-instance-count 2 \\
--min-instance-percentage 20 --instance-close-delay-duration '00:11:00'
- name: Update managed stateful service.
text: >
az sf managed-service update -g testRG -c testCluster --application-name testApp --service-name testService2 --service-placement-time-limit '00:11:00' \\
--stand-by-replica-keep-duration '00:11:00' --replica-restart-wait-duration '00:11:00' --quorum-loss-wait-duration '00:11:00'
"""
helps['sf managed-service delete'] = """
type: command
short-summary: Delete a managed service.
examples:
- name: Delete managed service.
text: >
az sf managed-service delete -g testRG -c testCluster --application-name testApp --service-name testService
"""
helps['sf managed-service correlation-scheme'] = """
type: group
short-summary: Manage correlation schemes of services running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service correlation-scheme create'] = """
type: command
short-summary: Create a new managed service correlation scheme on an Azure Service Fabric managed cluster.
long-summary: Create a new managed service correlation scheme on an Azure Service Fabric managed cluster. NOTE You can only have one service correlation per service.
examples:
- name: Create a new managed service correlation scheme.
text: >
az sf managed-service correlation-scheme create -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2" \\
--scheme AlignedAffinity
"""
helps['sf managed-service correlation-scheme update'] = """
type: command
short-summary: Update a managed service correlation scheme.
examples:
- name: Update managed service correlation scheme.
text: >
az sf managed-service correlation-scheme update -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2" \\
--scheme NonAlignedAffinity
"""
helps['sf managed-service correlation-scheme delete'] = """
type: command
short-summary: Delete a managed service correlation scheme.
examples:
- name: Delete managed service correlation scheme.
text: >
az sf managed-service correlation-scheme delete -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2"
"""
helps['sf managed-service load-metrics'] = """
type: group
short-summary: Manage service load metrics running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service load-metrics create'] = """
type: command
short-summary: Create a new managed service load metric on an Azure Service Fabric managed cluster.
examples:
- name: Create a new stateless managed service load metric.
text: >
az sf managed-service load-metrics create -g testRG -c testCluster --application-name testApp --service-name testService \\
--metric-name Metric1 --weight Low --default-load 3
- name: Create a new stateful service load metric.
text: >
az sf managed-service load-metrics create -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric2 --weight High --primary-default-load 3 --secondary-default-load 2
"""
helps['sf managed-service load-metrics update'] = """
type: command
short-summary: Update a managed service.
examples:
- name: Update a new stateless managed service load metric.
text: >
az sf managed-service load-metrics update -g testRG -c testCluster --application-name testApp --service-name testService \\
--metric-name Metric1 --weight Medium --default-load 5
- name: Update a new stateful service load metric.
text: >
az sf managed-service load-metrics update -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric2 --weight Low --primary-default-load 2 --secondary-default-load 1
"""
helps['sf managed-service load-metrics delete'] = """
type: command
short-summary: Delete a managed service.
examples:
- name: Delete managed service.
text: >
az sf managed-service load-metrics delete -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric1
"""
| 39.892934 | 328 | 0.725819 |
from knack.help_files import helps
helps['sf'] = """
type: group
short-summary: Manage and administer Azure Service Fabric clusters.
"""
helps['sf application'] = """
type: group
short-summary: Manage applications running on an Azure Service Fabric cluster. Only support ARM deployed applications.
"""
helps['sf application create'] = """
type: command
short-summary: Create a new application on an Azure Service Fabric cluster.
examples:
- name: Create application "testApp" with parameters. The application type "TestAppType" version "v1" should already exist in the cluster, and the application parameters should be defined in the application manifest.
text: >
az sf application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --application-parameters key0=value0
- name: Create application "testApp" and app type version using the package url provided.
text: >
az sf application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg" \\
--application-parameters key0=value0
"""
helps['sf application update'] = """
type: command
short-summary: Update a Azure Service Fabric application. This allows updating the application parameters and/or upgrade the application type version which will trigger an application upgrade.
examples:
- name: Update application parameters and upgreade policy values and app type version to v2.
text: >
az sf application update -g testRG -c testCluster --application-name testApp --application-type-version v2 \\
--application-parameters key0=value0 --health-check-stable-duration 0 --health-check-wait-duration 0 --health-check-retry-timeout 0 \\
--upgrade-domain-timeout 5000 --upgrade-timeout 7000 --failure-action Rollback --upgrade-replica-set-check-timeout 300 --force-restart
- name: Update application minimum and maximum nodes.
text: >
az sf application update -g testRG -c testCluster --application-name testApp --minimum-nodes 1 --maximum-nodes 3
"""
helps['sf application certificate'] = """
type: group
short-summary: Manage the certificate of an application.
"""
helps['sf application certificate add'] = """
type: command
short-summary: Add a new certificate to the Virtual Machine Scale Sets that make up the cluster to be used by hosted applications.
examples:
- name: Add an application certificate.
text: >
az sf application certificate add -g group-name -c cluster1 --secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}'
"""
helps['sf application show'] = """
type: command
short-summary: Show the properties of an application on an Azure Service Fabric cluster.
examples:
- name: Get application.
text: >
az sf application show -g testRG -c testCluster --application-name testApp
"""
helps['sf application list'] = """
type: command
short-summary: List applications of a given cluster.
examples:
- name: List applications for a given cluster.
text: >
az sf application list -g testRG -c testCluster
"""
helps['sf application delete'] = """
type: command
short-summary: Delete an application.
examples:
- name: Delete application.
text: >
az sf application delete -g testRG -c testCluster --application-name testApp
"""
helps['sf application-type'] = """
type: group
short-summary: Manage applications types and its versions running on an Azure Service Fabric cluster. Only support ARM deployed application types.
"""
helps['sf application-type'] = """
type: group
short-summary: Manage application types on an Azure Service Fabric cluster.
"""
helps['sf application-type create'] = """
type: command
short-summary: Create a new application type on an Azure Service Fabric cluster.
examples:
- name: Create new application type.
text: >
az sf application-type create -g testRG -c testCluster --application-type-name testAppType
"""
helps['sf application-type show'] = """
type: command
short-summary: Show the properties of an application type on an Azure Service Fabric cluster.
examples:
- name: Get application type.
text: >
az sf application-type show -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type list'] = """
type: command
short-summary: List application types of a given cluster.
examples:
- name: List application types for a given cluster.
text: >
az sf application-type list -g testRG -c testCluster
"""
helps['sf application-type delete'] = """
type: command
short-summary: Delete an application type.
examples:
- name: Delete application type.
text: >
az sf application-type delete -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type version'] = """
type: group
short-summary: Manage application type versions on an Azure Service Fabric cluster. Only support ARM deployed application type versions.
"""
helps['sf application-type version create'] = """
type: command
short-summary: Create a new application type on an Azure Service Fabric cluster.
examples:
- name: Create new application type version using the provided package url. The version in the application manifest contained in the package should have the same version as the one specified in --version.
text: >
az sf application-type version create -g testRG -c testCluster --application-type-name testAppType \\
--version 1.0 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg"
"""
helps['sf application-type version show'] = """
type: command
short-summary: Show the properties of an application type version on an Azure Service Fabric cluster.
examples:
- name: Show the properties of an application type version on an Azure Service Fabric cluster.
text: >
az sf application-type version show -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf application-type version list'] = """
type: command
short-summary: List version of a given application type.
examples:
- name: List versions for a particular application type.
text: >
az sf application-type version list -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf application-type version delete'] = """
type: command
short-summary: Delete an application type version.
examples:
- name: Delete application type version.
text: >
az sf application-type version delete -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf service'] = """
type: group
short-summary: Manage services running on an Azure Service Fabric cluster. Only support ARM deployed services.
"""
helps['sf service create'] = """
type: command
short-summary: Create a new service on an Azure Service Fabric cluster.
examples:
- name: Create a new stateless service "testApp~testService1" with instance count -1 (on all the nodes).
text: >
az sf service create -g testRG -c testCluster --application-name testApp --state stateless --service-name testApp~testService \\
--service-type testStateless --instance-count -1 --partition-scheme singleton
- name: Create a new stateful service "testApp~testService2" with a target of 5 nodes.
text: >
az sf service create -g testRG -c testCluster --application-name testApp --state stateful --service-name testApp~testService2 \\
--service-type testStatefulType --min-replica-set-size 3 --target-replica-set-size 5
"""
helps['sf service show'] = """
type: command
short-summary: Get a service.
examples:
- name: Show the properties of a service on an Azure Service Fabric cluster.
text: >
az sf service show -g testRG -c testCluster --application-name testApp --service-name testApp~testService
"""
helps['sf service list'] = """
type: command
short-summary: List services of a given application.
examples:
- name: List services.
text: >
az sf service list -g testRG -c testCluster --application-name testApp
"""
helps['sf service delete'] = """
type: command
short-summary: Delete a service.
examples:
- name: Delete service.
text: >
az sf service delete -g testRG -c testCluster --application-name testApp --service-name testApp~testService
"""
helps['sf cluster'] = """
type: group
short-summary: Manage an Azure Service Fabric cluster.
"""
helps['sf cluster certificate'] = """
type: group
short-summary: Manage a cluster certificate.
"""
helps['sf cluster certificate add'] = """
type: command
short-summary: Add a secondary cluster certificate to the cluster.
examples:
- name: Add a certificate to a cluster using a keyvault secret identifier.
text: |
az sf cluster certificate add -g group-name -c cluster1 \\
--secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}'
- name: Add a self-signed certificate to a cluster.
text: >
az sf cluster certificate add -g group-name -c cluster1 --certificate-subject-name test.com
- name: Add a secondary cluster certificate to the cluster. (autogenerated)
text: az sf cluster certificate add --cluster-name cluster1 --resource-group group-name --secret-identifier 'https://{KeyVault}.vault.azure.net/secrets/{Secret}' --vault-name MyVault
crafted: true
"""
helps['sf cluster certificate remove'] = """
type: command
short-summary: Remove a certificate from a cluster.
examples:
- name: Remove a certificate by thumbprint.
text: >
az sf cluster certificate remove -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster client-certificate'] = """
type: group
short-summary: Manage the client certificate of a cluster.
"""
helps['sf cluster client-certificate add'] = """
type: command
short-summary: Add a common name or certificate thumbprint to the cluster for client authentication.
examples:
- name: Add client certificate by thumbprint
text: >
az sf cluster client-certificate add -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster client-certificate remove'] = """
type: command
short-summary: Remove client certificates or subject names used for authentication.
examples:
- name: Remove a client certificate by thumbprint.
text: >
az sf cluster client-certificate remove -g group-name -c cluster1 --thumbprint '5F3660C715EBBDA31DB1FFDCF508302348DE8E7A'
"""
helps['sf cluster create'] = """
type: command
short-summary: Create a new Azure Service Fabric cluster.
examples:
- name: Create a cluster with a given size and self-signed certificate that is downloaded locally.
text: >
az sf cluster create -g group-name -c cluster1 -l westus --cluster-size 4 --vm-password Password#1234 --certificate-output-folder MyCertificates --certificate-subject-name cluster1
- name: Use a keyvault certificate and custom template to deploy a cluster.
text: >
az sf cluster create -g group-name -c cluster1 -l westus --template-file template.json \\
--parameter-file parameter.json --secret-identifier https://{KeyVault}.vault.azure.net:443/secrets/{MyCertificate}
"""
helps['sf cluster durability'] = """
type: group
short-summary: Manage the durability of a cluster.
"""
helps['sf cluster durability update'] = """
type: command
short-summary: Update the durability tier or VM SKU of a node type in the cluster.
examples:
- name: Change the cluster durability level to 'Silver'.
text: >
az sf cluster durability update -g group-name -c cluster1 --durability-level Silver --node-type nt1
"""
helps['sf cluster list'] = """
type: command
short-summary: List cluster resources.
"""
helps['sf cluster node'] = """
type: group
short-summary: Manage the node instance of a cluster.
"""
helps['sf cluster node add'] = """
type: command
short-summary: Add nodes to a node type in a cluster.
examples:
- name: Add 2 'nt1' nodes to a cluster.
text: >
az sf cluster node add -g group-name -c cluster1 --number-of-nodes-to-add 2 --node-type 'nt1'
"""
helps['sf cluster node remove'] = """
type: command
short-summary: Remove nodes from a node type in a cluster.
examples:
- name: Remove 2 'nt1' nodes from a cluster.
text: >
az sf cluster node remove -g group-name -c cluster1 --node-type 'nt1' --number-of-nodes-to-remove 2
"""
helps['sf cluster node-type'] = """
type: group
short-summary: Manage the node-type of a cluster.
"""
helps['sf cluster node-type add'] = """
type: command
short-summary: Add a new node type to a cluster.
examples:
- name: Add a new node type to a cluster.
text: >
az sf cluster node-type add -g group-name -c cluster1 --node-type 'n2' --capacity 5 --vm-user-name 'adminName' --vm-password testPassword0
"""
helps['sf cluster reliability'] = """
type: group
short-summary: Manage the reliability of a cluster.
"""
helps['sf cluster reliability update'] = """
type: command
short-summary: Update the reliability tier for the primary node in a cluster.
examples:
- name: Change the cluster reliability level to 'Silver'.
text: >
az sf cluster reliability update -g group-name -c cluster1 --reliability-level Silver
"""
helps['sf cluster setting'] = """
type: group
short-summary: Manage a cluster's settings.
"""
helps['sf cluster setting remove'] = """
type: command
short-summary: Remove settings from a cluster.
examples:
- name: Remove the `MaxFileOperationTimeout` setting from a cluster.
text: >
az sf cluster setting remove -g group-name -c cluster1 --section 'NamingService' --parameter 'MaxFileOperationTimeout'
"""
helps['sf cluster setting set'] = """
type: command
short-summary: Update the settings of a cluster.
examples:
- name: Set the `MaxFileOperationTimeout` setting for a cluster to 5 seconds.
text: >
az sf cluster setting set -g group-name -c cluster1 --section 'NamingService' --parameter 'MaxFileOperationTimeout' --value 5000
"""
helps['sf cluster upgrade-type'] = """
type: group
short-summary: Manage the upgrade type of a cluster.
"""
helps['sf cluster upgrade-type set'] = """
type: command
short-summary: Change the upgrade type for a cluster.
examples:
- name: Set a cluster to use the 'Automatic' upgrade mode.
text: >
az sf cluster upgrade-type set -g group-name -c cluster1 --upgrade-mode Automatic
"""
helps['sf managed-cluster'] = """
type: group
short-summary: Manage an Azure Service Fabric managed cluster.
"""
helps['sf managed-cluster show'] = """
type: command
short-summary: Show the properties of an Azure Service Fabric managed cluster.
examples:
- name: Get cluster.
text: >
az sf managed-cluster show -g testRG -c testCluster
"""
helps['sf managed-cluster list'] = """
type: command
short-summary: List managed clusters.
examples:
- name: List clusters by resource group.
text: >
az sf managed-cluster list -g testRG
- name: List clusters by subscription.
text: >
az sf managed-cluster list
"""
helps['sf managed-cluster create'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Create cluster with standard sku and client cert by thumbprint.
text: >
az sf managed-cluster create -g testRG -c testCluster -l eastus2 --cert-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --cert-is-admin --admin-password PassTest123@ --sku Standard
- name: Create cluster with standard sku and client cert by common name.
text: >
az sf managed-cluster create -g testRG -c testCluster -l eastus2 --cert-common-name Contoso.com --cert-issuer-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --cert-is-admin --admin-password PassTest123@ --sku Standard
"""
helps['sf managed-cluster update'] = """
type: command
short-summary: Update a managed cluster.
examples:
- name: Update cluster client port and dns name.
text: >
az sf managed-cluster update -g testRG -c testCluster --client-port 50000 --dns-name testnewdns
"""
helps['sf managed-cluster delete'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Delete cluster.
text: >
az sf managed-cluster delete -g testRG -c testCluster
"""
helps['sf managed-cluster client-certificate'] = """
type: group
short-summary: Manage client certificates of a manged cluster.
"""
helps['sf managed-cluster client-certificate add'] = """
type: command
short-summary: Add a new client certificate to the managed cluster.
examples:
- name: Add admin client certificate by thumbprint.
text: >
az sf managed-cluster client-certificate add -g testRG -c testCluster --thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX --is-admin
- name: Add non admin client certificate by common name.
text: >
az sf managed-cluster client-certificate add -g testRG -c testCluster --common-name Contoso.com --issuer-thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
"""
helps['sf managed-cluster client-certificate delete'] = """
type: command
short-summary: Delete a client certificate from the managed cluster.
examples:
- name: Delete client certificate by thumbprint.
text: >
az sf managed-cluster client-certificate delete -g testRG -c testCluster --thumbprint XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- name: Delete client certificate by common name.
text: >
az sf managed-cluster client-certificate delete -g testRG -c testCluster --common-name Contoso.com
"""
helps['sf managed-node-type'] = """
type: group
short-summary: Manage a node type of an Azure Service Fabric managed cluster.
"""
helps['sf managed-node-type show'] = """
type: command
short-summary: Show the properties of a node type.
examples:
- name: Get node type.
text: >
az sf managed-node-type show -g testRG -c testCluster -n pnt
"""
helps['sf managed-node-type list'] = """
type: command
short-summary: List node types of a managed cluster.
examples:
- name: List node types by cluster.
text: >
az sf managed-node-type list -g testRG -c testCluster
"""
helps['sf managed-node-type create'] = """
type: command
short-summary: Delete a managed cluster.
examples:
- name: Create primary node type with 5 nodes.
text: >
az sf managed-node-type create -g testRG -c testCluster -n pnt --instance-count 5 --primary
- name: Create non primary node type with placement properities, capacities and ports.
text: >
az sf managed-node-type create -g testRG -c testCluster -n snt --instance-count 5 --placement-property NodeColor=Green SomeProperty=5 --capacity ClientConnections=65536 --app-start-port 20575 --app-end-port 20605 --ephemeral-start-port 20606 --ephemeral-end-port 20861
"""
helps['sf managed-node-type update'] = """
type: command
short-summary: Update a managed cluster.
examples:
- name: Update the instance count of the node type.
text: >
az sf managed-node-type update -g testRG -c testCluster -n snt --instance-count 7
- name: Update placement properties of the node type. This will overwrite older placement properties if any.
text: >
az sf managed-node-type update -g testRG -c testCluster -n snt --placement-property NodeColor=Red SomeProperty=6
"""
helps['sf managed-node-type delete'] = """
type: command
short-summary: Delete node type from a cluster.
examples:
- name: Delete cluster.
text: >
az sf managed-node-type delete -g testRG -c testCluster -n snt
"""
helps['sf managed-node-type node'] = """
type: group
short-summary: Perform operations on nodes of a node type on managed clusters.
"""
helps['sf managed-node-type node restart'] = """
type: command
short-summary: Restart nodes of a node type.
examples:
- name: Restart 2 nodes.
text: >
az sf managed-node-type node restart -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type node reimage'] = """
type: command
short-summary: Reimage nodes of a node type.
examples:
- name: Reimage 2 nodes.
text: >
az sf managed-node-type node reimage -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type node delete'] = """
type: command
short-summary: Delete nodes of a node type.
examples:
- name: Delete 2 nodes.
text: >
az sf managed-node-type node delete -g testRG -c testCluster -n snt --node-name snt_0 snt_1
"""
helps['sf managed-node-type vm-extension'] = """
type: group
short-summary: Managed vm extension on a node type on managed clusters.
"""
helps['sf managed-node-type vm-extension add'] = """
type: command
short-summary: Add an extension to the node type.
examples:
- name: Add bg extension.
text: >
az sf managed-node-type vm-extension add -g testRG -c testCluster -n snt --extension-name csetest --publisher Microsoft.Compute --extension-type BGInfo --type-handler-version 2.1 --auto-upgrade-minor-version
"""
helps['sf managed-node-type vm-extension delete'] = """
type: command
short-summary: Delete an extension to the node type.
examples:
- name: Delete extension by name.
text: >
az sf managed-node-type vm-extension delete -g testRG -c testCluster -n snt --extension-name csetest
"""
helps['sf managed-node-type vm-secret'] = """
type: group
short-summary: Managed vm secrets on a node type on managed clusters.
"""
helps['sf managed-node-type vm-secret add'] = """
type: command
short-summary: Add a secret to the node type.
examples:
- name: Add certificate to the node type as a secret.
text: >
az sf managed-node-type vm-secret add -g testRG -c testCluster -n snt --source-vault-id /subscriptions/XXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/testRG/providers/Microsoft.KeyVault/vaults/testkv --certificate-url https://testskv.vault.azure.net:443/secrets/TestCert/xxxxxxxxxxxxxxxxxxxxxxxx --certificate-store my
"""
helps['sf managed-application'] = """
type: group
short-summary: Manage applications running on an Azure Service Fabric managed cluster. Only support ARM deployed applications.
"""
helps['sf managed-application create'] = """
type: command
short-summary: Create a new managed application on an Azure Service Fabric managed cluster.
examples:
- name: Create managed application "testApp" with parameters. The application type "TestAppType" version "v1" should already exist in the cluster, and the application parameters should be defined in the application manifest.
text: >
az sf managed-application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --application-parameters key0=value0 --tags key1=value1
- name: Create application "testApp" and app type version using the package url provided.
text: >
az sf managed-application create -g testRG -c testCluster --application-name testApp --application-type-name TestAppType \\
--application-type-version v1 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg" \\
--application-parameters key0=value0
"""
helps['sf managed-application update'] = """
type: command
short-summary: Update a Azure Service Fabric managed application.
long-summary: This allows for updating the tags, the application parameters, value is the application UpgradePolicy and/or upgrade the application type version which will trigger an application upgrade.
examples:
- name: Update application parameters and upgreade policy values and app type version to v2.
text: >
az sf managed-application update -g testRG -c testCluster --application-name testApp --application-type-version v2 \\
--application-parameters key0=value0 --health-check-stable-duration 0 --health-check-wait-duration 0 --health-check-retry-timeout 0 \\
--upgrade-domain-timeout 5000 --upgrade-timeout 7000 --failure-action Rollback --upgrade-replica-set-check-timeout 300 --force-restart
- name: Update managed application service type health policy map.
text: >
az sf managed-application update -g testRG -c testCluster --application-name testApp --service-type-health-policy-map \"ServiceTypeName01\"=\"5,10,5\" \"ServiceTypeName02\"=\"5,5,5\"
"""
helps['sf managed-application show'] = """
type: command
short-summary: Show the properties of a managed application on an Azure Service Fabric managed cluster.
examples:
- name: Get managed application.
text: >
az sf managed-application show -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-application list'] = """
type: command
short-summary: List managed applications of a given managed cluster.
examples:
- name: List managed applications for a given managed cluster.
text: >
az sf managed-application list -g testRG -c testCluster
"""
helps['sf managed-application delete'] = """
type: command
short-summary: Delete a managed application.
examples:
- name: Delete managed application.
text: >
az sf managed-application delete -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-application-type'] = """
type: group
short-summary: Manage applications types and its versions running on an Azure Service Fabric managed cluster. Only support ARM deployed application types.
"""
helps['sf managed-application-type'] = """
type: group
short-summary: Manage application types on an Azure Service Fabric cluster.
"""
helps['sf managed-application-type create'] = """
type: command
short-summary: Create a new managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Create new managed application type.
text: >
az sf managed-application-type create -g testRG -c testCluster --application-type-name testAppType
"""
helps['sf managed-application-type show'] = """
type: command
short-summary: Show the properties of a managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Get managed application type.
text: >
az sf managed-application-type show -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type list'] = """
type: command
short-summary: List managed application types of a given managed cluster.
examples:
- name: List managed application types for a given managed cluster.
text: >
az sf managed-application-type list -g testRG -c testCluster
"""
helps['sf managed-application-type update'] = """
type: command
short-summary: Update an managed application type.
long-summary: This allows for updating of application type tags.
examples:
- name: Update application type tags.
text: >
az sf managed-application-type update -g testRG -c testCluster --application-type-name CalcServiceApp --tags new=tags are=nice
"""
helps['sf managed-application-type delete'] = """
type: command
short-summary: Delete a managed application type.
examples:
- name: Delete managed application type.
text: >
az sf managed-application-type delete -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type version'] = """
type: group
short-summary: Manage application type versions on an Azure Service Fabric managed cluster. Only support ARM deployed application type versions.
"""
helps['sf managed-application-type version create'] = """
type: command
short-summary: Create a new managed application type on an Azure Service Fabric managed cluster.
examples:
- name: Create new managed application type version using the provided package url. The version in the application manifest contained in the package should have the same version as the one specified in --version.
text: >
az sf managed-application-type version create -g testRG -c testCluster --application-type-name testAppType \\
--version 1.0 --package-url "https://sftestapp.blob.core.windows.net/sftestapp/testApp_1.0.sfpkg"
"""
helps['sf managed-application-type version show'] = """
type: command
short-summary: Show the properties of a managed application type version on an Azure Service Fabric managed cluster.
examples:
- name: Show the properties of a managed application type version on an Azure Service Fabric managed cluster.
text: >
az sf managed-application-type version show -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf managed-application-type version list'] = """
type: command
short-summary: List versions of a given managed application type.
examples:
- name: List versions for a particular managed application type.
text: >
az sf managed-application-type version list -g testRG -c testCluster --application-type-name CalcServiceApp
"""
helps['sf managed-application-type version update'] = """
type: command
short-summary: Update a managed application type version.
long-summary: This allows for updating of application type version tags and the package url.
examples:
- name: Update managed application type version.
text: >
az sf managed-application-type version update -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0 --tags new=tags
"""
helps['sf managed-application-type version delete'] = """
type: command
short-summary: Delete a managed application type version.
examples:
- name: Delete managed application type version.
text: >
az sf managed-application-type version delete -g testRG -c testCluster --application-type-name CalcServiceApp --version 1.0
"""
helps['sf managed-service'] = """
type: group
short-summary: Manage services running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service create'] = """
type: command
short-summary: Create a new managed service on an Azure Service Fabric managed cluster.
examples:
- name: Create a new stateless managed service "testService1" with instance count -1 (on all the nodes).
text: >
az sf managed-service create -g testRG -c testCluster --application-name testApp --state stateless --service-name testService \\
--service-type testStateless --instance-count -1 --partition-scheme singleton
- name: Create a new stateful service "testService2" with a target of 5 nodes.
text: >
az sf managed-service create -g testRG -c testCluster --application-name testApp --state stateful --service-name testService2 --has-persisted-state \\
--service-type testStatefulType --min-replica-set-size 3 --target-replica-set-size 5 --partition-scheme uniformint64range --partition-count 1 --low-key 0 --high-key 25
"""
helps['sf managed-service show'] = """
type: command
short-summary: Get a service.
examples:
- name: Show the properties of a managed service on an Azure Service Fabric managed cluster.
text: >
az sf managed-service show -g testRG -c testCluster --application-name testApp --service-name testService
"""
helps['sf managed-service list'] = """
type: command
short-summary: List managed services of a given managed application.
examples:
- name: List managed services.
text: >
az sf managed-service list -g testRG -c testCluster --application-name testApp
"""
helps['sf managed-service update'] = """
type: command
short-summary: Update a managed service.
examples:
- name: Update managed stateless service.
text: >
az sf managed-service update -g testRG -c testCluster --application-name testApp --service-name testService --min-instance-count 2 \\
--min-instance-percentage 20 --instance-close-delay-duration '00:11:00'
- name: Update managed stateful service.
text: >
az sf managed-service update -g testRG -c testCluster --application-name testApp --service-name testService2 --service-placement-time-limit '00:11:00' \\
--stand-by-replica-keep-duration '00:11:00' --replica-restart-wait-duration '00:11:00' --quorum-loss-wait-duration '00:11:00'
"""
helps['sf managed-service delete'] = """
type: command
short-summary: Delete a managed service.
examples:
- name: Delete managed service.
text: >
az sf managed-service delete -g testRG -c testCluster --application-name testApp --service-name testService
"""
helps['sf managed-service correlation-scheme'] = """
type: group
short-summary: Manage correlation schemes of services running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service correlation-scheme create'] = """
type: command
short-summary: Create a new managed service correlation scheme on an Azure Service Fabric managed cluster.
long-summary: Create a new managed service correlation scheme on an Azure Service Fabric managed cluster. NOTE You can only have one service correlation per service.
examples:
- name: Create a new managed service correlation scheme.
text: >
az sf managed-service correlation-scheme create -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2" \\
--scheme AlignedAffinity
"""
helps['sf managed-service correlation-scheme update'] = """
type: command
short-summary: Update a managed service correlation scheme.
examples:
- name: Update managed service correlation scheme.
text: >
az sf managed-service correlation-scheme update -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2" \\
--scheme NonAlignedAffinity
"""
helps['sf managed-service correlation-scheme delete'] = """
type: command
short-summary: Delete a managed service correlation scheme.
examples:
- name: Delete managed service correlation scheme.
text: >
az sf managed-service correlation-scheme delete -g testRG -c testCluster --application-name testApp --service-name testService \\
--correlated-service-name "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/testRg/providers/Microsoft.ServiceFabric/managedclusters/testCluster/applications/testApp/services/testService2"
"""
helps['sf managed-service load-metrics'] = """
type: group
short-summary: Manage service load metrics running on an Azure Service Fabric managed cluster. Only support ARM deployed services.
"""
helps['sf managed-service load-metrics create'] = """
type: command
short-summary: Create a new managed service load metric on an Azure Service Fabric managed cluster.
examples:
- name: Create a new stateless managed service load metric.
text: >
az sf managed-service load-metrics create -g testRG -c testCluster --application-name testApp --service-name testService \\
--metric-name Metric1 --weight Low --default-load 3
- name: Create a new stateful service load metric.
text: >
az sf managed-service load-metrics create -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric2 --weight High --primary-default-load 3 --secondary-default-load 2
"""
helps['sf managed-service load-metrics update'] = """
type: command
short-summary: Update a managed service.
examples:
- name: Update a new stateless managed service load metric.
text: >
az sf managed-service load-metrics update -g testRG -c testCluster --application-name testApp --service-name testService \\
--metric-name Metric1 --weight Medium --default-load 5
- name: Update a new stateful service load metric.
text: >
az sf managed-service load-metrics update -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric2 --weight Low --primary-default-load 2 --secondary-default-load 1
"""
helps['sf managed-service load-metrics delete'] = """
type: command
short-summary: Delete a managed service.
examples:
- name: Delete managed service.
text: >
az sf managed-service load-metrics delete -g testRG -c testCluster --application-name testApp --service-name testService2 \\
--metric-name Metric1
"""
| true | true |
f71b8100e2c77204d39461f764e255793c25b730 | 1,884 | py | Python | american_gut_project_pipeline/pipeline/metrics.py | mas-dse-ringhilt/DSE-American-Gut-Project | dadb3be8d40d6fb325d26920b145c04c837a6869 | [
"CC-BY-4.0"
] | 1 | 2020-05-02T21:15:21.000Z | 2020-05-02T21:15:21.000Z | american_gut_project_pipeline/pipeline/metrics.py | ringhilterra/DSE-American-Gut-Project | dadb3be8d40d6fb325d26920b145c04c837a6869 | [
"CC-BY-4.0"
] | null | null | null | american_gut_project_pipeline/pipeline/metrics.py | ringhilterra/DSE-American-Gut-Project | dadb3be8d40d6fb325d26920b145c04c837a6869 | [
"CC-BY-4.0"
] | 2 | 2019-06-26T02:07:41.000Z | 2019-07-15T16:28:44.000Z | import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
def evaluate(clf, x_train, x_test, y_train, y_test, name, training_data_name, embedding, params=None):
predictions = clf.predict(x_train)
# train_tn, train_fp, train_fn, train_tp = confusion_matrix(y_train, predictions).ravel()
train_accuracy = accuracy_score(y_train, predictions)
# train_precision = precision_score(y_train, predictions)
# train_recall = recall_score(y_train, predictions)
train_f1_score = f1_score(y_train, predictions, average='weighted')
predictions = clf.predict(x_test)
# test_tn, test_fp, test_fn, test_tp = confusion_matrix(y_test, predictions).ravel()
test_accuracy = accuracy_score(y_test, predictions)
# test_precision = precision_score(y_test, predictions)
# test_recall = recall_score(y_test, predictions)
test_f1_score = f1_score(y_test, predictions, average='weighted')
result_dict = {
'name': [name],
'embedding': [embedding],
'params': [params],
'training_data_name': [training_data_name],
# 'train_true_negative': [train_tn],
# 'train_false_positive': [train_fp],
# 'train_false_negative': [train_fn],
# 'train_true_positive': [train_tp],
'train_accuracy': [train_accuracy],
# 'train_precision': [train_precision],
# 'train_recall': [train_recall],
'train_f1_score': [train_f1_score],
# 'test_true_negative': [test_tn],
# 'test_false_positive': [test_fp],
# 'test_false_negative': [test_fn],
# 'test_true_positive': [test_tp],
'test_accuracy': [test_accuracy],
# 'test_precision': [test_precision],
# 'test_recall': [test_recall],
'test_f1_score': [test_f1_score],
}
return pd.DataFrame(result_dict)
| 41.866667 | 102 | 0.684183 | import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
def evaluate(clf, x_train, x_test, y_train, y_test, name, training_data_name, embedding, params=None):
predictions = clf.predict(x_train)
train_accuracy = accuracy_score(y_train, predictions)
train_f1_score = f1_score(y_train, predictions, average='weighted')
predictions = clf.predict(x_test)
test_accuracy = accuracy_score(y_test, predictions)
test_f1_score = f1_score(y_test, predictions, average='weighted')
result_dict = {
'name': [name],
'embedding': [embedding],
'params': [params],
'training_data_name': [training_data_name],
'train_accuracy': [train_accuracy],
'train_f1_score': [train_f1_score],
'test_accuracy': [test_accuracy],
'test_f1_score': [test_f1_score],
}
return pd.DataFrame(result_dict)
| true | true |
f71b824fba4f7bb51835a6ef5657cce8b66fe369 | 112 | py | Python | ABC183/B.py | shimomura314/AtcoderCodes | db1d62a7715f5f1b3c40eceff8d34f0f34839f41 | [
"MIT"
] | null | null | null | ABC183/B.py | shimomura314/AtcoderCodes | db1d62a7715f5f1b3c40eceff8d34f0f34839f41 | [
"MIT"
] | null | null | null | ABC183/B.py | shimomura314/AtcoderCodes | db1d62a7715f5f1b3c40eceff8d34f0f34839f41 | [
"MIT"
] | null | null | null | sx, sy, gx, gy = map(int, input().split())
if sx == gx:
print(sx)
exit()
print(sx + sy*(gx-sx)/(gy+sy))
| 18.666667 | 42 | 0.517857 | sx, sy, gx, gy = map(int, input().split())
if sx == gx:
print(sx)
exit()
print(sx + sy*(gx-sx)/(gy+sy))
| true | true |
f71b826b9f28eb525f8e2cb61594898e1ab461e2 | 685 | py | Python | ted_sws/rml_to_html/resources/query_registry.py | meaningfy-ws/ted-xml-2-rdf | ac26a19f3761b7cf79d79a46be6323b658f067eb | [
"Apache-2.0"
] | 1 | 2022-03-21T12:32:52.000Z | 2022-03-21T12:32:52.000Z | ted_sws/rml_to_html/resources/query_registry.py | meaningfy-ws/ted-xml-2-rdf | ac26a19f3761b7cf79d79a46be6323b658f067eb | [
"Apache-2.0"
] | 24 | 2022-02-10T10:43:56.000Z | 2022-03-29T12:36:21.000Z | ted_sws/rml_to_html/resources/query_registry.py | meaningfy-ws/ted-sws | d1e351eacb2900f84ec7edc457e49d8202fbaff5 | [
"Apache-2.0"
] | null | null | null | from ted_sws.rml_to_html.resources import get_sparql_query
class QueryRegistry:
@property
def TRIPLE_MAP(self):
return get_sparql_query(query_file_name="get_triple_maps.rq")
@property
def LOGICAL_SOURCE(self):
return get_sparql_query(query_file_name="get_logical_source.rq")
@property
def SUBJECT_MAP(self):
return get_sparql_query(query_file_name="get_subject_map.rq")
@property
def PREDICATE_OBJECT_MAP(self):
return get_sparql_query(query_file_name="get_predicate_object_map.rq") \
@property
def TRIPLE_MAP_COMMENT_LABEL(self):
return get_sparql_query(query_file_name="get_label_comment.rq")
| 27.4 | 83 | 0.743066 | from ted_sws.rml_to_html.resources import get_sparql_query
class QueryRegistry:
@property
def TRIPLE_MAP(self):
return get_sparql_query(query_file_name="get_triple_maps.rq")
@property
def LOGICAL_SOURCE(self):
return get_sparql_query(query_file_name="get_logical_source.rq")
@property
def SUBJECT_MAP(self):
return get_sparql_query(query_file_name="get_subject_map.rq")
@property
def PREDICATE_OBJECT_MAP(self):
return get_sparql_query(query_file_name="get_predicate_object_map.rq") \
@property
def TRIPLE_MAP_COMMENT_LABEL(self):
return get_sparql_query(query_file_name="get_label_comment.rq")
| true | true |
f71b8275c618ced19c9930e8361174690cf06e80 | 10,326 | py | Python | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/18-extending_bound_32.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | 3 | 2021-04-23T23:29:26.000Z | 2022-03-23T10:00:30.000Z | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/18-extending_bound_32.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | null | null | null | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/18-extending_bound_32.py | EnricoMagnago/F3 | c863215c318d7d5f258eb9be38c6962cf6863b52 | [
"MIT"
] | 1 | 2021-11-17T22:02:56.000Z | 2021-11-17T22:02:56.000Z | from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_make_or
from mathsat import msat_make_leq, msat_make_equal
from mathsat import msat_make_number, msat_make_plus
from pysmt.environment import Environment as PysmtEnv
import pysmt.typing as types
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next, symb_to_next
from hint import Hint, Location
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
def check_ltl(menv: msat_env, enc: LTLEncoder) -> Tuple[Iterable, msat_term,
msat_term, msat_term]:
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
bool_type = msat_get_bool_type(menv)
real_type = msat_get_rational_type(menv)
i = msat_declare_function(menv, "i", real_type)
i = msat_make_constant(menv, i)
r = msat_declare_function(menv, "r", real_type)
r = msat_make_constant(menv, r)
l = msat_declare_function(menv, "l", real_type)
l = msat_make_constant(menv, l)
inc_i = msat_declare_function(menv, "inc_i", bool_type)
inc_i = msat_make_constant(menv, inc_i)
x_i = msat_declare_function(menv, name_next("i"), real_type)
x_i = msat_make_constant(menv, x_i)
x_r = msat_declare_function(menv, name_next("r"), real_type)
x_r = msat_make_constant(menv, x_r)
x_l = msat_declare_function(menv, name_next("l"), real_type)
x_l = msat_make_constant(menv, x_l)
x_inc_i = msat_declare_function(menv, name_next("inc_i"), bool_type)
x_inc_i = msat_make_constant(menv, x_inc_i)
curr2next = {i: x_i, r: x_r, l: x_l, inc_i: x_inc_i}
zero = msat_make_number(menv, "0")
one = msat_make_number(menv, "1")
r_gt_0 = msat_make_gt(menv, r, zero)
r_lt_l = msat_make_lt(menv, r, l)
i_geq_0 = msat_make_geq(menv, i, zero)
init = msat_make_and(menv, r_gt_0, r_lt_l)
init = msat_make_and(menv, init,
msat_make_and(menv, i_geq_0,
msat_make_not(menv, inc_i)))
init = msat_make_and(menv, init, msat_make_gt(menv, l, zero))
# r' = r
trans = msat_make_equal(menv, x_r, r)
# i < l -> ((inc_i' & i' = i + 1) | (!inc_i' & i' = i)) & l' = l
i_lt_l = msat_make_lt(menv, i, l)
x_i_eq_i_p_1 = msat_make_and(menv, x_inc_i,
msat_make_equal(menv, x_i,
msat_make_plus(menv, i, one)))
x_i_eq_i = msat_make_and(menv, msat_make_not(menv, x_inc_i),
msat_make_equal(menv, x_i, i))
x_i_eq_i_p_1_or_i = msat_make_or(menv, x_i_eq_i_p_1, x_i_eq_i)
x_l_eq_l = msat_make_equal(menv, x_l, l)
x_i_eq_i_p_1_or_i_and_x_l_eq_l = msat_make_and(menv, x_i_eq_i_p_1_or_i,
x_l_eq_l)
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_lt_l,
x_i_eq_i_p_1_or_i_and_x_l_eq_l))
# i >= l -> i' = 0 & l' = l + 1 & !inc_i'
i_geq_l = msat_make_geq(menv, i, l)
x_i_eq_0 = msat_make_equal(menv, x_i, zero)
x_l_eq_l_p_1 = msat_make_equal(menv, x_l, msat_make_plus(menv, l, one))
x_i_eq_0_and_x_l_eq_l_p_1 = msat_make_and(menv,
msat_make_and(menv, x_i_eq_0,
x_l_eq_l_p_1),
msat_make_not(menv, x_inc_i))
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_geq_l,
x_i_eq_0_and_x_l_eq_l_p_1))
# (G F inc_i) -> ! G F r > i
G_F_x_i_gt_i = enc.make_G(enc.make_F(inc_i))
r_gt_i = msat_make_gt(menv, r, i)
n_G_F_r_gt_i = msat_make_not(menv, enc.make_G(enc.make_F(r_gt_i)))
ltl = msat_make_impl(menv, G_F_x_i_gt_i, n_G_F_r_gt_i)
return TermMap(curr2next), init, trans, ltl
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
i = mgr.Symbol("i", types.REAL)
r = mgr.Symbol("r", types.REAL)
l = mgr.Symbol("l", types.REAL)
inc_i = mgr.Symbol("inc_i", types.BOOL)
symbs = frozenset([i, r, l, inc_i])
x_i = symb_to_next(mgr, i)
x_r = symb_to_next(mgr, r)
x_l = symb_to_next(mgr, l)
x_inc_i = symb_to_next(mgr, inc_i)
res = []
n0 = mgr.Real(0)
n1 = mgr.Real(1)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.GE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Plus(i, n1)))
h_i = Hint("h_i0", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc = Location(env, mgr.GE(r, n0))
loc.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r0", env, frozenset([r]), symbs)
h_r.set_locs([loc])
res.append(h_r)
loc = Location(env, mgr.GE(l, n0))
loc.set_progress(0, mgr.Equals(x_l, mgr.Plus(l, n1)))
h_l = Hint("h_l0", env, frozenset([l]), symbs)
h_l.set_locs([loc])
res.append(h_l)
loc = Location(env, inc_i)
loc.set_progress(0, x_inc_i)
h_inc = Hint("h_inc0", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc])
res.append(h_inc)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.LE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Minus(i, n1)))
h_i = Hint("h_i1", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc = Location(env, mgr.LE(r, n0))
loc.set_progress(0, mgr.Equals(x_r, mgr.Minus(r, n1)))
h_r = Hint("h_r1", env, frozenset([r]), symbs)
h_r.set_locs([loc])
res.append(h_r)
loc = Location(env, mgr.LE(l, n0))
loc.set_progress(0, mgr.Equals(x_l, mgr.Minus(l, n1)))
h_l = Hint("h_l1", env, frozenset([l]), symbs)
h_l.set_locs([loc])
res.append(h_l)
loc = Location(env, mgr.Not(inc_i))
loc.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc1", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc])
res.append(h_inc)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r2", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1])
res.append(h_r)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i)
loc1.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc2", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1])
res.append(h_inc)
loc0 = Location(env, mgr.GE(i, n0), mgr.GE(l, n0),
stutterT=mgr.Equals(x_i, mgr.Plus(i, l)))
loc0.set_progress(1, mgr.Equals(x_i, mgr.Plus(i, n1)))
loc1 = Location(env, mgr.GE(i, n0))
loc1.set_progress(0, mgr.Equals(x_i, i))
h_i = Hint("h_i3", env, frozenset([i]), symbs)
h_i.set_locs([loc0, loc1])
res.append(h_i)
loc0 = Location(env, mgr.GE(r, n0), mgr.GE(i, n0),
stutterT=mgr.Equals(x_r, mgr.Plus(r, i)))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r3", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1])
res.append(h_r)
loc0 = Location(env, mgr.GE(l, n0), mgr.GE(r, n0),
stutterT=mgr.Equals(x_l, mgr.Plus(l, r)))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l3", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1])
res.append(h_l)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i, stutterT=x_inc_i)
loc1.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc3", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1])
res.append(h_inc)
loc0 = Location(env, mgr.GE(i, n0))
loc0.set_progress(1, mgr.Equals(x_i, mgr.Plus(i, n1)))
loc1 = Location(env, mgr.GE(i, n0))
loc1.set_progress(2, mgr.Equals(x_i, i))
loc2 = Location(env, mgr.GE(i, n0))
loc2.set_progress(0, mgr.Equals(x_i, i))
h_i = Hint("h_i4", env, frozenset([i]), symbs)
h_i.set_locs([loc0, loc1, loc2])
res.append(h_i)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(2, mgr.Equals(x_r, mgr.Plus(r, n1)))
loc2 = Location(env, mgr.GE(r, n0))
loc2.set_progress(0, mgr.Equals(x_r, r))
h_r = Hint("h_r4", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1, loc2])
res.append(h_r)
loc0 = Location(env, mgr.GE(l, n0))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(2, mgr.Equals(x_l, l))
loc2 = Location(env, mgr.GE(l, n0))
loc2.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l4", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1, loc2])
res.append(h_l)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i, stutterT=x_inc_i)
loc1.set_progress(2, mgr.Not(x_inc_i))
loc2 = Location(env, mgr.Not(inc_i))
loc2.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc4", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1, loc2])
res.append(h_inc)
return frozenset(res)
| 35.242321 | 89 | 0.62454 | from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_make_or
from mathsat import msat_make_leq, msat_make_equal
from mathsat import msat_make_number, msat_make_plus
from pysmt.environment import Environment as PysmtEnv
import pysmt.typing as types
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next, symb_to_next
from hint import Hint, Location
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
def check_ltl(menv: msat_env, enc: LTLEncoder) -> Tuple[Iterable, msat_term,
msat_term, msat_term]:
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
bool_type = msat_get_bool_type(menv)
real_type = msat_get_rational_type(menv)
i = msat_declare_function(menv, "i", real_type)
i = msat_make_constant(menv, i)
r = msat_declare_function(menv, "r", real_type)
r = msat_make_constant(menv, r)
l = msat_declare_function(menv, "l", real_type)
l = msat_make_constant(menv, l)
inc_i = msat_declare_function(menv, "inc_i", bool_type)
inc_i = msat_make_constant(menv, inc_i)
x_i = msat_declare_function(menv, name_next("i"), real_type)
x_i = msat_make_constant(menv, x_i)
x_r = msat_declare_function(menv, name_next("r"), real_type)
x_r = msat_make_constant(menv, x_r)
x_l = msat_declare_function(menv, name_next("l"), real_type)
x_l = msat_make_constant(menv, x_l)
x_inc_i = msat_declare_function(menv, name_next("inc_i"), bool_type)
x_inc_i = msat_make_constant(menv, x_inc_i)
curr2next = {i: x_i, r: x_r, l: x_l, inc_i: x_inc_i}
zero = msat_make_number(menv, "0")
one = msat_make_number(menv, "1")
r_gt_0 = msat_make_gt(menv, r, zero)
r_lt_l = msat_make_lt(menv, r, l)
i_geq_0 = msat_make_geq(menv, i, zero)
init = msat_make_and(menv, r_gt_0, r_lt_l)
init = msat_make_and(menv, init,
msat_make_and(menv, i_geq_0,
msat_make_not(menv, inc_i)))
init = msat_make_and(menv, init, msat_make_gt(menv, l, zero))
trans = msat_make_equal(menv, x_r, r)
# i < l -> ((inc_i' & i' = i + 1) | (!inc_i' & i' = i)) & l' = l
i_lt_l = msat_make_lt(menv, i, l)
x_i_eq_i_p_1 = msat_make_and(menv, x_inc_i,
msat_make_equal(menv, x_i,
msat_make_plus(menv, i, one)))
x_i_eq_i = msat_make_and(menv, msat_make_not(menv, x_inc_i),
msat_make_equal(menv, x_i, i))
x_i_eq_i_p_1_or_i = msat_make_or(menv, x_i_eq_i_p_1, x_i_eq_i)
x_l_eq_l = msat_make_equal(menv, x_l, l)
x_i_eq_i_p_1_or_i_and_x_l_eq_l = msat_make_and(menv, x_i_eq_i_p_1_or_i,
x_l_eq_l)
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_lt_l,
x_i_eq_i_p_1_or_i_and_x_l_eq_l))
i_geq_l = msat_make_geq(menv, i, l)
x_i_eq_0 = msat_make_equal(menv, x_i, zero)
x_l_eq_l_p_1 = msat_make_equal(menv, x_l, msat_make_plus(menv, l, one))
x_i_eq_0_and_x_l_eq_l_p_1 = msat_make_and(menv,
msat_make_and(menv, x_i_eq_0,
x_l_eq_l_p_1),
msat_make_not(menv, x_inc_i))
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_geq_l,
x_i_eq_0_and_x_l_eq_l_p_1))
# (G F inc_i) -> ! G F r > i
G_F_x_i_gt_i = enc.make_G(enc.make_F(inc_i))
r_gt_i = msat_make_gt(menv, r, i)
n_G_F_r_gt_i = msat_make_not(menv, enc.make_G(enc.make_F(r_gt_i)))
ltl = msat_make_impl(menv, G_F_x_i_gt_i, n_G_F_r_gt_i)
return TermMap(curr2next), init, trans, ltl
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
i = mgr.Symbol("i", types.REAL)
r = mgr.Symbol("r", types.REAL)
l = mgr.Symbol("l", types.REAL)
inc_i = mgr.Symbol("inc_i", types.BOOL)
symbs = frozenset([i, r, l, inc_i])
x_i = symb_to_next(mgr, i)
x_r = symb_to_next(mgr, r)
x_l = symb_to_next(mgr, l)
x_inc_i = symb_to_next(mgr, inc_i)
res = []
n0 = mgr.Real(0)
n1 = mgr.Real(1)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.GE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Plus(i, n1)))
h_i = Hint("h_i0", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc = Location(env, mgr.GE(r, n0))
loc.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r0", env, frozenset([r]), symbs)
h_r.set_locs([loc])
res.append(h_r)
loc = Location(env, mgr.GE(l, n0))
loc.set_progress(0, mgr.Equals(x_l, mgr.Plus(l, n1)))
h_l = Hint("h_l0", env, frozenset([l]), symbs)
h_l.set_locs([loc])
res.append(h_l)
loc = Location(env, inc_i)
loc.set_progress(0, x_inc_i)
h_inc = Hint("h_inc0", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc])
res.append(h_inc)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.LE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Minus(i, n1)))
h_i = Hint("h_i1", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc = Location(env, mgr.LE(r, n0))
loc.set_progress(0, mgr.Equals(x_r, mgr.Minus(r, n1)))
h_r = Hint("h_r1", env, frozenset([r]), symbs)
h_r.set_locs([loc])
res.append(h_r)
loc = Location(env, mgr.LE(l, n0))
loc.set_progress(0, mgr.Equals(x_l, mgr.Minus(l, n1)))
h_l = Hint("h_l1", env, frozenset([l]), symbs)
h_l.set_locs([loc])
res.append(h_l)
loc = Location(env, mgr.Not(inc_i))
loc.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc1", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc])
res.append(h_inc)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r2", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1])
res.append(h_r)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i)
loc1.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc2", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1])
res.append(h_inc)
loc0 = Location(env, mgr.GE(i, n0), mgr.GE(l, n0),
stutterT=mgr.Equals(x_i, mgr.Plus(i, l)))
loc0.set_progress(1, mgr.Equals(x_i, mgr.Plus(i, n1)))
loc1 = Location(env, mgr.GE(i, n0))
loc1.set_progress(0, mgr.Equals(x_i, i))
h_i = Hint("h_i3", env, frozenset([i]), symbs)
h_i.set_locs([loc0, loc1])
res.append(h_i)
loc0 = Location(env, mgr.GE(r, n0), mgr.GE(i, n0),
stutterT=mgr.Equals(x_r, mgr.Plus(r, i)))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r3", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1])
res.append(h_r)
loc0 = Location(env, mgr.GE(l, n0), mgr.GE(r, n0),
stutterT=mgr.Equals(x_l, mgr.Plus(l, r)))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l3", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1])
res.append(h_l)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i, stutterT=x_inc_i)
loc1.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc3", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1])
res.append(h_inc)
loc0 = Location(env, mgr.GE(i, n0))
loc0.set_progress(1, mgr.Equals(x_i, mgr.Plus(i, n1)))
loc1 = Location(env, mgr.GE(i, n0))
loc1.set_progress(2, mgr.Equals(x_i, i))
loc2 = Location(env, mgr.GE(i, n0))
loc2.set_progress(0, mgr.Equals(x_i, i))
h_i = Hint("h_i4", env, frozenset([i]), symbs)
h_i.set_locs([loc0, loc1, loc2])
res.append(h_i)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(2, mgr.Equals(x_r, mgr.Plus(r, n1)))
loc2 = Location(env, mgr.GE(r, n0))
loc2.set_progress(0, mgr.Equals(x_r, r))
h_r = Hint("h_r4", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1, loc2])
res.append(h_r)
loc0 = Location(env, mgr.GE(l, n0))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(2, mgr.Equals(x_l, l))
loc2 = Location(env, mgr.GE(l, n0))
loc2.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l4", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1, loc2])
res.append(h_l)
loc0 = Location(env, mgr.Not(inc_i))
loc0.set_progress(1, x_inc_i)
loc1 = Location(env, inc_i, stutterT=x_inc_i)
loc1.set_progress(2, mgr.Not(x_inc_i))
loc2 = Location(env, mgr.Not(inc_i))
loc2.set_progress(0, mgr.Not(x_inc_i))
h_inc = Hint("h_inc4", env, frozenset([inc_i]), symbs)
h_inc.set_locs([loc0, loc1, loc2])
res.append(h_inc)
return frozenset(res)
| true | true |
f71b839ea462d9355fe88e220fc9c5b89f52ab5a | 827 | py | Python | virtex/serial/__init__.py | chrislarson1/virtex | 36eb47d1ace297951cae36edc8a00544b85fed79 | [
"Apache-2.0"
] | 5 | 2020-06-17T06:22:32.000Z | 2022-03-04T09:25:31.000Z | virtex/serial/__init__.py | virtexlabs/virtex | 36eb47d1ace297951cae36edc8a00544b85fed79 | [
"Apache-2.0"
] | null | null | null | virtex/serial/__init__.py | virtexlabs/virtex | 36eb47d1ace297951cae36edc8a00544b85fed79 | [
"Apache-2.0"
] | null | null | null | # -------------------------------------------------------------------
# Copyright 2021 Virtex authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
# -------------------------------------------------------------------
from .bytes import *
from .pillow import *
from .pickle import *
from .numpy import *
| 39.380952 | 69 | 0.629988 |
from .bytes import *
from .pillow import *
from .pickle import *
from .numpy import *
| true | true |
f71b83f83a3906286de03127e55e5392ecaea99d | 1,613 | py | Python | ishuhui/__init__.py | lawnight/flask_ishuhui | be42684a4cf461aaccd691fc61548450869abc17 | [
"MIT"
] | null | null | null | ishuhui/__init__.py | lawnight/flask_ishuhui | be42684a4cf461aaccd691fc61548450869abc17 | [
"MIT"
] | null | null | null | ishuhui/__init__.py | lawnight/flask_ishuhui | be42684a4cf461aaccd691fc61548450869abc17 | [
"MIT"
] | 1 | 2021-05-20T10:19:19.000Z | 2021-05-20T10:19:19.000Z | from flask import Flask
from . import csrf
import ishuhui.data as data
import env
from flask_assets import Environment, Bundle
def create_app(config, should_register_blueprints=True):
app = Flask(__name__,static_folder = env.ASSETS,static_url_path='/assets')
assets = Environment(app)
js = Bundle('app.js','style.css')
assets.register('assets',js)
app.config.from_object(config)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
from ishuhui.extensions.loginmanger import login_manager
from ishuhui.extensions.flasksqlalchemy import db
login_manager.setup_app(app)
db.init_app(app)
csrf.init(app)
from ishuhui.logger import init_logger
init_logger(app)
if should_register_blueprints:
register_blueprints(app)
with app.app_context():
db.create_all()
fake_db()
return app
def fake_db():
from ishuhui.extensions.flasksqlalchemy import db
data.Comic.query.delete()
for item in env.COMICS:
comic = data.Comic()
comic.title = item['title']
comic.description = item['description']
comic.classify_id = item['classify_id']
db.session.add(comic)
db.session.commit()
def register_blueprints(app):
from ishuhui.controllers.comic import bp_comic
app.register_blueprint(bp_comic)
from ishuhui.controllers.admin import bp_admin
app.register_blueprint(bp_admin)
from ishuhui.controllers.auth import bp_auth
app.register_blueprint(bp_auth)
from ishuhui.controllers.error import bp_error
app.register_blueprint(bp_error)
| 26.016129 | 78 | 0.716677 | from flask import Flask
from . import csrf
import ishuhui.data as data
import env
from flask_assets import Environment, Bundle
def create_app(config, should_register_blueprints=True):
app = Flask(__name__,static_folder = env.ASSETS,static_url_path='/assets')
assets = Environment(app)
js = Bundle('app.js','style.css')
assets.register('assets',js)
app.config.from_object(config)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
from ishuhui.extensions.loginmanger import login_manager
from ishuhui.extensions.flasksqlalchemy import db
login_manager.setup_app(app)
db.init_app(app)
csrf.init(app)
from ishuhui.logger import init_logger
init_logger(app)
if should_register_blueprints:
register_blueprints(app)
with app.app_context():
db.create_all()
fake_db()
return app
def fake_db():
from ishuhui.extensions.flasksqlalchemy import db
data.Comic.query.delete()
for item in env.COMICS:
comic = data.Comic()
comic.title = item['title']
comic.description = item['description']
comic.classify_id = item['classify_id']
db.session.add(comic)
db.session.commit()
def register_blueprints(app):
from ishuhui.controllers.comic import bp_comic
app.register_blueprint(bp_comic)
from ishuhui.controllers.admin import bp_admin
app.register_blueprint(bp_admin)
from ishuhui.controllers.auth import bp_auth
app.register_blueprint(bp_auth)
from ishuhui.controllers.error import bp_error
app.register_blueprint(bp_error)
| true | true |
f71b8422d45790abd3999a3b0b1534cd72a75c0b | 19,515 | py | Python | prody/chromatin/hic.py | grandevelia/ProDy | 7c725640a94c16543423c0756388998cb86a97ae | [
"MIT"
] | 210 | 2015-01-26T08:17:56.000Z | 2022-03-30T01:40:34.000Z | prody/chromatin/hic.py | grandevelia/ProDy | 7c725640a94c16543423c0756388998cb86a97ae | [
"MIT"
] | 555 | 2015-01-05T21:51:54.000Z | 2022-03-31T16:51:41.000Z | prody/chromatin/hic.py | grandevelia/ProDy | 7c725640a94c16543423c0756388998cb86a97ae | [
"MIT"
] | 99 | 2015-02-09T18:00:39.000Z | 2022-03-07T12:52:51.000Z | from numbers import Integral
from numpy import ma
import numpy as np
from scipy.sparse import coo_matrix
from scipy.stats import mode
from prody.chromatin.norm import VCnorm, SQRTVCnorm, Filenorm
from prody.chromatin.functions import div0, showDomains, _getEigvecs
from prody import PY2K
from prody.dynamics import GNM, MaskedGNM
from prody.dynamics.functions import writeArray
from prody.dynamics.mode import Mode
from prody.dynamics.modeset import ModeSet
from prody.utilities import openFile, importLA, showMatrix, isURL, fixArraySize, makeSymmetric
__all__ = ['HiC', 'parseHiC', 'parseHiCStream', 'parseHiCBinary', 'saveHiC', 'loadHiC', 'writeMap']
class HiC(object):
"""This class is used to store and preprocess Hi-C contact map. A :class:`.GNM`
instance for analyzing the contact map can be also created by using this class.
"""
def __init__(self, title='Unknown', map=None, bin=None):
self._title = title
self._map = None
self.mask = False
self._labels = 0
self.masked = True
self.bin = bin
self.map = map
@property
def map(self):
if self.masked:
return self.getTrimedMap()
else:
return self._map
@map.setter
def map(self, value):
if value is None:
self._map = None
else:
self._map = np.asarray(value)
self._map = makeSymmetric(self._map)
self._maskUnmappedRegions()
self._labels = np.zeros(len(self._map), dtype=int)
def __repr__(self):
mask = self.mask
if np.isscalar(mask):
return '<HiC: {0} ({1} loci)>'.format(self._title, len(self._map))
else:
return '<HiC: {0} ({1} mapped loci; {2} in total)>'.format(self._title, np.count_nonzero(mask), len(self._map))
def __str__(self):
return 'HiC ' + self._title
def __getitem__(self, index):
if isinstance(index, Integral):
return self.map.flatten()[index]
else:
i, j = index
return self.map[i,j]
def __len__(self):
mask = self.mask
if np.isscalar(mask):
return len(self._map)
else:
return np.count_nonzero(mask)
def numAtoms(self):
return len(self.map)
def getTitle(self):
"""Returns title of the instance."""
return self._title
def setTitle(self, title):
"""Sets title of the instance."""
self._title = str(title)
def getCompleteMap(self):
"""Obtains the complete contact map with unmapped regions."""
return self._map
def getTrimedMap(self):
"""Obtains the contact map without unmapped regions."""
if self._map is None:
return None
if np.isscalar(self.mask):
return self._map
M = ma.array(self._map)
M.mask = np.diag(~self.mask)
return ma.compress_rowcols(M)
def align(self, array, axis=None):
if not isinstance(array, np.ndarray):
array = np.array(array)
ret = array = array.copy()
if np.isscalar(self.mask):
return ret
mask = self.mask.copy()
l_full = self.getCompleteMap().shape[0]
l_trim = self.getTrimedMap().shape[0]
if len(array.shape) == 0:
raise ValueError('array cannot be empty')
elif len(array.shape) == 1:
l = array.shape[0]
if l == l_trim:
N = len(mask)
ret = np.zeros(N, dtype=array.dtype)
ret[mask] = array
elif l == l_full:
ret = array[mask]
else:
raise ValueError('The length of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(l, l_full, l_trim))
elif len(array.shape) == 2:
s = array.shape
if axis is None:
if s[0] != s[1]:
raise ValueError('The array must be a square matrix '
'if axis is set to None.')
if s[0] == l_trim:
N = len(mask)
whole_mat = np.zeros((N,N), dtype=array.dtype)
mask = np.outer(mask, mask)
whole_mat[mask] = array.flatten()
ret = whole_mat
elif s[0] == l_full:
M = ma.array(array)
M.mask = np.diag(mask)
ret = ma.compress_rowcols(M)
else:
raise ValueError('The size of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(s[0], l_full, l_trim))
else:
new_shape = list(s)
otheraxis = 0 if axis!=0 else 1
if s[axis] == l_trim:
N = len(mask)
new_shape[axis] = N
whole_mat = np.zeros(new_shape)
mask = np.expand_dims(mask, axis=otheraxis)
mask = mask.repeat(s[otheraxis], axis=otheraxis)
whole_mat[mask] = array.flatten()
ret = whole_mat
elif s[axis] == l_full:
mask = np.expand_dims(mask, axis=otheraxis)
mask = mask.repeat(s[otheraxis])
ret = self._map[mask]
else:
raise ValueError('The size of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(s[0], l_full, l_trim))
return ret
def getKirchhoff(self):
"""Builds a Kirchhoff matrix based on the contact map."""
if self._map is None:
return None
else:
M = self.map
I = np.eye(M.shape[0], dtype=bool)
A = M.copy()
A[I] = 0.
D = np.diag(np.sum(A, axis=0))
K = D - A
return K
def _maskUnmappedRegions(self, diag=False):
"""Finds and masks unmapped regions in the contact map."""
M = self._map
if M is None: return
if diag:
# Obtain the diagonal values, need to make sure d is an array
# instead of a matrix, otherwise diag() later will not work as
# intended.
d = np.array(np.diag(M))
else:
d = np.array(M.sum(0))
# mask if a diagonal value is zero
mask_zero = np.array(d==0)
# mask if a diagonal value is NAN
mask_nan = np.isnan(d)
# combine two masks
mask = np.logical_or(mask_nan, mask_zero)
self.mask = ~mask
return self.mask
def calcGNM(self, n_modes=None, **kwargs):
"""Calculates GNM on the current Hi-C map. By default, ``n_modes`` is
set to **None** and ``zeros`` to **True**."""
if 'zeros' not in kwargs:
kwargs['zeros'] = True
if self.masked:
gnm = MaskedGNM(self._title, self.mask)
else:
gnm = GNM(self._title)
gnm.setKirchhoff(self.getKirchhoff())
gnm.calcModes(n_modes=n_modes, **kwargs)
return gnm
def normalize(self, method=VCnorm, **kwargs):
"""Applies chosen normalization on the current Hi-C map."""
M = self._map
N = method(M, **kwargs)
self.map = N
return N
def setDomains(self, labels, **kwargs):
"""Uses spectral clustering to identify structural domains on the chromosome.
:arg labels: domain labels
:type labels: :class:`~numpy.ndarray`, list
:arg method: Label assignment algorithm used after Laplacian embedding.
:type method: func
"""
wastrimmed = self.masked
self.masked = True
if len(labels) == self.numAtoms():
full_length = self.numAtoms()
if full_length != len(labels):
_labels = np.empty(full_length)
_labels.fill(np.nan)
_labels[self.mask] = labels
currlbl = labels[0]
for i in range(len(_labels)):
l = _labels[i]
if np.isnan(l):
_labels[i] = currlbl
elif currlbl != l:
currlbl = l
labels = _labels
else:
self.masked = False
if len(labels) != self.numAtoms():
raise ValueError('The length of the labels should match either the length '
'of masked or complete Hi-C map. Turn off "masked" if '
'you intended to set the labels to the full map.')
self.masked = wastrimmed
self._labels = labels
return self.getDomains()
def getDomains(self):
"""Returns an 1D :class:`numpy.ndarray` whose length is the number of loci. Each
element is an index denotes to which domain the locus belongs."""
lbl = self._labels
mask = self.mask
if self.masked:
lbl = lbl[mask]
return lbl
def getDomainList(self):
"""Returns a list of domain separations. The list has two columns: the first is for
the domain starts and the second is for the domain ends."""
indicators = np.diff(self.getDomains())
indicators = np.append(1., indicators)
indicators[-1] = 1
sites = np.where(indicators != 0)[0]
starts = sites[:-1]
ends = sites[1:]
domains = np.array([starts, ends]).T
return domains
def view(self, spec='p', **kwargs):
"""Visualization of the Hi-C map and domains (if present). The function makes use
of :func:`.showMatrix`.
:arg spec: a string specifies how to preprocess the matrix. Blank for no preprocessing,
'p' for showing only data from *p*-th to *100-p*-th percentile. '_' is to suppress
creating a new figure and paint to the current one instead. The letter specifications
can be applied sequentially, e.g. 'p_'.
:type spec: str
:arg p: specifies the percentile threshold.
:type p: double
"""
dm_kwargs = {}
keys = list(kwargs.keys())
for k in keys:
if k.startswith('dm_'):
dm_kwargs[k[3:]] = kwargs.pop(k)
elif k.startswith('domain_'):
dm_kwargs[k[7:]] = kwargs.pop(k)
M = self.map
if 'p' in spec:
p = kwargs.pop('p', 5)
lp = kwargs.pop('lp', p)
hp = kwargs.pop('hp', 100-p)
vmin = np.percentile(M, lp)
vmax = np.percentile(M, hp)
else:
vmin = vmax = None
if not 'vmin' in kwargs:
kwargs['vmin'] = vmin
if not 'vmax' in kwargs:
kwargs['vmax'] = vmax
im = showMatrix(M, **kwargs)
domains = self.getDomainList()
if len(domains) > 1:
showDomains(domains, **dm_kwargs)
return im
def copy(self):
new = type(self)()
new.__dict__.update(self.__dict__)
return new
__copy__ = copy
def parseHiC(filename, **kwargs):
"""Returns an :class:`.HiC` from a Hi-C data file.
This function extends :func:`.parseHiCStream`.
:arg filename: the filename to the Hi-C data file.
:type filename: str
"""
import os, struct
title = kwargs.get('title')
if title is None:
title = os.path.basename(filename)
else:
title = kwargs.pop('title')
if isURL(filename):
M, res = parseHiCBinary(filename, title=title, **kwargs)
else:
with open(filename,'rb') as req:
magic_number = struct.unpack('<3s',req.read(3))[0]
if magic_number == b"HIC":
M, res = parseHiCBinary(filename, title=title, **kwargs)
else:
with open(filename, 'r') as filestream:
M, res = parseHiCStream(filestream, title=title, **kwargs)
hic = HiC(title=title, map=M, bin=res)
return hic
def _sparse2dense(I, J, values, bin=None):
I = np.asarray(I, dtype=int)
J = np.asarray(J, dtype=int)
values = np.asarray(values, dtype=float)
# determine the bin size by the most frequent interval
if bin is None:
loci = np.unique(np.sort(I))
bins = np.diff(loci)
bin = mode(bins)[0][0]
# convert coordinate from basepair to locus index
bin = int(bin)
I = I // bin
J = J // bin
# make sure that the matrix is square
# if np.max(I) != np.max(J):
# b = np.max(np.append(I, J))
# I = np.append(I, b)
# J = np.append(J, b)
# values = np.append(values, 0.)
# Convert to sparse matrix format, then full matrix format
# and finally array type. Matrix format is avoided because
# diag() won't work as intended for Matrix instances.
M = np.array(coo_matrix((values, (I, J))).todense())
return M, bin
def parseHiCStream(stream, **kwargs):
"""Returns an :class:`.HiC` from a stream of Hi-C data lines.
:arg stream: Anything that implements the method ``read``, ``seek``
(e.g. :class:`file`, buffer, stdin)
"""
issparse = kwargs.get('sparse', None)
import csv
dialect = csv.Sniffer().sniff(stream.read(1024))
stream.seek(0)
reader = csv.reader(stream, dialect)
D = list()
for row in reader:
d = list()
for element in row:
d.append(np.double(element))
D.append(d)
D = np.array(D)
res = kwargs.get('bin', None)
if res is not None:
res = int(res)
size = D.shape
if len(D.shape) <= 1:
raise ValueError("cannot parse the file: input file only contains one column.")
if issparse is None:
issparse = size[1] == 3
if not issparse:
M = D
else:
try:
I, J, values = D.T[:3]
except ValueError:
raise ValueError('the sparse matrix format should have three columns')
M, res = _sparse2dense(I, J, values, bin=res)
return M, res
def parseHiCBinary(filename, **kwargs):
chrloc = kwargs.get('chrom', None)
if chrloc is None:
raise ValueError('chrom needs to be specified when parsing .hic format')
chrloc1 = kwargs.get('chrom1', chrloc)
chrloc2 = kwargs.get('chrom2', chrloc)
norm = kwargs.get('norm', 'NONE')
unit = kwargs.get('unit', 'BP')
res = kwargs.get('binsize', None)
res = kwargs.get('bin', res)
if res is None:
raise ValueError('bin needs to be specified when parsing .hic format')
res = int(res)
from .straw import straw
result = straw(norm, filename, chrloc1, chrloc2, unit, res)
M, res = _sparse2dense(*result, bin=res)
return M, res
def writeMap(filename, map, bin=None, format='%f'):
"""Writes *map* to the file designated by *filename*.
:arg filename: the file to be written.
:type filename: str
:arg map: a Hi-C contact map.
:type map: :class:`numpy.ndarray`
:arg bin: bin size of the *map*. If bin is `None`, *map* will be
written in full matrix format.
:type bin: int
:arg format: output format for map elements.
:type format: str
"""
assert isinstance(map, np.ndarray), 'map must be a numpy.ndarray.'
if bin is None:
return writeArray(filename, map, format=format)
else:
L = int(map.size - np.diag(map).size)//2 + np.diag(map).size
spmat = np.zeros((L, 3))
m,n = map.shape
l = 0
for i in range(m):
for j in range(i,n):
spmat[l, 0] = i * bin
spmat[l, 1] = j * bin
spmat[l, 2] = map[i, j]
l += 1
fmt = ['%d', '%d', format]
return writeArray(filename, spmat, format=fmt)
def saveHiC(hic, filename=None, map=True, **kwargs):
"""Saves *HiC* model data as :file:`filename.hic.npz`. If *map* is **True**,
Hi-C contact map will not be saved and it can be loaded from raw data file
later. If *filename* is **None**, name of the Hi-C instance will be used as
the filename, after ``" "`` (white spaces) in the name are replaced with
``"_"`` (underscores). Upon successful completion of saving, filename is
returned. This function makes use of :func:`numpy.savez` function."""
assert isinstance(hic, HiC), 'hic must be a HiC instance.'
if filename is None:
filename = hic.getTitle().replace(' ', '_')
if filename.endswith('.hic'):
filename += '.npz'
elif not filename.endswith('.hic.npz'):
filename += '.hic.npz'
attr_dict = hic.__dict__.copy()
if not map:
attr_dict.pop('_map')
ostream = openFile(filename, 'wb', **kwargs)
np.savez_compressed(ostream, **attr_dict)
ostream.close()
return filename
def loadHiC(filename):
"""Returns HiC instance after loading it from file (*filename*).
This function makes use of :func:`numpy.load` function. See also
:func:`saveHiC`."""
attr_dict = np.load(filename)
hic = HiC()
keys = attr_dict.keys()
for k in keys:
val = attr_dict[k]
if len(val.shape) == 0:
val = np.asscalar(val)
setattr(hic, k, val)
return hic
def saveHiC_h5(hic, filename=None, **kwargs):
"""Saves *HiC* model data as :file:`filename.hic.npz`. If *filename* is
**None**, name of the Hi-C instance will be used as
the filename, after ``" "`` (white spaces) in the name are replaced with
``"_"`` (underscores). Upon successful completion of saving, filename is
returned. This function makes use of :func:`numpy.savez` function."""
try:
import h5py
except:
raise ImportError('h5py needs to be installed for using this function')
assert isinstance(hic, HiC), 'hic must be a HiC instance.'
if filename is None:
filename = hic.getTitle().replace(' ', '_')
if filename.endswith('.hic'):
filename += '.hic'
elif not filename.endswith('.hic.h5'):
filename += '.hic.h5'
attr_dict = hic.__dict__.copy()
with h5py.File(filename, 'w') as f:
for key in attr_dict:
value = attr_dict[key]
compression = None if np.isscalar(value) else 'gzip'
f.create_dataset(key, data=value, compression=compression)
return filename
def loadHiC_h5(filename):
"""Returns HiC instance after loading it from file (*filename*).
This function makes use of :func:`numpy.load` function. See also
:func:`saveHiC`."""
try:
import h5py
except:
raise ImportError('h5py needs to be installed for using this function')
hic = HiC()
with h5py.File(filename, 'r') as f:
for key in f.keys():
try:
value = f[key][:]
except:
value = f[key][()]
setattr(hic, key, value)
return hic
| 31.887255 | 123 | 0.544146 | from numbers import Integral
from numpy import ma
import numpy as np
from scipy.sparse import coo_matrix
from scipy.stats import mode
from prody.chromatin.norm import VCnorm, SQRTVCnorm, Filenorm
from prody.chromatin.functions import div0, showDomains, _getEigvecs
from prody import PY2K
from prody.dynamics import GNM, MaskedGNM
from prody.dynamics.functions import writeArray
from prody.dynamics.mode import Mode
from prody.dynamics.modeset import ModeSet
from prody.utilities import openFile, importLA, showMatrix, isURL, fixArraySize, makeSymmetric
__all__ = ['HiC', 'parseHiC', 'parseHiCStream', 'parseHiCBinary', 'saveHiC', 'loadHiC', 'writeMap']
class HiC(object):
def __init__(self, title='Unknown', map=None, bin=None):
self._title = title
self._map = None
self.mask = False
self._labels = 0
self.masked = True
self.bin = bin
self.map = map
@property
def map(self):
if self.masked:
return self.getTrimedMap()
else:
return self._map
@map.setter
def map(self, value):
if value is None:
self._map = None
else:
self._map = np.asarray(value)
self._map = makeSymmetric(self._map)
self._maskUnmappedRegions()
self._labels = np.zeros(len(self._map), dtype=int)
def __repr__(self):
mask = self.mask
if np.isscalar(mask):
return '<HiC: {0} ({1} loci)>'.format(self._title, len(self._map))
else:
return '<HiC: {0} ({1} mapped loci; {2} in total)>'.format(self._title, np.count_nonzero(mask), len(self._map))
def __str__(self):
return 'HiC ' + self._title
def __getitem__(self, index):
if isinstance(index, Integral):
return self.map.flatten()[index]
else:
i, j = index
return self.map[i,j]
def __len__(self):
mask = self.mask
if np.isscalar(mask):
return len(self._map)
else:
return np.count_nonzero(mask)
def numAtoms(self):
return len(self.map)
def getTitle(self):
return self._title
def setTitle(self, title):
self._title = str(title)
def getCompleteMap(self):
return self._map
def getTrimedMap(self):
if self._map is None:
return None
if np.isscalar(self.mask):
return self._map
M = ma.array(self._map)
M.mask = np.diag(~self.mask)
return ma.compress_rowcols(M)
def align(self, array, axis=None):
if not isinstance(array, np.ndarray):
array = np.array(array)
ret = array = array.copy()
if np.isscalar(self.mask):
return ret
mask = self.mask.copy()
l_full = self.getCompleteMap().shape[0]
l_trim = self.getTrimedMap().shape[0]
if len(array.shape) == 0:
raise ValueError('array cannot be empty')
elif len(array.shape) == 1:
l = array.shape[0]
if l == l_trim:
N = len(mask)
ret = np.zeros(N, dtype=array.dtype)
ret[mask] = array
elif l == l_full:
ret = array[mask]
else:
raise ValueError('The length of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(l, l_full, l_trim))
elif len(array.shape) == 2:
s = array.shape
if axis is None:
if s[0] != s[1]:
raise ValueError('The array must be a square matrix '
'if axis is set to None.')
if s[0] == l_trim:
N = len(mask)
whole_mat = np.zeros((N,N), dtype=array.dtype)
mask = np.outer(mask, mask)
whole_mat[mask] = array.flatten()
ret = whole_mat
elif s[0] == l_full:
M = ma.array(array)
M.mask = np.diag(mask)
ret = ma.compress_rowcols(M)
else:
raise ValueError('The size of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(s[0], l_full, l_trim))
else:
new_shape = list(s)
otheraxis = 0 if axis!=0 else 1
if s[axis] == l_trim:
N = len(mask)
new_shape[axis] = N
whole_mat = np.zeros(new_shape)
mask = np.expand_dims(mask, axis=otheraxis)
mask = mask.repeat(s[otheraxis], axis=otheraxis)
whole_mat[mask] = array.flatten()
ret = whole_mat
elif s[axis] == l_full:
mask = np.expand_dims(mask, axis=otheraxis)
mask = mask.repeat(s[otheraxis])
ret = self._map[mask]
else:
raise ValueError('The size of array (%d) does not '
'match that of either the full (%d) '
'or trimed (%d).'
%(s[0], l_full, l_trim))
return ret
def getKirchhoff(self):
if self._map is None:
return None
else:
M = self.map
I = np.eye(M.shape[0], dtype=bool)
A = M.copy()
A[I] = 0.
D = np.diag(np.sum(A, axis=0))
K = D - A
return K
def _maskUnmappedRegions(self, diag=False):
M = self._map
if M is None: return
if diag:
d = np.array(np.diag(M))
else:
d = np.array(M.sum(0))
mask_zero = np.array(d==0)
mask_nan = np.isnan(d)
mask = np.logical_or(mask_nan, mask_zero)
self.mask = ~mask
return self.mask
def calcGNM(self, n_modes=None, **kwargs):
if 'zeros' not in kwargs:
kwargs['zeros'] = True
if self.masked:
gnm = MaskedGNM(self._title, self.mask)
else:
gnm = GNM(self._title)
gnm.setKirchhoff(self.getKirchhoff())
gnm.calcModes(n_modes=n_modes, **kwargs)
return gnm
def normalize(self, method=VCnorm, **kwargs):
M = self._map
N = method(M, **kwargs)
self.map = N
return N
def setDomains(self, labels, **kwargs):
wastrimmed = self.masked
self.masked = True
if len(labels) == self.numAtoms():
full_length = self.numAtoms()
if full_length != len(labels):
_labels = np.empty(full_length)
_labels.fill(np.nan)
_labels[self.mask] = labels
currlbl = labels[0]
for i in range(len(_labels)):
l = _labels[i]
if np.isnan(l):
_labels[i] = currlbl
elif currlbl != l:
currlbl = l
labels = _labels
else:
self.masked = False
if len(labels) != self.numAtoms():
raise ValueError('The length of the labels should match either the length '
'of masked or complete Hi-C map. Turn off "masked" if '
'you intended to set the labels to the full map.')
self.masked = wastrimmed
self._labels = labels
return self.getDomains()
def getDomains(self):
lbl = self._labels
mask = self.mask
if self.masked:
lbl = lbl[mask]
return lbl
def getDomainList(self):
indicators = np.diff(self.getDomains())
indicators = np.append(1., indicators)
indicators[-1] = 1
sites = np.where(indicators != 0)[0]
starts = sites[:-1]
ends = sites[1:]
domains = np.array([starts, ends]).T
return domains
def view(self, spec='p', **kwargs):
dm_kwargs = {}
keys = list(kwargs.keys())
for k in keys:
if k.startswith('dm_'):
dm_kwargs[k[3:]] = kwargs.pop(k)
elif k.startswith('domain_'):
dm_kwargs[k[7:]] = kwargs.pop(k)
M = self.map
if 'p' in spec:
p = kwargs.pop('p', 5)
lp = kwargs.pop('lp', p)
hp = kwargs.pop('hp', 100-p)
vmin = np.percentile(M, lp)
vmax = np.percentile(M, hp)
else:
vmin = vmax = None
if not 'vmin' in kwargs:
kwargs['vmin'] = vmin
if not 'vmax' in kwargs:
kwargs['vmax'] = vmax
im = showMatrix(M, **kwargs)
domains = self.getDomainList()
if len(domains) > 1:
showDomains(domains, **dm_kwargs)
return im
def copy(self):
new = type(self)()
new.__dict__.update(self.__dict__)
return new
__copy__ = copy
def parseHiC(filename, **kwargs):
import os, struct
title = kwargs.get('title')
if title is None:
title = os.path.basename(filename)
else:
title = kwargs.pop('title')
if isURL(filename):
M, res = parseHiCBinary(filename, title=title, **kwargs)
else:
with open(filename,'rb') as req:
magic_number = struct.unpack('<3s',req.read(3))[0]
if magic_number == b"HIC":
M, res = parseHiCBinary(filename, title=title, **kwargs)
else:
with open(filename, 'r') as filestream:
M, res = parseHiCStream(filestream, title=title, **kwargs)
hic = HiC(title=title, map=M, bin=res)
return hic
def _sparse2dense(I, J, values, bin=None):
I = np.asarray(I, dtype=int)
J = np.asarray(J, dtype=int)
values = np.asarray(values, dtype=float)
if bin is None:
loci = np.unique(np.sort(I))
bins = np.diff(loci)
bin = mode(bins)[0][0]
bin = int(bin)
I = I // bin
J = J // bin
M = np.array(coo_matrix((values, (I, J))).todense())
return M, bin
def parseHiCStream(stream, **kwargs):
issparse = kwargs.get('sparse', None)
import csv
dialect = csv.Sniffer().sniff(stream.read(1024))
stream.seek(0)
reader = csv.reader(stream, dialect)
D = list()
for row in reader:
d = list()
for element in row:
d.append(np.double(element))
D.append(d)
D = np.array(D)
res = kwargs.get('bin', None)
if res is not None:
res = int(res)
size = D.shape
if len(D.shape) <= 1:
raise ValueError("cannot parse the file: input file only contains one column.")
if issparse is None:
issparse = size[1] == 3
if not issparse:
M = D
else:
try:
I, J, values = D.T[:3]
except ValueError:
raise ValueError('the sparse matrix format should have three columns')
M, res = _sparse2dense(I, J, values, bin=res)
return M, res
def parseHiCBinary(filename, **kwargs):
chrloc = kwargs.get('chrom', None)
if chrloc is None:
raise ValueError('chrom needs to be specified when parsing .hic format')
chrloc1 = kwargs.get('chrom1', chrloc)
chrloc2 = kwargs.get('chrom2', chrloc)
norm = kwargs.get('norm', 'NONE')
unit = kwargs.get('unit', 'BP')
res = kwargs.get('binsize', None)
res = kwargs.get('bin', res)
if res is None:
raise ValueError('bin needs to be specified when parsing .hic format')
res = int(res)
from .straw import straw
result = straw(norm, filename, chrloc1, chrloc2, unit, res)
M, res = _sparse2dense(*result, bin=res)
return M, res
def writeMap(filename, map, bin=None, format='%f'):
assert isinstance(map, np.ndarray), 'map must be a numpy.ndarray.'
if bin is None:
return writeArray(filename, map, format=format)
else:
L = int(map.size - np.diag(map).size)//2 + np.diag(map).size
spmat = np.zeros((L, 3))
m,n = map.shape
l = 0
for i in range(m):
for j in range(i,n):
spmat[l, 0] = i * bin
spmat[l, 1] = j * bin
spmat[l, 2] = map[i, j]
l += 1
fmt = ['%d', '%d', format]
return writeArray(filename, spmat, format=fmt)
def saveHiC(hic, filename=None, map=True, **kwargs):
assert isinstance(hic, HiC), 'hic must be a HiC instance.'
if filename is None:
filename = hic.getTitle().replace(' ', '_')
if filename.endswith('.hic'):
filename += '.npz'
elif not filename.endswith('.hic.npz'):
filename += '.hic.npz'
attr_dict = hic.__dict__.copy()
if not map:
attr_dict.pop('_map')
ostream = openFile(filename, 'wb', **kwargs)
np.savez_compressed(ostream, **attr_dict)
ostream.close()
return filename
def loadHiC(filename):
attr_dict = np.load(filename)
hic = HiC()
keys = attr_dict.keys()
for k in keys:
val = attr_dict[k]
if len(val.shape) == 0:
val = np.asscalar(val)
setattr(hic, k, val)
return hic
def saveHiC_h5(hic, filename=None, **kwargs):
try:
import h5py
except:
raise ImportError('h5py needs to be installed for using this function')
assert isinstance(hic, HiC), 'hic must be a HiC instance.'
if filename is None:
filename = hic.getTitle().replace(' ', '_')
if filename.endswith('.hic'):
filename += '.hic'
elif not filename.endswith('.hic.h5'):
filename += '.hic.h5'
attr_dict = hic.__dict__.copy()
with h5py.File(filename, 'w') as f:
for key in attr_dict:
value = attr_dict[key]
compression = None if np.isscalar(value) else 'gzip'
f.create_dataset(key, data=value, compression=compression)
return filename
def loadHiC_h5(filename):
try:
import h5py
except:
raise ImportError('h5py needs to be installed for using this function')
hic = HiC()
with h5py.File(filename, 'r') as f:
for key in f.keys():
try:
value = f[key][:]
except:
value = f[key][()]
setattr(hic, key, value)
return hic
| true | true |
f71b8454f0e6b786481174f05b105f50d177f810 | 568 | py | Python | tools/leetcode.125.Valid Palindrome/leetcode.125.Valid Palindrome.submission1.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | 4 | 2015-10-10T00:30:55.000Z | 2020-07-27T19:45:54.000Z | tools/leetcode.125.Valid Palindrome/leetcode.125.Valid Palindrome.submission1.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | null | null | null | tools/leetcode.125.Valid Palindrome/leetcode.125.Valid Palindrome.submission1.py | tedye/leetcode | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | [
"MIT"
] | null | null | null | class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if not s:
return True
start = 0
end = len(s)-1
s = s.lower()
while start < end:
while start < end and not s[start].isalnum():
start += 1
while start < end and not s[end].isalnum():
end -= 1
if s[start] == s[end]:
start += 1
end -= 1
else:
return False
return True | 568 | 568 | 0.399648 | class Solution:
| true | true |
f71b84b71246068431940b564be47b7c900c6b87 | 3,164 | py | Python | gamestonk_terminal/common/quantitative_analysis/rolling_model.py | minhhoang1023/GamestonkTerminal | 195dc19b491052df080178c0cc6a9d535a91a704 | [
"MIT"
] | 1 | 2022-03-15T13:05:40.000Z | 2022-03-15T13:05:40.000Z | gamestonk_terminal/common/quantitative_analysis/rolling_model.py | minhhoang1023/GamestonkTerminal | 195dc19b491052df080178c0cc6a9d535a91a704 | [
"MIT"
] | null | null | null | gamestonk_terminal/common/quantitative_analysis/rolling_model.py | minhhoang1023/GamestonkTerminal | 195dc19b491052df080178c0cc6a9d535a91a704 | [
"MIT"
] | null | null | null | """Rolling Statistics"""
__docformat__ = "numpy"
import logging
from typing import Tuple
import pandas as pd
import pandas_ta as ta
from gamestonk_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def get_rolling_avg(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Return rolling mean and standard deviation
Parameters
----------
df_stock : pd.DataFrame
Dataframe of target data
length : int
Length of rolling window
Returns
-------
pd.DataFrame :
Dataframe of rolling mean
pd.DataFrame :
Dataframe of rolling standard deviation
"""
rolling_mean = df.rolling(length, center=True, min_periods=1).mean()
rolling_std = df.rolling(length, center=True, min_periods=1).std()
return pd.DataFrame(rolling_mean), pd.DataFrame(rolling_std)
@log_start_end(log=logger)
def get_spread(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Standard Deviation and Variance
Parameters
----------
df_stock : pd.DataFrame
DataFrame of targeted data
Returns
-------
df_sd : pd.DataFrame
Dataframe of rolling standard deviation
df_var : pd.DataFrame
Dataframe of rolling standard deviation
"""
df_sd = ta.stdev(
close=df,
length=length,
).dropna()
df_var = ta.variance(
close=df,
length=length,
).dropna()
return pd.DataFrame(df_sd), pd.DataFrame(df_var)
@log_start_end(log=logger)
def get_quantile(
df: pd.DataFrame, length: int, quantile_pct: float
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Overlay Median & Quantile
Parameters
----------
df : pd.DataFrame
Dataframe of targeted data
length : int
Length of window
quantile : float
Quantile to display
Returns
-------
df_med : pd.DataFrame
Dataframe of median prices over window
df_quantile : pd.DataFrame
Dataframe of gievn quantile prices over window
"""
df_med = ta.median(close=df, length=length).dropna()
df_quantile = ta.quantile(
df,
length=length,
q=quantile_pct,
).dropna()
return pd.DataFrame(df_med), pd.DataFrame(df_quantile)
@log_start_end(log=logger)
def get_skew(df: pd.DataFrame, length: int) -> pd.DataFrame:
"""Skewness Indicator
Parameters
----------
df_stock : pd.DataFrame
Dataframe of targeted data
length : int
Length of window
Returns
-------
df_skew : pd.DataFrame
Dataframe of rolling skew
"""
df_skew = ta.skew(close=df, length=length).dropna()
return df_skew
@log_start_end(log=logger)
def get_kurtosis(df: pd.DataFrame, length: int) -> pd.DataFrame:
"""Kurtosis Indicator
Parameters
----------
df_stock : pd.DataFrame
Dataframe of targeted data
length : int
Length of window
Returns
-------
df_kurt : pd.DataFrame
Dataframe of rolling kurtosis
"""
df_kurt = ta.kurtosis(close=df, length=length).dropna()
return df_kurt
| 23.094891 | 88 | 0.640645 | __docformat__ = "numpy"
import logging
from typing import Tuple
import pandas as pd
import pandas_ta as ta
from gamestonk_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def get_rolling_avg(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
rolling_mean = df.rolling(length, center=True, min_periods=1).mean()
rolling_std = df.rolling(length, center=True, min_periods=1).std()
return pd.DataFrame(rolling_mean), pd.DataFrame(rolling_std)
@log_start_end(log=logger)
def get_spread(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
df_sd = ta.stdev(
close=df,
length=length,
).dropna()
df_var = ta.variance(
close=df,
length=length,
).dropna()
return pd.DataFrame(df_sd), pd.DataFrame(df_var)
@log_start_end(log=logger)
def get_quantile(
df: pd.DataFrame, length: int, quantile_pct: float
) -> Tuple[pd.DataFrame, pd.DataFrame]:
df_med = ta.median(close=df, length=length).dropna()
df_quantile = ta.quantile(
df,
length=length,
q=quantile_pct,
).dropna()
return pd.DataFrame(df_med), pd.DataFrame(df_quantile)
@log_start_end(log=logger)
def get_skew(df: pd.DataFrame, length: int) -> pd.DataFrame:
df_skew = ta.skew(close=df, length=length).dropna()
return df_skew
@log_start_end(log=logger)
def get_kurtosis(df: pd.DataFrame, length: int) -> pd.DataFrame:
df_kurt = ta.kurtosis(close=df, length=length).dropna()
return df_kurt
| true | true |
f71b8506b37bb0252f9682c2fbba2ee5c82cb403 | 729 | py | Python | utils/see.py | jack09581013/Dual-GDNet | d9d65928208caee781cbe8f8f794241d06b4bf5d | [
"MIT"
] | null | null | null | utils/see.py | jack09581013/Dual-GDNet | d9d65928208caee781cbe8f8f794241d06b4bf5d | [
"MIT"
] | null | null | null | utils/see.py | jack09581013/Dual-GDNet | d9d65928208caee781cbe8f8f794241d06b4bf5d | [
"MIT"
] | null | null | null | import tools
import os
from dataset import RandomCropper, sub_sampling
from utils import plot_flying_things3D
height = 240
width = 576
ratio = 1
height = height//ratio
width = width//ratio
train_files = os.listdir('/media/jack/data/Dataset/pytorch/flyingthings3d/TRAIN')
test_files = os.listdir('/media/jack/data/Dataset/pytorch/flyingthings3d/TEST')
print('number of train files:', len(train_files))
print('number of test files:', len(test_files))
# (540, 960)
X, Y = tools.load('/media/jack/data/Dataset/pytorch/flyingthings3d/TRAIN/data_00000.np')
X, Y = sub_sampling(X, Y, ratio)
cropper = RandomCropper(X.shape[1:3], (height, width), seed=0)
X, Y = cropper.crop(X), cropper.crop(Y)
plot_flying_things3D(X, Y, None)
| 25.137931 | 88 | 0.747599 | import tools
import os
from dataset import RandomCropper, sub_sampling
from utils import plot_flying_things3D
height = 240
width = 576
ratio = 1
height = height//ratio
width = width//ratio
train_files = os.listdir('/media/jack/data/Dataset/pytorch/flyingthings3d/TRAIN')
test_files = os.listdir('/media/jack/data/Dataset/pytorch/flyingthings3d/TEST')
print('number of train files:', len(train_files))
print('number of test files:', len(test_files))
X, Y = tools.load('/media/jack/data/Dataset/pytorch/flyingthings3d/TRAIN/data_00000.np')
X, Y = sub_sampling(X, Y, ratio)
cropper = RandomCropper(X.shape[1:3], (height, width), seed=0)
X, Y = cropper.crop(X), cropper.crop(Y)
plot_flying_things3D(X, Y, None)
| true | true |
f71b86630d2154e3ec53d9c2d1bbc45428ac1669 | 498 | py | Python | Lib/site-packages/plotly/validators/sankey/link/concentrationscales/_label.py | tytanya/my-first-blog | 2b40adb0816c3546e90ad6ca1e7fb50d924c1536 | [
"bzip2-1.0.6"
] | 4 | 2020-02-05T11:26:47.000Z | 2021-05-26T07:48:46.000Z | Lib/site-packages/plotly/validators/sankey/link/concentrationscales/_label.py | tytanya/my-first-blog | 2b40adb0816c3546e90ad6ca1e7fb50d924c1536 | [
"bzip2-1.0.6"
] | 6 | 2021-03-18T22:27:08.000Z | 2022-03-11T23:40:50.000Z | venv/lib/python3.7/site-packages/plotly/validators/sankey/link/concentrationscales/_label.py | kylenahas/180LoginV1 | 8f64be6e6016d47dff8febfcfa3bbd56e9042f89 | [
"MIT"
] | 1 | 2020-02-02T21:17:12.000Z | 2020-02-02T21:17:12.000Z | import _plotly_utils.basevalidators
class LabelValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='label',
parent_name='sankey.link.concentrationscales',
**kwargs
):
super(LabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
role=kwargs.pop('role', 'info'),
**kwargs
)
| 26.210526 | 67 | 0.610442 | import _plotly_utils.basevalidators
class LabelValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='label',
parent_name='sankey.link.concentrationscales',
**kwargs
):
super(LabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
role=kwargs.pop('role', 'info'),
**kwargs
)
| true | true |
f71b867bee311ba5e70b95ace8a6be7c624ca76a | 3,503 | py | Python | tensorflow_probability/python/experimental/auto_batching/numpy_backend_test.py | matthieucoquet/probability | 2426f4fc4743ceedc1a638a03d19ce6654ebff76 | [
"Apache-2.0"
] | null | null | null | tensorflow_probability/python/experimental/auto_batching/numpy_backend_test.py | matthieucoquet/probability | 2426f4fc4743ceedc1a638a03d19ce6654ebff76 | [
"Apache-2.0"
] | null | null | null | tensorflow_probability/python/experimental/auto_batching/numpy_backend_test.py | matthieucoquet/probability | 2426f4fc4743ceedc1a638a03d19ce6654ebff76 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tests for implementations of batched variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import hypothesis as hp
from hypothesis import strategies as hps
from hypothesis.extra import numpy as hpnp
import numpy as np
import tensorflow as tf
from tensorflow_probability.python.experimental.auto_batching import backend_test_lib as backend_test
from tensorflow_probability.python.experimental.auto_batching import instructions as inst
from tensorflow_probability.python.experimental.auto_batching import numpy_backend
NP_BACKEND = numpy_backend.NumpyBackend()
def var_init(max_stack_depth, initial_value):
type_ = inst.TensorType(initial_value.dtype, initial_value.shape[1:])
var = NP_BACKEND.create_variable(
None, inst.VariableAllocation.FULL, type_,
max_stack_depth, batch_size=initial_value.shape[0])
return var.update(
initial_value, NP_BACKEND.full_mask(initial_value.shape[0]))
# A TF test case for self.assertAllEqual, but doesn't use TF so doesn't care
# about Eager vs Graph mode.
class NumpyVariableTest(tf.test.TestCase, backend_test.VariableTestCase):
def testNumpySmoke(self):
"""Test the property on specific example, without relying on Hypothesis."""
init = (12, np.random.randn(3, 2, 2).astype(np.float32))
ops = [('pop', [False, False, True]),
('push', [True, False, True]),
('update', np.ones((3, 2, 2), dtype=np.float32),
[True, True, False]),
('pop', [True, False, True])]
self.check_same_results(init, ops, var_init)
@hp.given(hps.data())
@hp.settings(
deadline=None,
max_examples=100)
def testNumpyVariableRandomOps(self, data):
# Hypothesis strategy:
# Generate a random max stack depth and value shape
# Deduce the batch size from the value shape
# Make a random dtype
# Generate a random initial value of that dtype and shape
# Generate ops, some of which write random values of that dtype and shape
max_stack_depth = data.draw(hps.integers(min_value=1, max_value=1000))
value_shape = data.draw(hpnp.array_shapes(min_dims=1))
batch_size = value_shape[0]
dtype = data.draw(hpnp.scalar_dtypes())
masks = hpnp.arrays(dtype=np.bool, shape=[batch_size])
values = hpnp.arrays(dtype, value_shape)
init_val = data.draw(values)
ops = data.draw(
hps.lists(
hps.one_of(
hps.tuples(hps.just('update'), values, masks),
hps.tuples(hps.just('push'), masks),
hps.tuples(hps.just('pop'), masks), # preserve line break
hps.tuples(hps.just('read')))))
self.check_same_results((max_stack_depth, init_val), ops, var_init)
if __name__ == '__main__':
tf.test.main()
| 39.806818 | 101 | 0.703968 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import hypothesis as hp
from hypothesis import strategies as hps
from hypothesis.extra import numpy as hpnp
import numpy as np
import tensorflow as tf
from tensorflow_probability.python.experimental.auto_batching import backend_test_lib as backend_test
from tensorflow_probability.python.experimental.auto_batching import instructions as inst
from tensorflow_probability.python.experimental.auto_batching import numpy_backend
NP_BACKEND = numpy_backend.NumpyBackend()
def var_init(max_stack_depth, initial_value):
type_ = inst.TensorType(initial_value.dtype, initial_value.shape[1:])
var = NP_BACKEND.create_variable(
None, inst.VariableAllocation.FULL, type_,
max_stack_depth, batch_size=initial_value.shape[0])
return var.update(
initial_value, NP_BACKEND.full_mask(initial_value.shape[0]))
class NumpyVariableTest(tf.test.TestCase, backend_test.VariableTestCase):
def testNumpySmoke(self):
init = (12, np.random.randn(3, 2, 2).astype(np.float32))
ops = [('pop', [False, False, True]),
('push', [True, False, True]),
('update', np.ones((3, 2, 2), dtype=np.float32),
[True, True, False]),
('pop', [True, False, True])]
self.check_same_results(init, ops, var_init)
@hp.given(hps.data())
@hp.settings(
deadline=None,
max_examples=100)
def testNumpyVariableRandomOps(self, data):
max_stack_depth = data.draw(hps.integers(min_value=1, max_value=1000))
value_shape = data.draw(hpnp.array_shapes(min_dims=1))
batch_size = value_shape[0]
dtype = data.draw(hpnp.scalar_dtypes())
masks = hpnp.arrays(dtype=np.bool, shape=[batch_size])
values = hpnp.arrays(dtype, value_shape)
init_val = data.draw(values)
ops = data.draw(
hps.lists(
hps.one_of(
hps.tuples(hps.just('update'), values, masks),
hps.tuples(hps.just('push'), masks),
hps.tuples(hps.just('pop'), masks),
hps.tuples(hps.just('read')))))
self.check_same_results((max_stack_depth, init_val), ops, var_init)
if __name__ == '__main__':
tf.test.main()
| true | true |
f71b87f9a34ad86788ead5a5a291dfc02bf3cc77 | 138 | py | Python | modules/2.79/bpy/types/GPENCIL_UL_brush.py | cmbasnett/fake-bpy-module | acb8b0f102751a9563e5b5e5c7cd69a4e8aa2a55 | [
"MIT"
] | null | null | null | modules/2.79/bpy/types/GPENCIL_UL_brush.py | cmbasnett/fake-bpy-module | acb8b0f102751a9563e5b5e5c7cd69a4e8aa2a55 | [
"MIT"
] | null | null | null | modules/2.79/bpy/types/GPENCIL_UL_brush.py | cmbasnett/fake-bpy-module | acb8b0f102751a9563e5b5e5c7cd69a4e8aa2a55 | [
"MIT"
] | null | null | null | class GPENCIL_UL_brush:
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
pass
| 17.25 | 96 | 0.702899 | class GPENCIL_UL_brush:
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
pass
| true | true |
f71b88eb5a8cae0039b8f28310d55519871da1ba | 43,625 | py | Python | STR.py | Kashnikov-AV/Special-Theory-of-Relativity-lab- | 60a154bc357c38b097604bd21aaa810e07665104 | [
"MIT"
] | null | null | null | STR.py | Kashnikov-AV/Special-Theory-of-Relativity-lab- | 60a154bc357c38b097604bd21aaa810e07665104 | [
"MIT"
] | null | null | null | STR.py | Kashnikov-AV/Special-Theory-of-Relativity-lab- | 60a154bc357c38b097604bd21aaa810e07665104 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import pygame
import math
import time
import os
from rocket import Rocket
from watch import Watch
from button import Start
from button import Stop
from button import Pause
from button import Scroll
from button import Change_velocity
from button import Galileo
from button import Ruseng
def run_game():
'''initilize pygame'''
pygame.init()
'''settings of window'''
video = pygame.display.Info() #объект с разрешением экрана
# Set title of screen
image_icon = pygame.image.load("icon.ico")
pygame.display.set_caption("STR")
pygame.display.set_icon(image_icon)
WIDTH = video.current_w
HEIGHT = video.current_h
if video.current_w < 1600:
WIDTH = 1200
HEIGHT = 900
if video.current_w == 1440:
WIDTH = 1440
HEIGHT = 900
if video.current_w >= 1600:
WIDTH = 1600
HEIGHT = 900
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) #Инициализация окна
screen_rect = screen.get_rect() #координаты экрана
s = pygame.Surface((WIDTH,HEIGHT)) # the size of your rect
s.set_alpha(230) # alpha level
s.fill((0,0,0)) # this fills the entire surface
'''Constants and verables, flags and constants - big words'''
global_time = 0.0 #счетчик времени
if WIDTH == 1440 or WIDTH == 1600:
GLOBAL_L = 340 #длина ракеты расстояние между столбами в покое
if WIDTH == 1200:
GLOBAL_L = 256
alpha = 0 # относительная скорость
GLOBAL_C = 400 # скорость света
frame_count = 0 #счетчик фреймов
if WIDTH == 1600:
border = 70 #граница окон в пикселях
if WIDTH == 1440 or WIDTH == 1200:
border = 30
'''Флаги'''
RUSENG = True #изменение языка
GALILEO = True #преобразования галилео
DONE = False #флаг главного цикла
MOUSE_KLICK = False #обработка клика мышкой
LEFT_KLICK = False
RIGHT_KLICK = False
MENU = True #флаг меню
INSTRUCTION = False
AUTORS = False
mouse_x = 0
mouse_y = 0
frame_rate = 0.0
frame1_ind = 0
frame1_rocket_length = 340 #length of moving rocket
RED = (255, 0, 0)
WHITE = (255,255,255)
BLACK = (0 , 0, 0)
#Background and menu
gerb = pygame.image.load('images/Gerb_MGTU_imeni_Baumana.png')
gerb = pygame.transform.scale(gerb, (170, 200))
gerb = gerb.convert_alpha()
selph = pygame.image.load('images/logo.png')
selph = pygame.transform.scale(selph, (368, 200))
selph = selph.convert_alpha()
if WIDTH==1440 or WIDTH==1200:
background = pygame.image.load('images/background_1440.png')
background = pygame.transform.scale(background, (WIDTH, HEIGHT))
background = background.convert_alpha()
background2 = pygame.image.load('images/background2_1440.png')
background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT))
background2 = background2.convert()
if WIDTH == 1600:
background = pygame.image.load('images/background.png')
background = pygame.transform.scale(background, (WIDTH, HEIGHT))
background = background.convert_alpha()
background2 = pygame.image.load('images/background2.png')
background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT))
background2 = background2.convert()
back_menu = pygame.image.load('images/menu.jpg')
back_menu = pygame.transform.scale(back_menu, (WIDTH, HEIGHT))
back_menu = back_menu.convert()
back_left = pygame.image.load('images/background_left.png')
back_left = pygame.transform.scale(back_left, (30, HEIGHT))
back_left = back_left.convert_alpha()
back_centr = pygame.image.load('images/background_centr.png')
back_centr = pygame.transform.scale(back_centr, (770, HEIGHT))
back_centr = back_centr.convert_alpha()
back_right = pygame.image.load('images/background_right.png')
back_right = pygame.transform.scale(back_right, (400, HEIGHT))
back_right = back_right.convert_alpha()
'''шрифты'''
font_1 = pygame.font.SysFont("arial", 18, bold=True)
font_2 = pygame.font.Font('fonts\courbd.ttf', 19)
font_3 = pygame.font.Font('fonts\mpus.ttf', 22)
font_4 = pygame.font.Font('fonts\courierstd-bold.otf', 22)
font_5 = pygame.font.Font('fonts\mpus.ttf', 56)
def text_1(Ttext, Tcolor, Tlocation):
text = font_1.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_2(Ttext, Tcolor, Tlocation):
text = font_2.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_3(Ttext, Tcolor, Tlocation):
text = font_3.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_4(Ttext, Tcolor, Tlocation):
text = font_4.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_5(Ttext, Tcolor, Tlocation):
text = font_5.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
'''buttons from module button, arrows '''
if WIDTH == 1600:
bt_1 = Change_velocity(screen , 1135, 270, 'images/speed_change.png','', (200, 100)) #ползунок
bt_start = Start(screen ,1200 ,420 , 'images/start.png','images/start_light.png', (140, 50))
bt_pause = Pause(screen ,1350 ,420 , 'images/pause.png','images/pause_light.png', (140, 50))
bt_stop = Stop(screen ,1500 ,420 , 'images/stop.png','images/stop_light.png', (140, 50))
bt_left = Scroll(screen ,1295 ,490 , 'images/bt_scroll_left_light.png','images/bt_scroll_left.png', (100, 60))
bt_right = Scroll(screen ,1405 ,490 , 'images/bt_scroll_right_light.png','images/bt_scroll_right.png', (100, 60))
bt_galileo = Galileo(screen ,1350 ,790 , 'images/Galileo_off.png','images/Galileo_on.png', (360, 50))
bt_ruseng = Ruseng(screen ,WIDTH - 100,HEIGHT - 50, 'images/ruseng.png','images/ruseng2.png', (50, 25))
if WIDTH == 1440 or WIDTH == 1200:
bt_1 = Change_velocity(screen , WIDTH-350, 270, 'images/speed_change.png','', (200, 100)) #ползунок
bt_start = Start(screen ,WIDTH-305 , 420 , 'images/start.png','images/start_light.png', (120, 40))
bt_pause = Pause(screen ,WIDTH-185 , 420 , 'images/pause.png','images/pause_light.png', (120, 40))
bt_stop = Stop(screen ,WIDTH-65 , 420 , 'images/stop.png','images/stop_light.png', (120, 40))
bt_left = Scroll(screen ,WIDTH-240 , 490 , 'images/bt_scroll_left_light.png','images/bt_scroll_left.png', (100, 60))
bt_right = Scroll(screen ,WIDTH-130 , 490 , 'images/bt_scroll_right_light.png','images/bt_scroll_right.png', (100, 60))
bt_galileo = Galileo(screen ,WIDTH-190, 790 , 'images/Galileo_off.png','images/Galileo_on.png', (360, 50))
bt_ruseng = Ruseng(screen ,WIDTH - 100, HEIGHT - 50, 'images/ruseng.png','images/ruseng2.png', (50, 25))
'''create objects'''
#function of pillars-----------------------------------------------------------------
img_pillar = pygame.image.load('images/pillar3.png')
img_pillar = pygame.transform.scale(img_pillar, (102, 192))
img_pillar = img_pillar.convert_alpha()
img_pillar_2 = img_pillar
rect_pillar = img_pillar.get_rect() #rectangle of image of pillar
rect_pillar.bottom = 870
rect_pillar.centerx = 0
x = 0 #coordinate arrow of pillar watches
y = 0
def img_load(beta, img_pillar, img_pillar_2):
scale = 1/beta
img_pillar = img_pillar_2
img_pillar = pygame.transform.scale(img_pillar, (int(102/scale), 192))
rect = img_pillar.get_rect()
rect.bottom = 870
return(img_pillar, rect)
def update_watchup(global_time):
x = 25*math.cos(math.pi/2-math.pi/30*global_time)
y = 25*math.sin(math.pi/2-math.pi/30*global_time)
return(x,y)
def update_watchdown(t, beta):
x = 25*beta*math.cos(math.pi/2-math.pi/30*t)
y = 25*math.sin(math.pi/2-math.pi/30*t)
return(x,y)
def blitme_pillar(screen, color, img, rect, x, y):
screen.blit(img, rect)
pygame.draw.line(screen, color, (rect.centerx,rect.bottom -143),
(rect.centerx + x, rect.bottom -143 - y), 2)
#--------------------------------------------------------------------------------------------
if WIDTH==1600:
watch1 = Watch(screen, 1200, 150, 'images/watch.png') #часы
watch2 = Watch(screen, 1350, 150, 'images/watch.png')
watch3 = Watch(screen, 1500, 150, 'images/watch.png')
watch4 = Watch(screen, 1200, 670, 'images/watch.png')
watch5 = Watch(screen, 1350, 670, 'images/watch.png')
watch6 = Watch(screen, 1500, 670, 'images/watch.png')
if WIDTH == 1440 or WIDTH == 1200:
watch1 = Watch(screen, WIDTH-315, 150, 'images/watch_1440.png') #часы
watch2 = Watch(screen, WIDTH-190, 150, 'images/watch_1440.png')
watch3 = Watch(screen, WIDTH- 65, 150, 'images/watch_1440.png')
watch4 = Watch(screen, WIDTH-315, 670, 'images/watch_1440.png')
watch5 = Watch(screen, WIDTH-190, 670, 'images/watch_1440.png')
watch6 = Watch(screen, WIDTH- 65, 670, 'images/watch_1440.png')
rocket_1 = Rocket(screen, border + 1.5*GLOBAL_L, 150, GLOBAL_L) #ракеты
rocket_2 = Rocket(screen, border + 1.5*GLOBAL_L, 580, GLOBAL_L)
#watches icons----------------------------------------
img_watchpick = pygame.image.load('images/watchpick.png')
img_watchpick = pygame.transform.scale(img_watchpick, (20, 20))
img_watchpick = img_watchpick.convert_alpha()
img_watchpick2 = img_watchpick
rect_icon = img_watchpick.get_rect()
def img_load_icons(beta, img_watchpick, img_watchpick2):
scale = 1/beta
img_watchpick = img_watchpick2
img_watchpick = pygame.transform.scale(img_watchpick, (int(20/scale), 20))
rect = img_watchpick.get_rect()
rect.centery = 150
return(img_watchpick, rect)
#-----------------------------------------------------------
img_a = pygame.image.load('images/A.png')
img_a = pygame.transform.scale(img_a, (40, 40))
img_a = img_a.convert_alpha()
img_b = pygame.image.load('images/B.png')
img_b = pygame.transform.scale(img_b, (40, 40))
img_b = img_b.convert_alpha()
img_c = pygame.image.load('images/C.png')
img_c = pygame.transform.scale(img_c, (40, 40))
img_c = img_c.convert_alpha()
'''timers'''
clock = pygame.time.Clock()
timer = pygame.time.Clock()
timer.tick()
'''function str watch timers'''
def time_to_string(x):
if x < 0:
x += 60*60
return str(math.floor(x/60)*10+1001)[1:3]+':'+str(math.floor(x%60)*10+1001)[1:3]+':'+str((x-math.floor(x))*1000+1001)[1:3]
# -------- Main Program Loop -----------
screen.blit(s, (0,0))
screen.blit(gerb, (screen_rect.centerx-300, screen_rect.centery-100))
screen.blit(selph, (screen_rect.centerx, screen_rect.centery-100))
pygame.display.flip()
time.sleep(1.5)
while not DONE:
mouse_pos = pygame.mouse.get_pos()
mouse_x = mouse_pos[0]
mouse_y = mouse_pos[1]
'''Events'''
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
DONE = True # Flag that we are done so we exit this loop
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
MENU = True
global_time = 0.0
rocket_1.global_rocket_x = 0.0
rocket_1.global_rocket_x_start = 0
rocket_1.global_rocket_t_start = 0
bt_pause.pause = True
alpha = 0
bt_1.bt1_x = bt_1.rect.left
rocket_1.img_load()
rocket_1.firestop = False
rocket_2.firestop = False
AUTORS = False
if event.key == pygame.K_RIGHT:
RIGHT_KLICK = True
if event.key == pygame.K_LEFT:
LEFT_KLICK = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
RIGHT_KLICK = False
if event.key == pygame.K_LEFT:
LEFT_KLICK = False
if event.key == pygame.K_SPACE:
bt_pause.pause = False
elif event.type == pygame.MOUSEBUTTONDOWN:
MOUSE_KLICK = True
elif event.type == pygame.MOUSEBUTTONUP:
MOUSE_KLICK = False
'''Logic'''
if not MENU:
#преобразования галилео
if bt_galileo.flag:
GALILEO = True
else:
GALILEO = False
frame_count += 1
frame_rate = clock.get_time()
# множитель лоренцевых преобразований
beta = math.sqrt(1 - alpha*alpha)
#////////////////////////////////////////////////////////////////#
#buttons
if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.pause = True
else:
rocket_1.firestop = True
rocket_2.firestop = True
if bt_pause.pause:
frame_rate = 0
rocket_1.firestop = False
rocket_2.firestop = False
if bt_left.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_pause.pause:
if global_time > 0:
rocket_1.firestop = True
rocket_2.firestop = True
global_time -= 0.01/(alpha+0.01)
else:
global_time = 0
if LEFT_KLICK and bt_pause.pause:
if global_time > 0:
rocket_1.firestop = True
rocket_2.firestop = True
global_time -= 0.0025/(alpha+0.01)
else:
global_time = 0
if bt_right.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_pause.pause:
rocket_1.firestop = True
rocket_2.firestop = True
global_time += 0.01/(alpha+0.01)
if RIGHT_KLICK and bt_pause.pause:
rocket_1.firestop = True
rocket_2.firestop = True
global_time += 0.0025/(alpha+0.01)
if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.pause = False
if alpha == 0:
alpha = 0.05
rocket_1.firestop = True
rocket_2.firestop = True
if bt_1.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and global_time == 0:
bt_1.bt1_x = mouse_x-10
frame_rate = 0
if (mouse_x - bt_1.rect.left)/200 > 0.98:
alpha = 0.98
else:
alpha = ((mouse_x - bt_1.rect.left)/200)
rocket_1.img_load()
rocket_1.global_rocket_t_start = global_time
rocket_1.global_rocket_x_start = rocket_1.global_rocket_x
if WIDTH < 1600 and (mouse_x - bt_1.rect.left)/200 > 0.965:
alpha = 0.965
if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
rocket_1.global_rocket_x_start = 0
rocket_1.global_rocket_t_start = 0
global_time = 0
bt_pause.pause = True
alpha = 0
bt_1.bt1_x = bt_1.rect.left
rocket_1.img_load()
rocket_1.firestop = False
rocket_2.firestop = False
if bt_galileo.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_galileo.clickflag == True:
bt_galileo.click()
rocket_1.img_load()
else:
rocket_1.img_load()
bt_galileo.clickflag == True
if MOUSE_KLICK == False:
bt_galileo.clickflag = True
#////////////////////////////////////////////////////////////////
# --- Timer going up ---
# Calculate total seconds
if frame_rate != 0:
# global time
global_time += frame_rate /1000
frame1_rocket_time1 = global_time*beta + alpha*GLOBAL_L*0.5/GLOBAL_C
frame1_rocket_time2 = global_time*beta
frame1_rocket_time3 = global_time*beta - alpha*GLOBAL_L*0.5/GLOBAL_C
#rocket_1 scale with alpha
if not GALILEO:
rocket_1.Lx_scale(alpha, 150, GLOBAL_L)
else:
rocket_1.Lx_scale(0, 150, GLOBAL_L)
#rocket_1 move
rocket_1.update(alpha, GLOBAL_C, GLOBAL_L, frame1_rocket_length, global_time, frame1_ind, border)
frame1_ind = math.floor((rocket_1.global_rocket_x + 2*GLOBAL_L)/(4*GLOBAL_L))
#length_of_rocket scale with alpha
frame1_rocket_length = beta*GLOBAL_L
#update watches
if not GALILEO:
watch1.update(frame1_rocket_time1)
watch2.update(frame1_rocket_time2)
watch3.update(frame1_rocket_time3)
watch4.update(global_time)
watch5.update(global_time)
watch6.update(global_time)
else:
watch1.update(global_time)
watch2.update(global_time)
watch3.update(global_time)
watch4.update(global_time)
watch5.update(global_time)
watch6.update(global_time)
#кнопка переключения языка
else:
if bt_ruseng.flag == True:
RUSENG = True
else:
RUSENG = False
if bt_ruseng.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_ruseng.clickflag == True:
bt_ruseng.click()
else:
bt_ruseng.clickflag == True
if MOUSE_KLICK == False:
bt_ruseng.clickflag = True
#*****************************************************************
#/////////////////////////////////////////////////////////////////
#*****************************************************************
'''Draw all'''
if not MENU:
screen.blit(background2, screen_rect)
rocket_1.blitme(frame_count)
rocket_2.blitme(frame_count)
if not GALILEO:
pygame.draw.line(screen, (231, 115, 38), (rocket_1.rect.centerx- 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx - 0.5*beta*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx, rocket_1.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_1.rect.centerx+ 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx + 0.5*beta*GLOBAL_L, rocket_1.rect.centery))
else:
pygame.draw.line(screen, (231, 115, 38), (rocket_1.rect.centerx- 0.5*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx - 0.5*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx, rocket_1.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_1.rect.centerx+ 0.5*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx + 0.5*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (231, 115, 38), (rocket_2.rect.centerx- 0.5*GLOBAL_L, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx - 0.5*GLOBAL_L, rocket_2.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_2.rect.centerx, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx, rocket_2.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_2.rect.centerx+ 0.5*GLOBAL_L, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx + 0.5*GLOBAL_L, rocket_2.rect.centery))
#watch icons
#----------------------------------------------------------------------------------------------------
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10, rocket_2.rect.centery - 10))
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 - 0.5*GLOBAL_L, rocket_2.rect.centery - 10))
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 + 0.5*GLOBAL_L, rocket_2.rect.centery - 10))
if not GALILEO:
img_watchpick, rect_icon = img_load_icons(beta, img_watchpick, img_watchpick2)
rect_icon.centerx = rocket_1.rect.centerx
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx - 0.5*beta*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx + 0.5*beta*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
screen.blit(img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100))
screen.blit(img_a, (rocket_1.rect.centerx - 20 - 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_c, (rocket_1.rect.centerx - 20 + 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 100))
else:
img_watchpick, rect_icon = img_load_icons(1, img_watchpick, img_watchpick2)
rect_icon.centerx = rocket_1.rect.centerx
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx - 0.5*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx + 0.5*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
screen.blit(img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100))
screen.blit(img_a, (rocket_1.rect.centerx - 20 - 0.5*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_c, (rocket_1.rect.centerx - 20 + 0.5*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_b, (rocket_2.rect.centerx - 20, rocket_2.rect.centery - 100))
screen.blit(img_a, (rocket_2.rect.centerx - 20 - 0.5*GLOBAL_L, rocket_2.rect.centery - 100))
screen.blit(img_c, (rocket_2.rect.centerx - 20 + 0.5*GLOBAL_L, rocket_2.rect.centery - 100))
#----------------------------------------------------------------------------------------------------
#pillar update and draw
frame1_pillar1_ind = (frame1_ind)*4
frame1_pillar2_ind = (frame1_ind)*4 + 1
frame1_pillar3_ind = (frame1_ind)*4 + 2
x, y = update_watchup(global_time)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + GLOBAL_L/2, 248, 102, 192), x, y)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + 1.5*GLOBAL_L, 248, 102, 192), x, y)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + 2.5*GLOBAL_L, 248, 102, 192), x, y)
text_1(str(frame1_pillar1_ind%100), BLACK,(border-6 + GLOBAL_L/2, 206))
text_1(str(frame1_pillar2_ind%100), BLACK,(border-6 + 1.5*GLOBAL_L, 206))
text_1(str(frame1_pillar3_ind%100), BLACK,(border-6 + 2.5*GLOBAL_L, 206))
str_time = time_to_string(global_time)
text_1('['+ str_time + ']', BLACK,(border-33 + GLOBAL_L/2, 225))
text_1('['+ str_time + ']', BLACK,(border-33 + 1.5*GLOBAL_L, 225))
text_1('['+ str_time + ']', BLACK,(border-33 + 2.5*GLOBAL_L, 225))
if not GALILEO:
a = math.ceil((-2*GLOBAL_L+alpha*GLOBAL_C*global_time)/beta/GLOBAL_L) #index of pillar
b = math.floor((2*GLOBAL_L+alpha*GLOBAL_C*global_time)/beta/GLOBAL_L+1)
img_pillar, rect_pillar = img_load(beta, img_pillar, img_pillar_2)
for ind in range(a, b+1):
frame2_pillar_x = beta*(ind-1)*GLOBAL_L-GLOBAL_C*alpha*global_time + 1.5*GLOBAL_L + border
frame2_pillar_time = beta*global_time + alpha*GLOBAL_L/GLOBAL_C*(ind - 1)
rect_pillar.centerx = frame2_pillar_x
x, y = update_watchdown(frame2_pillar_time, beta)
blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y)
text_1(str(ind%1000), BLACK,(rect_pillar.centerx - 6, 636))
str_time = time_to_string(frame2_pillar_time)
text_1('[' + str_time + ']', BLACK,(rect_pillar.centerx - 33, 655))
else:
a = math.ceil((-2*GLOBAL_L+alpha*GLOBAL_C*global_time)/GLOBAL_L) #index of pillar
b = math.floor((2*GLOBAL_L+alpha*GLOBAL_C*global_time)/GLOBAL_L+1)
img_pillar, rect_pillar = img_load(1, img_pillar, img_pillar_2)
for ind in range(a, b+1):
frame2_pillar_x = (ind-1)*GLOBAL_L-GLOBAL_C*alpha*global_time + 1.5*GLOBAL_L + border
frame2_pillar_time = global_time
rect_pillar.centerx = frame2_pillar_x
x, y = update_watchdown(frame2_pillar_time, beta)
blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y)
text_1(str(ind%1000), BLACK,(rect_pillar.centerx - 6, 636))
str_time = time_to_string(frame2_pillar_time)
text_1('[' + str_time + ']', BLACK,(rect_pillar.centerx - 33, 655))
#---------------------------------------------------------------------------
if WIDTH != 1200:
screen.blit(background, screen_rect)
else:
screen.blit(back_left, (0,0))
screen.blit(back_centr, (30, 0))
screen.blit(back_right, (800,0))
bt_1.blitme()
if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_start.blitme()
else:
bt_start.blitmeclick()
if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.blitmeclick()
else:
bt_pause.blitme()
if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_stop.blitme()
else:
bt_stop.blitmeclick()
if bt_left.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_left.blitme()
else:
bt_left.blitmeclick()
if bt_right.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_right.blitme()
else:
bt_right.blitmeclick()
if not bt_galileo.flag:
bt_galileo.blitme()
else:
bt_galileo.blitmeclick()
watch1.blitme(BLACK)
watch2.blitme(BLACK)
watch3.blitme(BLACK)
watch4.blitme(BLACK)
watch5.blitme(BLACK)
watch6.blitme(BLACK)
#watches text
if not GALILEO:
screen.blit(img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time1)
if WIDTH==1600:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48))
screen.blit(img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time2)
if WIDTH==1600:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48))
screen.blit(img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time3)
if WIDTH==1600:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48))
screen.blit(img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130))
str_time = time_to_string(global_time)
if WIDTH==1600:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48))
screen.blit(img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48))
screen.blit(img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48))
else:
screen.blit(img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130))
str_time = time_to_string(global_time)
if WIDTH==1600:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48))
screen.blit(img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48))
screen.blit(img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48))
screen.blit(img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48))
screen.blit(img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48))
screen.blit(img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48))
#текст на кнопках
if RUSENG:
text_4("START", BLACK, (bt_start.rect.centerx-30, bt_start.rect.centery-7))
text_4("PAUSE", BLACK, (bt_pause.rect.centerx-30, bt_pause.rect.centery-7))
text_4("STOP", BLACK, (bt_stop.rect.centerx-30, bt_stop.rect.centery-7))
text_2("Galilean", BLACK, (bt_galileo.rect.centerx-168, bt_galileo.rect.centery-18))
text_2("Transformation", BLACK, (bt_galileo.rect.centerx-168, bt_galileo.rect.centery +3))
text_2("Lorentz", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery-18))
text_2("Transformation", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery +3))
else:
text_2("СТАРТ", BLACK, (bt_start.rect.centerx-30, bt_start.rect.centery-10))
text_2("ПАУЗА", BLACK, (bt_pause.rect.centerx-30, bt_pause.rect.centery-10))
text_2("СТОП", BLACK, (bt_stop.rect.centerx-25, bt_stop.rect.centery-10))
text_2("Трансформация", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery-18))
text_2("Галилея", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery))
text_2("Трансформация", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery-18))
text_2("Лоренца", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery))
#text
if RUSENG:
if WIDTH == 1600:
text_4("Velocity:", BLACK, (1370, 270))
text_4(str(round(alpha, 3)), BLACK, (1370, 310))
text_4("of light speed", BLACK, (1370, 350))
if WIDTH==1440 or WIDTH==1200:
text_4("Velocity:", BLACK, (WIDTH-140, 270))
text_4(str(round(alpha, 3)), BLACK, (WIDTH-140, 310))
text_4("of light", BLACK, (WIDTH-140, 350))
else:
if WIDTH == 1600:
text_1("Скорость:", BLACK, (1370, 270))
text_1(str(round(alpha, 3)), BLACK, (1370, 310))
text_1("скорости света", BLACK, (1370, 350))
if WIDTH==1440 or WIDTH==1200:
text_1("Скорость:", BLACK, (WIDTH-140, 270))
text_1(str(round(alpha, 3)), BLACK, (WIDTH-140, 310))
text_1("скорости света", BLACK, (WIDTH-140, 350))
else:
screen.blit(back_menu, screen_rect)
if INSTRUCTION:
os.startfile(r'STR_laba.pdf')
INSTRUCTION = False
if RUSENG:
text_5("New experiment", BLACK,(WIDTH-498,282))
text_5("New experiment", WHITE,(WIDTH-500,280))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350:
text_5("New experiment", RED,(WIDTH-500,280))
if MOUSE_KLICK:
MENU = False
text_5("Instruction", BLACK,(WIDTH-498,382))
text_5("Instruction", WHITE,(WIDTH-500,380))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450:
text_5("Instruction", RED,(WIDTH-500,380))
if MOUSE_KLICK:
INSTRUCTION = True
text_5("Autors", BLACK,(WIDTH-498,482))
text_5("Autors", WHITE,(WIDTH-500,480))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550:
text_5("Autors", RED,(WIDTH-500,480))
if MOUSE_KLICK:
AUTORS = True
text_5("Quit", BLACK,(WIDTH-498,582))
text_5("Quit", WHITE,(WIDTH-500,580))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650:
text_5("Quit", RED,(WIDTH-500,580))
if MOUSE_KLICK:
DONE = True
else:
text_5("Новый эксперимент", BLACK,(WIDTH-548,282))
text_5("Новый эксперимент", WHITE,(WIDTH-550,280))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350:
text_5("Новый эксперимент", RED,(WIDTH-550,280))
if MOUSE_KLICK:
MENU = False
text_5("Инструкция", BLACK,(WIDTH-548,382))
text_5("Инструкция", WHITE,(WIDTH-550,380))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450:
text_5("Инструкция", RED,(WIDTH-550,380))
if MOUSE_KLICK:
INSTRUCTION = True
text_5("Авторы", BLACK,(WIDTH-548,482))
text_5("Авторы", WHITE,(WIDTH-550,480))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550:
text_5("Авторы", RED,(WIDTH-550,480))
if MOUSE_KLICK:
AUTORS = True
text_5("Выход", BLACK,(WIDTH-548,582))
text_5("Выход", WHITE,(WIDTH-550,580))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650:
text_5("Выход", RED,(WIDTH-550,580))
if MOUSE_KLICK:
DONE = True
if bt_ruseng.flag:
bt_ruseng.blitme()
else:
bt_ruseng.blitmeclick()
text_1("РУС", BLACK,(bt_ruseng.rect.centerx-55,bt_ruseng.rect.centery-10))
text_1("ENG", BLACK,(bt_ruseng.rect.centerx+30,bt_ruseng.rect.centery-10))
if bt_ruseng.rect.collidepoint(mouse_pos):
text_1("РУС", RED,(bt_ruseng.rect.centerx-55,bt_ruseng.rect.centery-10))
text_1("ENG", RED,(bt_ruseng.rect.centerx+30,bt_ruseng.rect.centery-10))
if AUTORS:
screen.blit(s, (0,0)) # (0,0) are the top-left coordinates
if not RUSENG:
text_1("Программирование", WHITE, (screen_rect.centerx-50,screen_rect.centery-150))
text_3("Кашников Александр МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery-120))
text_3("Киктенко Евгений МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery-90))
text_1("Расчеты", WHITE, (screen_rect.centerx-50, screen_rect.centery-60))
text_3("Киктенко Евгений", WHITE, (screen_rect.centerx-150, screen_rect.centery-30))
text_3("Кашников Александр", WHITE, (screen_rect.centerx-150, screen_rect.centery))
text_3("Гусманова Анастасия МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery+30))
text_1("Графика", WHITE, (screen_rect.centerx-50, screen_rect.centery+60))
text_3("Кашников Александр", WHITE, (screen_rect.centerx-150, screen_rect.centery+90))
else:
text_1("programming", WHITE, (screen_rect.centerx-50,screen_rect.centery-150))
text_3("Kashnikov Alexander BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery-120))
text_3("Kiktenko Evgeniy BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery-90))
text_1("Calculations", WHITE, (screen_rect.centerx-50, screen_rect.centery-60))
text_3("Kiktenko Evgeniy", WHITE, (screen_rect.centerx-150, screen_rect.centery-30))
text_3("Kashnikov Alexander", WHITE, (screen_rect.centerx-150, screen_rect.centery))
text_3("Gusmanova Anastasiya BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery+30))
text_1("Design", WHITE, (screen_rect.centerx-50, screen_rect.centery+60))
text_3("Kashnikov Alexander", WHITE, (screen_rect.centerx-150, screen_rect.centery+90))
clock.tick(60)
'''Go ahead and update the screen with what we've drawn.'''
pygame.display.flip()
run_game()
pygame.quit()
| 49.349548 | 134 | 0.525547 |
import pygame
import math
import time
import os
from rocket import Rocket
from watch import Watch
from button import Start
from button import Stop
from button import Pause
from button import Scroll
from button import Change_velocity
from button import Galileo
from button import Ruseng
def run_game():
'''initilize pygame'''
pygame.init()
'''settings of window'''
video = pygame.display.Info()
image_icon = pygame.image.load("icon.ico")
pygame.display.set_caption("STR")
pygame.display.set_icon(image_icon)
WIDTH = video.current_w
HEIGHT = video.current_h
if video.current_w < 1600:
WIDTH = 1200
HEIGHT = 900
if video.current_w == 1440:
WIDTH = 1440
HEIGHT = 900
if video.current_w >= 1600:
WIDTH = 1600
HEIGHT = 900
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN)
screen_rect = screen.get_rect()
s = pygame.Surface((WIDTH,HEIGHT))
s.set_alpha(230)
s.fill((0,0,0))
'''Constants and verables, flags and constants - big words'''
global_time = 0.0
if WIDTH == 1440 or WIDTH == 1600:
GLOBAL_L = 340
if WIDTH == 1200:
GLOBAL_L = 256
alpha = 0
GLOBAL_C = 400
frame_count = 0
if WIDTH == 1600:
border = 70
if WIDTH == 1440 or WIDTH == 1200:
border = 30
'''Флаги'''
RUSENG = True
GALILEO = True
DONE = False
MOUSE_KLICK = False
LEFT_KLICK = False
RIGHT_KLICK = False
MENU = True
INSTRUCTION = False
AUTORS = False
mouse_x = 0
mouse_y = 0
frame_rate = 0.0
frame1_ind = 0
frame1_rocket_length = 340
RED = (255, 0, 0)
WHITE = (255,255,255)
BLACK = (0 , 0, 0)
gerb = pygame.image.load('images/Gerb_MGTU_imeni_Baumana.png')
gerb = pygame.transform.scale(gerb, (170, 200))
gerb = gerb.convert_alpha()
selph = pygame.image.load('images/logo.png')
selph = pygame.transform.scale(selph, (368, 200))
selph = selph.convert_alpha()
if WIDTH==1440 or WIDTH==1200:
background = pygame.image.load('images/background_1440.png')
background = pygame.transform.scale(background, (WIDTH, HEIGHT))
background = background.convert_alpha()
background2 = pygame.image.load('images/background2_1440.png')
background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT))
background2 = background2.convert()
if WIDTH == 1600:
background = pygame.image.load('images/background.png')
background = pygame.transform.scale(background, (WIDTH, HEIGHT))
background = background.convert_alpha()
background2 = pygame.image.load('images/background2.png')
background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT))
background2 = background2.convert()
back_menu = pygame.image.load('images/menu.jpg')
back_menu = pygame.transform.scale(back_menu, (WIDTH, HEIGHT))
back_menu = back_menu.convert()
back_left = pygame.image.load('images/background_left.png')
back_left = pygame.transform.scale(back_left, (30, HEIGHT))
back_left = back_left.convert_alpha()
back_centr = pygame.image.load('images/background_centr.png')
back_centr = pygame.transform.scale(back_centr, (770, HEIGHT))
back_centr = back_centr.convert_alpha()
back_right = pygame.image.load('images/background_right.png')
back_right = pygame.transform.scale(back_right, (400, HEIGHT))
back_right = back_right.convert_alpha()
'''шрифты'''
font_1 = pygame.font.SysFont("arial", 18, bold=True)
font_2 = pygame.font.Font('fonts\courbd.ttf', 19)
font_3 = pygame.font.Font('fonts\mpus.ttf', 22)
font_4 = pygame.font.Font('fonts\courierstd-bold.otf', 22)
font_5 = pygame.font.Font('fonts\mpus.ttf', 56)
def text_1(Ttext, Tcolor, Tlocation):
text = font_1.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_2(Ttext, Tcolor, Tlocation):
text = font_2.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_3(Ttext, Tcolor, Tlocation):
text = font_3.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_4(Ttext, Tcolor, Tlocation):
text = font_4.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
def text_5(Ttext, Tcolor, Tlocation):
text = font_5.render(Ttext, True, Tcolor)
screen.blit(text, Tlocation)
'''buttons from module button, arrows '''
if WIDTH == 1600:
bt_1 = Change_velocity(screen , 1135, 270, 'images/speed_change.png','', (200, 100))
bt_start = Start(screen ,1200 ,420 , 'images/start.png','images/start_light.png', (140, 50))
bt_pause = Pause(screen ,1350 ,420 , 'images/pause.png','images/pause_light.png', (140, 50))
bt_stop = Stop(screen ,1500 ,420 , 'images/stop.png','images/stop_light.png', (140, 50))
bt_left = Scroll(screen ,1295 ,490 , 'images/bt_scroll_left_light.png','images/bt_scroll_left.png', (100, 60))
bt_right = Scroll(screen ,1405 ,490 , 'images/bt_scroll_right_light.png','images/bt_scroll_right.png', (100, 60))
bt_galileo = Galileo(screen ,1350 ,790 , 'images/Galileo_off.png','images/Galileo_on.png', (360, 50))
bt_ruseng = Ruseng(screen ,WIDTH - 100,HEIGHT - 50, 'images/ruseng.png','images/ruseng2.png', (50, 25))
if WIDTH == 1440 or WIDTH == 1200:
bt_1 = Change_velocity(screen , WIDTH-350, 270, 'images/speed_change.png','', (200, 100))
bt_start = Start(screen ,WIDTH-305 , 420 , 'images/start.png','images/start_light.png', (120, 40))
bt_pause = Pause(screen ,WIDTH-185 , 420 , 'images/pause.png','images/pause_light.png', (120, 40))
bt_stop = Stop(screen ,WIDTH-65 , 420 , 'images/stop.png','images/stop_light.png', (120, 40))
bt_left = Scroll(screen ,WIDTH-240 , 490 , 'images/bt_scroll_left_light.png','images/bt_scroll_left.png', (100, 60))
bt_right = Scroll(screen ,WIDTH-130 , 490 , 'images/bt_scroll_right_light.png','images/bt_scroll_right.png', (100, 60))
bt_galileo = Galileo(screen ,WIDTH-190, 790 , 'images/Galileo_off.png','images/Galileo_on.png', (360, 50))
bt_ruseng = Ruseng(screen ,WIDTH - 100, HEIGHT - 50, 'images/ruseng.png','images/ruseng2.png', (50, 25))
'''create objects'''
img_pillar = pygame.image.load('images/pillar3.png')
img_pillar = pygame.transform.scale(img_pillar, (102, 192))
img_pillar = img_pillar.convert_alpha()
img_pillar_2 = img_pillar
rect_pillar = img_pillar.get_rect()
rect_pillar.bottom = 870
rect_pillar.centerx = 0
x = 0
y = 0
def img_load(beta, img_pillar, img_pillar_2):
scale = 1/beta
img_pillar = img_pillar_2
img_pillar = pygame.transform.scale(img_pillar, (int(102/scale), 192))
rect = img_pillar.get_rect()
rect.bottom = 870
return(img_pillar, rect)
def update_watchup(global_time):
x = 25*math.cos(math.pi/2-math.pi/30*global_time)
y = 25*math.sin(math.pi/2-math.pi/30*global_time)
return(x,y)
def update_watchdown(t, beta):
x = 25*beta*math.cos(math.pi/2-math.pi/30*t)
y = 25*math.sin(math.pi/2-math.pi/30*t)
return(x,y)
def blitme_pillar(screen, color, img, rect, x, y):
screen.blit(img, rect)
pygame.draw.line(screen, color, (rect.centerx,rect.bottom -143),
(rect.centerx + x, rect.bottom -143 - y), 2)
if WIDTH==1600:
watch1 = Watch(screen, 1200, 150, 'images/watch.png')
watch2 = Watch(screen, 1350, 150, 'images/watch.png')
watch3 = Watch(screen, 1500, 150, 'images/watch.png')
watch4 = Watch(screen, 1200, 670, 'images/watch.png')
watch5 = Watch(screen, 1350, 670, 'images/watch.png')
watch6 = Watch(screen, 1500, 670, 'images/watch.png')
if WIDTH == 1440 or WIDTH == 1200:
watch1 = Watch(screen, WIDTH-315, 150, 'images/watch_1440.png')
watch2 = Watch(screen, WIDTH-190, 150, 'images/watch_1440.png')
watch3 = Watch(screen, WIDTH- 65, 150, 'images/watch_1440.png')
watch4 = Watch(screen, WIDTH-315, 670, 'images/watch_1440.png')
watch5 = Watch(screen, WIDTH-190, 670, 'images/watch_1440.png')
watch6 = Watch(screen, WIDTH- 65, 670, 'images/watch_1440.png')
rocket_1 = Rocket(screen, border + 1.5*GLOBAL_L, 150, GLOBAL_L)
rocket_2 = Rocket(screen, border + 1.5*GLOBAL_L, 580, GLOBAL_L)
img_watchpick = pygame.image.load('images/watchpick.png')
img_watchpick = pygame.transform.scale(img_watchpick, (20, 20))
img_watchpick = img_watchpick.convert_alpha()
img_watchpick2 = img_watchpick
rect_icon = img_watchpick.get_rect()
def img_load_icons(beta, img_watchpick, img_watchpick2):
scale = 1/beta
img_watchpick = img_watchpick2
img_watchpick = pygame.transform.scale(img_watchpick, (int(20/scale), 20))
rect = img_watchpick.get_rect()
rect.centery = 150
return(img_watchpick, rect)
img_a = pygame.image.load('images/A.png')
img_a = pygame.transform.scale(img_a, (40, 40))
img_a = img_a.convert_alpha()
img_b = pygame.image.load('images/B.png')
img_b = pygame.transform.scale(img_b, (40, 40))
img_b = img_b.convert_alpha()
img_c = pygame.image.load('images/C.png')
img_c = pygame.transform.scale(img_c, (40, 40))
img_c = img_c.convert_alpha()
'''timers'''
clock = pygame.time.Clock()
timer = pygame.time.Clock()
timer.tick()
'''function str watch timers'''
def time_to_string(x):
if x < 0:
x += 60*60
return str(math.floor(x/60)*10+1001)[1:3]+':'+str(math.floor(x%60)*10+1001)[1:3]+':'+str((x-math.floor(x))*1000+1001)[1:3]
screen.blit(s, (0,0))
screen.blit(gerb, (screen_rect.centerx-300, screen_rect.centery-100))
screen.blit(selph, (screen_rect.centerx, screen_rect.centery-100))
pygame.display.flip()
time.sleep(1.5)
while not DONE:
mouse_pos = pygame.mouse.get_pos()
mouse_x = mouse_pos[0]
mouse_y = mouse_pos[1]
'''Events'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
DONE = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
MENU = True
global_time = 0.0
rocket_1.global_rocket_x = 0.0
rocket_1.global_rocket_x_start = 0
rocket_1.global_rocket_t_start = 0
bt_pause.pause = True
alpha = 0
bt_1.bt1_x = bt_1.rect.left
rocket_1.img_load()
rocket_1.firestop = False
rocket_2.firestop = False
AUTORS = False
if event.key == pygame.K_RIGHT:
RIGHT_KLICK = True
if event.key == pygame.K_LEFT:
LEFT_KLICK = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
RIGHT_KLICK = False
if event.key == pygame.K_LEFT:
LEFT_KLICK = False
if event.key == pygame.K_SPACE:
bt_pause.pause = False
elif event.type == pygame.MOUSEBUTTONDOWN:
MOUSE_KLICK = True
elif event.type == pygame.MOUSEBUTTONUP:
MOUSE_KLICK = False
'''Logic'''
if not MENU:
if bt_galileo.flag:
GALILEO = True
else:
GALILEO = False
frame_count += 1
frame_rate = clock.get_time()
beta = math.sqrt(1 - alpha*alpha)
if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.pause = True
else:
rocket_1.firestop = True
rocket_2.firestop = True
if bt_pause.pause:
frame_rate = 0
rocket_1.firestop = False
rocket_2.firestop = False
if bt_left.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_pause.pause:
if global_time > 0:
rocket_1.firestop = True
rocket_2.firestop = True
global_time -= 0.01/(alpha+0.01)
else:
global_time = 0
if LEFT_KLICK and bt_pause.pause:
if global_time > 0:
rocket_1.firestop = True
rocket_2.firestop = True
global_time -= 0.0025/(alpha+0.01)
else:
global_time = 0
if bt_right.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_pause.pause:
rocket_1.firestop = True
rocket_2.firestop = True
global_time += 0.01/(alpha+0.01)
if RIGHT_KLICK and bt_pause.pause:
rocket_1.firestop = True
rocket_2.firestop = True
global_time += 0.0025/(alpha+0.01)
if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.pause = False
if alpha == 0:
alpha = 0.05
rocket_1.firestop = True
rocket_2.firestop = True
if bt_1.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and global_time == 0:
bt_1.bt1_x = mouse_x-10
frame_rate = 0
if (mouse_x - bt_1.rect.left)/200 > 0.98:
alpha = 0.98
else:
alpha = ((mouse_x - bt_1.rect.left)/200)
rocket_1.img_load()
rocket_1.global_rocket_t_start = global_time
rocket_1.global_rocket_x_start = rocket_1.global_rocket_x
if WIDTH < 1600 and (mouse_x - bt_1.rect.left)/200 > 0.965:
alpha = 0.965
if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
rocket_1.global_rocket_x_start = 0
rocket_1.global_rocket_t_start = 0
global_time = 0
bt_pause.pause = True
alpha = 0
bt_1.bt1_x = bt_1.rect.left
rocket_1.img_load()
rocket_1.firestop = False
rocket_2.firestop = False
if bt_galileo.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_galileo.clickflag == True:
bt_galileo.click()
rocket_1.img_load()
else:
rocket_1.img_load()
bt_galileo.clickflag == True
if MOUSE_KLICK == False:
bt_galileo.clickflag = True
if frame_rate != 0:
global_time += frame_rate /1000
frame1_rocket_time1 = global_time*beta + alpha*GLOBAL_L*0.5/GLOBAL_C
frame1_rocket_time2 = global_time*beta
frame1_rocket_time3 = global_time*beta - alpha*GLOBAL_L*0.5/GLOBAL_C
if not GALILEO:
rocket_1.Lx_scale(alpha, 150, GLOBAL_L)
else:
rocket_1.Lx_scale(0, 150, GLOBAL_L)
rocket_1.update(alpha, GLOBAL_C, GLOBAL_L, frame1_rocket_length, global_time, frame1_ind, border)
frame1_ind = math.floor((rocket_1.global_rocket_x + 2*GLOBAL_L)/(4*GLOBAL_L))
frame1_rocket_length = beta*GLOBAL_L
if not GALILEO:
watch1.update(frame1_rocket_time1)
watch2.update(frame1_rocket_time2)
watch3.update(frame1_rocket_time3)
watch4.update(global_time)
watch5.update(global_time)
watch6.update(global_time)
else:
watch1.update(global_time)
watch2.update(global_time)
watch3.update(global_time)
watch4.update(global_time)
watch5.update(global_time)
watch6.update(global_time)
else:
if bt_ruseng.flag == True:
RUSENG = True
else:
RUSENG = False
if bt_ruseng.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True and bt_ruseng.clickflag == True:
bt_ruseng.click()
else:
bt_ruseng.clickflag == True
if MOUSE_KLICK == False:
bt_ruseng.clickflag = True
'''Draw all'''
if not MENU:
screen.blit(background2, screen_rect)
rocket_1.blitme(frame_count)
rocket_2.blitme(frame_count)
if not GALILEO:
pygame.draw.line(screen, (231, 115, 38), (rocket_1.rect.centerx- 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx - 0.5*beta*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx, rocket_1.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_1.rect.centerx+ 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx + 0.5*beta*GLOBAL_L, rocket_1.rect.centery))
else:
pygame.draw.line(screen, (231, 115, 38), (rocket_1.rect.centerx- 0.5*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx - 0.5*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx, rocket_1.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_1.rect.centerx+ 0.5*GLOBAL_L, rocket_1.rect.centery - 60),
(rocket_1.rect.centerx + 0.5*GLOBAL_L, rocket_1.rect.centery))
pygame.draw.line(screen, (231, 115, 38), (rocket_2.rect.centerx- 0.5*GLOBAL_L, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx - 0.5*GLOBAL_L, rocket_2.rect.centery))
pygame.draw.line(screen, (37, 153, 42), (rocket_2.rect.centerx, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx, rocket_2.rect.centery))
pygame.draw.line(screen, (39, 37, 153), (rocket_2.rect.centerx+ 0.5*GLOBAL_L, rocket_2.rect.centery - 60),
(rocket_2.rect.centerx + 0.5*GLOBAL_L, rocket_2.rect.centery))
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10, rocket_2.rect.centery - 10))
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 - 0.5*GLOBAL_L, rocket_2.rect.centery - 10))
screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 + 0.5*GLOBAL_L, rocket_2.rect.centery - 10))
if not GALILEO:
img_watchpick, rect_icon = img_load_icons(beta, img_watchpick, img_watchpick2)
rect_icon.centerx = rocket_1.rect.centerx
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx - 0.5*beta*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx + 0.5*beta*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
screen.blit(img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100))
screen.blit(img_a, (rocket_1.rect.centerx - 20 - 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_c, (rocket_1.rect.centerx - 20 + 0.5*beta*GLOBAL_L, rocket_1.rect.centery - 100))
else:
img_watchpick, rect_icon = img_load_icons(1, img_watchpick, img_watchpick2)
rect_icon.centerx = rocket_1.rect.centerx
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx - 0.5*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
rect_icon.centerx = rocket_1.rect.centerx + 0.5*GLOBAL_L
screen.blit(img_watchpick, rect_icon)
screen.blit(img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100))
screen.blit(img_a, (rocket_1.rect.centerx - 20 - 0.5*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_c, (rocket_1.rect.centerx - 20 + 0.5*GLOBAL_L, rocket_1.rect.centery - 100))
screen.blit(img_b, (rocket_2.rect.centerx - 20, rocket_2.rect.centery - 100))
screen.blit(img_a, (rocket_2.rect.centerx - 20 - 0.5*GLOBAL_L, rocket_2.rect.centery - 100))
screen.blit(img_c, (rocket_2.rect.centerx - 20 + 0.5*GLOBAL_L, rocket_2.rect.centery - 100))
frame1_pillar1_ind = (frame1_ind)*4
frame1_pillar2_ind = (frame1_ind)*4 + 1
frame1_pillar3_ind = (frame1_ind)*4 + 2
x, y = update_watchup(global_time)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + GLOBAL_L/2, 248, 102, 192), x, y)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + 1.5*GLOBAL_L, 248, 102, 192), x, y)
blitme_pillar(screen, BLACK, img_pillar_2, pygame.Rect(border-51 + 2.5*GLOBAL_L, 248, 102, 192), x, y)
text_1(str(frame1_pillar1_ind%100), BLACK,(border-6 + GLOBAL_L/2, 206))
text_1(str(frame1_pillar2_ind%100), BLACK,(border-6 + 1.5*GLOBAL_L, 206))
text_1(str(frame1_pillar3_ind%100), BLACK,(border-6 + 2.5*GLOBAL_L, 206))
str_time = time_to_string(global_time)
text_1('['+ str_time + ']', BLACK,(border-33 + GLOBAL_L/2, 225))
text_1('['+ str_time + ']', BLACK,(border-33 + 1.5*GLOBAL_L, 225))
text_1('['+ str_time + ']', BLACK,(border-33 + 2.5*GLOBAL_L, 225))
if not GALILEO:
a = math.ceil((-2*GLOBAL_L+alpha*GLOBAL_C*global_time)/beta/GLOBAL_L)
b = math.floor((2*GLOBAL_L+alpha*GLOBAL_C*global_time)/beta/GLOBAL_L+1)
img_pillar, rect_pillar = img_load(beta, img_pillar, img_pillar_2)
for ind in range(a, b+1):
frame2_pillar_x = beta*(ind-1)*GLOBAL_L-GLOBAL_C*alpha*global_time + 1.5*GLOBAL_L + border
frame2_pillar_time = beta*global_time + alpha*GLOBAL_L/GLOBAL_C*(ind - 1)
rect_pillar.centerx = frame2_pillar_x
x, y = update_watchdown(frame2_pillar_time, beta)
blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y)
text_1(str(ind%1000), BLACK,(rect_pillar.centerx - 6, 636))
str_time = time_to_string(frame2_pillar_time)
text_1('[' + str_time + ']', BLACK,(rect_pillar.centerx - 33, 655))
else:
a = math.ceil((-2*GLOBAL_L+alpha*GLOBAL_C*global_time)/GLOBAL_L)
b = math.floor((2*GLOBAL_L+alpha*GLOBAL_C*global_time)/GLOBAL_L+1)
img_pillar, rect_pillar = img_load(1, img_pillar, img_pillar_2)
for ind in range(a, b+1):
frame2_pillar_x = (ind-1)*GLOBAL_L-GLOBAL_C*alpha*global_time + 1.5*GLOBAL_L + border
frame2_pillar_time = global_time
rect_pillar.centerx = frame2_pillar_x
x, y = update_watchdown(frame2_pillar_time, beta)
blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y)
text_1(str(ind%1000), BLACK,(rect_pillar.centerx - 6, 636))
str_time = time_to_string(frame2_pillar_time)
text_1('[' + str_time + ']', BLACK,(rect_pillar.centerx - 33, 655))
if WIDTH != 1200:
screen.blit(background, screen_rect)
else:
screen.blit(back_left, (0,0))
screen.blit(back_centr, (30, 0))
screen.blit(back_right, (800,0))
bt_1.blitme()
if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_start.blitme()
else:
bt_start.blitmeclick()
if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_pause.blitmeclick()
else:
bt_pause.blitme()
if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_stop.blitme()
else:
bt_stop.blitmeclick()
if bt_left.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_left.blitme()
else:
bt_left.blitmeclick()
if bt_right.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True:
bt_right.blitme()
else:
bt_right.blitmeclick()
if not bt_galileo.flag:
bt_galileo.blitme()
else:
bt_galileo.blitmeclick()
watch1.blitme(BLACK)
watch2.blitme(BLACK)
watch3.blitme(BLACK)
watch4.blitme(BLACK)
watch5.blitme(BLACK)
watch6.blitme(BLACK)
if not GALILEO:
screen.blit(img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time1)
if WIDTH==1600:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48))
screen.blit(img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time2)
if WIDTH==1600:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48))
screen.blit(img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130))
str_time = time_to_string(frame1_rocket_time3)
if WIDTH==1600:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48))
screen.blit(img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130))
str_time = time_to_string(global_time)
if WIDTH==1600:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48))
screen.blit(img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48))
screen.blit(img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48))
else:
screen.blit(img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130))
str_time = time_to_string(global_time)
if WIDTH==1600:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48))
screen.blit(img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48))
screen.blit(img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48))
screen.blit(img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48))
screen.blit(img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48))
screen.blit(img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130))
if WIDTH==1600:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53))
if WIDTH==1440 or WIDTH==1200:
text_2(str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48))
if RUSENG:
text_4("START", BLACK, (bt_start.rect.centerx-30, bt_start.rect.centery-7))
text_4("PAUSE", BLACK, (bt_pause.rect.centerx-30, bt_pause.rect.centery-7))
text_4("STOP", BLACK, (bt_stop.rect.centerx-30, bt_stop.rect.centery-7))
text_2("Galilean", BLACK, (bt_galileo.rect.centerx-168, bt_galileo.rect.centery-18))
text_2("Transformation", BLACK, (bt_galileo.rect.centerx-168, bt_galileo.rect.centery +3))
text_2("Lorentz", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery-18))
text_2("Transformation", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery +3))
else:
text_2("СТАРТ", BLACK, (bt_start.rect.centerx-30, bt_start.rect.centery-10))
text_2("ПАУЗА", BLACK, (bt_pause.rect.centerx-30, bt_pause.rect.centery-10))
text_2("СТОП", BLACK, (bt_stop.rect.centerx-25, bt_stop.rect.centery-10))
text_2("Трансформация", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery-18))
text_2("Галилея", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery))
text_2("Трансформация", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery-18))
text_2("Лоренца", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery))
if RUSENG:
if WIDTH == 1600:
text_4("Velocity:", BLACK, (1370, 270))
text_4(str(round(alpha, 3)), BLACK, (1370, 310))
text_4("of light speed", BLACK, (1370, 350))
if WIDTH==1440 or WIDTH==1200:
text_4("Velocity:", BLACK, (WIDTH-140, 270))
text_4(str(round(alpha, 3)), BLACK, (WIDTH-140, 310))
text_4("of light", BLACK, (WIDTH-140, 350))
else:
if WIDTH == 1600:
text_1("Скорость:", BLACK, (1370, 270))
text_1(str(round(alpha, 3)), BLACK, (1370, 310))
text_1("скорости света", BLACK, (1370, 350))
if WIDTH==1440 or WIDTH==1200:
text_1("Скорость:", BLACK, (WIDTH-140, 270))
text_1(str(round(alpha, 3)), BLACK, (WIDTH-140, 310))
text_1("скорости света", BLACK, (WIDTH-140, 350))
else:
screen.blit(back_menu, screen_rect)
if INSTRUCTION:
os.startfile(r'STR_laba.pdf')
INSTRUCTION = False
if RUSENG:
text_5("New experiment", BLACK,(WIDTH-498,282))
text_5("New experiment", WHITE,(WIDTH-500,280))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350:
text_5("New experiment", RED,(WIDTH-500,280))
if MOUSE_KLICK:
MENU = False
text_5("Instruction", BLACK,(WIDTH-498,382))
text_5("Instruction", WHITE,(WIDTH-500,380))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450:
text_5("Instruction", RED,(WIDTH-500,380))
if MOUSE_KLICK:
INSTRUCTION = True
text_5("Autors", BLACK,(WIDTH-498,482))
text_5("Autors", WHITE,(WIDTH-500,480))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550:
text_5("Autors", RED,(WIDTH-500,480))
if MOUSE_KLICK:
AUTORS = True
text_5("Quit", BLACK,(WIDTH-498,582))
text_5("Quit", WHITE,(WIDTH-500,580))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650:
text_5("Quit", RED,(WIDTH-500,580))
if MOUSE_KLICK:
DONE = True
else:
text_5("Новый эксперимент", BLACK,(WIDTH-548,282))
text_5("Новый эксперимент", WHITE,(WIDTH-550,280))
if mouse_x >= WIDTH-500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350:
text_5("Новый эксперимент", RED,(WIDTH-550,280))
if MOUSE_KLICK:
MENU = False
text_5("Инструкция", BLACK,(WIDTH-548,382))
text_5("Инструкция", WHITE,(WIDTH-550,380))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450:
text_5("Инструкция", RED,(WIDTH-550,380))
if MOUSE_KLICK:
INSTRUCTION = True
text_5("Авторы", BLACK,(WIDTH-548,482))
text_5("Авторы", WHITE,(WIDTH-550,480))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550:
text_5("Авторы", RED,(WIDTH-550,480))
if MOUSE_KLICK:
AUTORS = True
text_5("Выход", BLACK,(WIDTH-548,582))
text_5("Выход", WHITE,(WIDTH-550,580))
if mouse_x >= WIDTH-550 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650:
text_5("Выход", RED,(WIDTH-550,580))
if MOUSE_KLICK:
DONE = True
if bt_ruseng.flag:
bt_ruseng.blitme()
else:
bt_ruseng.blitmeclick()
text_1("РУС", BLACK,(bt_ruseng.rect.centerx-55,bt_ruseng.rect.centery-10))
text_1("ENG", BLACK,(bt_ruseng.rect.centerx+30,bt_ruseng.rect.centery-10))
if bt_ruseng.rect.collidepoint(mouse_pos):
text_1("РУС", RED,(bt_ruseng.rect.centerx-55,bt_ruseng.rect.centery-10))
text_1("ENG", RED,(bt_ruseng.rect.centerx+30,bt_ruseng.rect.centery-10))
if AUTORS:
screen.blit(s, (0,0))
if not RUSENG:
text_1("Программирование", WHITE, (screen_rect.centerx-50,screen_rect.centery-150))
text_3("Кашников Александр МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery-120))
text_3("Киктенко Евгений МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery-90))
text_1("Расчеты", WHITE, (screen_rect.centerx-50, screen_rect.centery-60))
text_3("Киктенко Евгений", WHITE, (screen_rect.centerx-150, screen_rect.centery-30))
text_3("Кашников Александр", WHITE, (screen_rect.centerx-150, screen_rect.centery))
text_3("Гусманова Анастасия МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx-150, screen_rect.centery+30))
text_1("Графика", WHITE, (screen_rect.centerx-50, screen_rect.centery+60))
text_3("Кашников Александр", WHITE, (screen_rect.centerx-150, screen_rect.centery+90))
else:
text_1("programming", WHITE, (screen_rect.centerx-50,screen_rect.centery-150))
text_3("Kashnikov Alexander BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery-120))
text_3("Kiktenko Evgeniy BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery-90))
text_1("Calculations", WHITE, (screen_rect.centerx-50, screen_rect.centery-60))
text_3("Kiktenko Evgeniy", WHITE, (screen_rect.centerx-150, screen_rect.centery-30))
text_3("Kashnikov Alexander", WHITE, (screen_rect.centerx-150, screen_rect.centery))
text_3("Gusmanova Anastasiya BMSTU", WHITE, (screen_rect.centerx-150, screen_rect.centery+30))
text_1("Design", WHITE, (screen_rect.centerx-50, screen_rect.centery+60))
text_3("Kashnikov Alexander", WHITE, (screen_rect.centerx-150, screen_rect.centery+90))
clock.tick(60)
'''Go ahead and update the screen with what we've drawn.'''
pygame.display.flip()
run_game()
pygame.quit()
| false | true |
f71b891108d478f5ab27a7c4e1616fd4375c19ac | 5,222 | py | Python | codes/test.py | dvschultz/BasicSR | 69f360227f02cc86fa534a82ff969dd9084ac825 | [
"Apache-2.0"
] | null | null | null | codes/test.py | dvschultz/BasicSR | 69f360227f02cc86fa534a82ff969dd9084ac825 | [
"Apache-2.0"
] | null | null | null | codes/test.py | dvschultz/BasicSR | 69f360227f02cc86fa534a82ff969dd9084ac825 | [
"Apache-2.0"
] | null | null | null | import os.path as osp
import logging
import time
import argparse
from collections import OrderedDict
import options.options as option
import utils.util as util
from data.util import bgr2ycbcr
from data import create_dataset, create_dataloader
from models import create_model
#### options
parser = argparse.ArgumentParser()
parser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.')
opt = option.parse(parser.parse_args().opt, is_train=False)
opt = option.dict_to_nonedict(opt)
util.mkdirs(
(path for key, path in opt['path'].items()
if not key == 'experiments_root' and 'pretrain_model' not in key and 'resume' not in key))
util.setup_logger('base', opt['path']['log'], 'test_' + opt['name'], level=logging.INFO,
screen=True, tofile=True)
logger = logging.getLogger('base')
logger.info(option.dict2str(opt))
#### Create test dataset and dataloader
test_loaders = []
for phase, dataset_opt in sorted(opt['datasets'].items()):
test_set = create_dataset(dataset_opt)
test_loader = create_dataloader(test_set, dataset_opt)
logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set)))
test_loaders.append(test_loader)
model = create_model(opt)
for test_loader in test_loaders:
test_set_name = test_loader.dataset.opt['name']
logger.info('\nTesting [{:s}]...'.format(test_set_name))
test_start_time = time.time()
dataset_dir = osp.join(opt['path']['results_root'], test_set_name)
util.mkdir(dataset_dir)
test_results = OrderedDict()
test_results['psnr'] = []
test_results['ssim'] = []
test_results['psnr_y'] = []
test_results['ssim_y'] = []
for data in test_loader:
# need_GT = False if test_loader.dataset.opt['dataroot_GT'] is None else True
need_GT = False
model.feed_data(data, need_GT=need_GT)
img_path = data['GT_path'][0] if need_GT else data['LQ_path'][0]
img_name = osp.splitext(osp.basename(img_path))[0]
model.test()
visuals = model.get_current_visuals(need_GT=need_GT)
sr_img = util.tensor2img(visuals['SR']) # uint8
# save images
suffix = opt['suffix']
if suffix:
save_img_path = osp.join(dataset_dir, img_name + suffix + '.png')
else:
save_img_path = osp.join(dataset_dir, img_name + '.png')
util.save_img(sr_img, save_img_path)
# calculate PSNR and SSIM
if need_GT:
gt_img = util.tensor2img(visuals['GT'])
gt_img = gt_img / 255.
sr_img = sr_img / 255.
crop_border = opt['crop_border'] if opt['crop_border'] else opt['scale']
if crop_border == 0:
cropped_sr_img = sr_img
cropped_gt_img = gt_img
else:
cropped_sr_img = sr_img[crop_border:-crop_border, crop_border:-crop_border, :]
cropped_gt_img = gt_img[crop_border:-crop_border, crop_border:-crop_border, :]
psnr = util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255)
ssim = util.calculate_ssim(cropped_sr_img * 255, cropped_gt_img * 255)
test_results['psnr'].append(psnr)
test_results['ssim'].append(ssim)
if gt_img.shape[2] == 3: # RGB image
sr_img_y = bgr2ycbcr(sr_img, only_y=True)
gt_img_y = bgr2ycbcr(gt_img, only_y=True)
if crop_border == 0:
cropped_sr_img_y = sr_img_y
cropped_gt_img_y = gt_img_y
else:
cropped_sr_img_y = sr_img_y[crop_border:-crop_border, crop_border:-crop_border]
cropped_gt_img_y = gt_img_y[crop_border:-crop_border, crop_border:-crop_border]
psnr_y = util.calculate_psnr(cropped_sr_img_y * 255, cropped_gt_img_y * 255)
ssim_y = util.calculate_ssim(cropped_sr_img_y * 255, cropped_gt_img_y * 255)
test_results['psnr_y'].append(psnr_y)
test_results['ssim_y'].append(ssim_y)
logger.info(
'{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.
format(img_name, psnr, ssim, psnr_y, ssim_y))
else:
logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, psnr, ssim))
else:
logger.info(img_name)
if need_GT: # metrics
# Average PSNR/SSIM results
ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
logger.info(
'----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
test_set_name, ave_psnr, ave_ssim))
if test_results['psnr_y'] and test_results['ssim_y']:
ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
logger.info(
'----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'.
format(ave_psnr_y, ave_ssim_y))
| 42.803279 | 99 | 0.617771 | import os.path as osp
import logging
import time
import argparse
from collections import OrderedDict
import options.options as option
import utils.util as util
from data.util import bgr2ycbcr
from data import create_dataset, create_dataloader
from models import create_model
ser()
parser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.')
opt = option.parse(parser.parse_args().opt, is_train=False)
opt = option.dict_to_nonedict(opt)
util.mkdirs(
(path for key, path in opt['path'].items()
if not key == 'experiments_root' and 'pretrain_model' not in key and 'resume' not in key))
util.setup_logger('base', opt['path']['log'], 'test_' + opt['name'], level=logging.INFO,
screen=True, tofile=True)
logger = logging.getLogger('base')
logger.info(option.dict2str(opt))
aset_opt)
test_loader = create_dataloader(test_set, dataset_opt)
logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set)))
test_loaders.append(test_loader)
model = create_model(opt)
for test_loader in test_loaders:
test_set_name = test_loader.dataset.opt['name']
logger.info('\nTesting [{:s}]...'.format(test_set_name))
test_start_time = time.time()
dataset_dir = osp.join(opt['path']['results_root'], test_set_name)
util.mkdir(dataset_dir)
test_results = OrderedDict()
test_results['psnr'] = []
test_results['ssim'] = []
test_results['psnr_y'] = []
test_results['ssim_y'] = []
for data in test_loader:
need_GT = False
model.feed_data(data, need_GT=need_GT)
img_path = data['GT_path'][0] if need_GT else data['LQ_path'][0]
img_name = osp.splitext(osp.basename(img_path))[0]
model.test()
visuals = model.get_current_visuals(need_GT=need_GT)
sr_img = util.tensor2img(visuals['SR'])
suffix = opt['suffix']
if suffix:
save_img_path = osp.join(dataset_dir, img_name + suffix + '.png')
else:
save_img_path = osp.join(dataset_dir, img_name + '.png')
util.save_img(sr_img, save_img_path)
if need_GT:
gt_img = util.tensor2img(visuals['GT'])
gt_img = gt_img / 255.
sr_img = sr_img / 255.
crop_border = opt['crop_border'] if opt['crop_border'] else opt['scale']
if crop_border == 0:
cropped_sr_img = sr_img
cropped_gt_img = gt_img
else:
cropped_sr_img = sr_img[crop_border:-crop_border, crop_border:-crop_border, :]
cropped_gt_img = gt_img[crop_border:-crop_border, crop_border:-crop_border, :]
psnr = util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255)
ssim = util.calculate_ssim(cropped_sr_img * 255, cropped_gt_img * 255)
test_results['psnr'].append(psnr)
test_results['ssim'].append(ssim)
if gt_img.shape[2] == 3:
sr_img_y = bgr2ycbcr(sr_img, only_y=True)
gt_img_y = bgr2ycbcr(gt_img, only_y=True)
if crop_border == 0:
cropped_sr_img_y = sr_img_y
cropped_gt_img_y = gt_img_y
else:
cropped_sr_img_y = sr_img_y[crop_border:-crop_border, crop_border:-crop_border]
cropped_gt_img_y = gt_img_y[crop_border:-crop_border, crop_border:-crop_border]
psnr_y = util.calculate_psnr(cropped_sr_img_y * 255, cropped_gt_img_y * 255)
ssim_y = util.calculate_ssim(cropped_sr_img_y * 255, cropped_gt_img_y * 255)
test_results['psnr_y'].append(psnr_y)
test_results['ssim_y'].append(ssim_y)
logger.info(
'{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.
format(img_name, psnr, ssim, psnr_y, ssim_y))
else:
logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, psnr, ssim))
else:
logger.info(img_name)
if need_GT:
ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])
ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])
logger.info(
'----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(
test_set_name, ave_psnr, ave_ssim))
if test_results['psnr_y'] and test_results['ssim_y']:
ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])
ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])
logger.info(
'----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'.
format(ave_psnr_y, ave_ssim_y))
| true | true |
f71b8944d7cb24a8c9e0c2e8ab0e255b732516de | 11,057 | py | Python | script/gen_requirements_all.py | TheDatNik/home-assistant | 12b451adf5e5e894cb0707b61535218260411189 | [
"Apache-2.0"
] | 2 | 2019-07-31T16:09:15.000Z | 2019-09-05T08:07:12.000Z | script/gen_requirements_all.py | TheDatNik/home-assistant | 12b451adf5e5e894cb0707b61535218260411189 | [
"Apache-2.0"
] | 2 | 2022-01-13T04:00:03.000Z | 2022-03-12T01:02:40.000Z | script/gen_requirements_all.py | TheDatNik/home-assistant | 12b451adf5e5e894cb0707b61535218260411189 | [
"Apache-2.0"
] | 2 | 2017-10-16T07:55:03.000Z | 2019-10-07T21:26:20.000Z | #!/usr/bin/env python3
"""Generate an updated requirements_all.txt."""
import fnmatch
import importlib
import os
import pathlib
import pkgutil
import re
import sys
from script.hassfest.model import Integration
COMMENT_REQUIREMENTS = (
'Adafruit-DHT',
'Adafruit_BBIO',
'avion',
'beacontools',
'blinkt',
'bluepy',
'bme680',
'credstash',
'decora',
'envirophat',
'evdev',
'face_recognition',
'fritzconnection',
'i2csense',
'opencv-python',
'py_noaa',
'VL53L1X2',
'pybluez',
'pycups',
'PySwitchbot',
'pySwitchmate',
'python-eq3bt',
'python-lirc',
'pyuserinput',
'raspihats',
'rpi-rf',
'RPi.GPIO',
'smbus-cffi',
)
TEST_REQUIREMENTS = (
'aioambient',
'aioautomatic',
'aiobotocore',
'aiohttp_cors',
'aiohue',
'aiounifi',
'apns2',
'av',
'axis',
'caldav',
'coinmarketcap',
'defusedxml',
'dsmr_parser',
'eebrightbox',
'emulated_roku',
'ephem',
'evohomeclient',
'feedparser-homeassistant',
'foobot_async',
'geojson_client',
'georss_generic_client',
'georss_ign_sismologia_client',
'google-api-python-client',
'gTTS-token',
'ha-ffmpeg',
'hangups',
'HAP-python',
'hass-nabucasa',
'haversine',
'hbmqtt',
'hdate',
'holidays',
'home-assistant-frontend',
'homekit[IP]',
'homematicip',
'httplib2',
'influxdb',
'jsonpath',
'libpurecool',
'libsoundtouch',
'luftdaten',
'mbddns',
'mficlient',
'numpy',
'oauth2client',
'paho-mqtt',
'pexpect',
'pilight',
'pmsensor',
'prometheus_client',
'pushbullet.py',
'py-canary',
'pyblackbird',
'pydeconz',
'pydispatcher',
'pyheos',
'pyhomematic',
'pylitejet',
'pymonoprice',
'pynx584',
'pyopenuv',
'pyotp',
'pyps4-homeassistant',
'pysmartapp',
'pysmartthings',
'pysonos',
'pyqwikswitch',
'PyRMVtransport',
'PyTransportNSW',
'pyspcwebgw',
'python-forecastio',
'python-nest',
'python_awair',
'pytradfri[async]',
'pyunifi',
'pyupnp-async',
'pywebpush',
'pyHS100',
'PyNaCl',
'regenmaschine',
'restrictedpython',
'rflink',
'ring_doorbell',
'rxv',
'simplisafe-python',
'sleepyq',
'smhi-pkg',
'somecomfort',
'sqlalchemy',
'srpenergy',
'statsd',
'toonapilib',
'uvcclient',
'vsure',
'warrant',
'pythonwhois',
'wakeonlan',
'vultr',
'YesssSMS',
'ruamel.yaml',
'zigpy-homeassistant',
'bellows-homeassistant',
)
IGNORE_PACKAGES = (
'homeassistant.components.hangouts.hangups_utils',
'homeassistant.components.cloud.client',
'homeassistant.components.homekit.*',
'homeassistant.components.recorder.models',
)
IGNORE_PIN = ('colorlog>2.1,<3', 'keyring>=9.3,<10.0', 'urllib3')
IGNORE_REQ = (
'colorama<=1', # Windows only requirement in check_config
)
URL_PIN = ('https://developers.home-assistant.io/docs/'
'creating_platform_code_review.html#1-requirements')
CONSTRAINT_PATH = os.path.join(os.path.dirname(__file__),
'../homeassistant/package_constraints.txt')
CONSTRAINT_BASE = """
pycryptodome>=3.6.6
# Breaks Python 3.6 and is not needed for our supported Python versions
enum34==1000000000.0.0
# This is a old unmaintained library and is replaced with pycryptodome
pycrypto==1000000000.0.0
# Contains code to modify Home Assistant to work around our rules
python-systemair-savecair==1000000000.0.0
# Newer version causes pylint to take forever
# https://github.com/timothycrosley/isort/issues/848
isort==4.3.4
"""
def explore_module(package, explore_children):
"""Explore the modules."""
module = importlib.import_module(package)
found = []
if not hasattr(module, '__path__'):
return found
for _, name, _ in pkgutil.iter_modules(module.__path__, package + '.'):
found.append(name)
if explore_children:
found.extend(explore_module(name, False))
return found
def core_requirements():
"""Gather core requirements out of setup.py."""
with open('setup.py') as inp:
reqs_raw = re.search(
r'REQUIRES = \[(.*?)\]', inp.read(), re.S).group(1)
return re.findall(r"'(.*?)'", reqs_raw)
def comment_requirement(req):
"""Comment out requirement. Some don't install on all systems."""
return any(ign in req for ign in COMMENT_REQUIREMENTS)
def gather_modules():
"""Collect the information."""
reqs = {}
errors = []
gather_requirements_from_manifests(errors, reqs)
gather_requirements_from_modules(errors, reqs)
for key in reqs:
reqs[key] = sorted(reqs[key],
key=lambda name: (len(name.split('.')), name))
if errors:
print("******* ERROR")
print("Errors while importing: ", ', '.join(errors))
print("Make sure you import 3rd party libraries inside methods.")
return None
return reqs
def gather_requirements_from_manifests(errors, reqs):
"""Gather all of the requirements from manifests."""
integrations = Integration.load_dir(pathlib.Path(
'homeassistant/components'
))
for domain in sorted(integrations):
integration = integrations[domain]
if not integration.manifest:
errors.append(
'The manifest for component {} is invalid.'.format(domain)
)
continue
process_requirements(
errors,
integration.manifest['requirements'],
'homeassistant.components.{}'.format(domain),
reqs
)
def gather_requirements_from_modules(errors, reqs):
"""Collect the requirements from the modules directly."""
for package in sorted(
explore_module('homeassistant.scripts', True) +
explore_module('homeassistant.auth', True)):
try:
module = importlib.import_module(package)
except ImportError as err:
for pattern in IGNORE_PACKAGES:
if fnmatch.fnmatch(package, pattern):
break
else:
print("{}: {}".format(package.replace('.', '/') + '.py', err))
errors.append(package)
continue
if getattr(module, 'REQUIREMENTS', None):
process_requirements(errors, module.REQUIREMENTS, package, reqs)
def process_requirements(errors, module_requirements, package, reqs):
"""Process all of the requirements."""
for req in module_requirements:
if req in IGNORE_REQ:
continue
if '://' in req:
errors.append(
"{}[Only pypi dependencies are allowed: {}]".format(
package, req))
if req.partition('==')[1] == '' and req not in IGNORE_PIN:
errors.append(
"{}[Please pin requirement {}, see {}]".format(
package, req, URL_PIN))
reqs.setdefault(req, []).append(package)
def generate_requirements_list(reqs):
"""Generate a pip file based on requirements."""
output = []
for pkg, requirements in sorted(reqs.items(), key=lambda item: item[0]):
for req in sorted(requirements):
output.append('\n# {}'.format(req))
if comment_requirement(pkg):
output.append('\n# {}\n'.format(pkg))
else:
output.append('\n{}\n'.format(pkg))
return ''.join(output)
def requirements_all_output(reqs):
"""Generate output for requirements_all."""
output = []
output.append('# Home Assistant core')
output.append('\n')
output.append('\n'.join(core_requirements()))
output.append('\n')
output.append(generate_requirements_list(reqs))
return ''.join(output)
def requirements_test_output(reqs):
"""Generate output for test_requirements."""
output = []
output.append('# Home Assistant test')
output.append('\n')
with open('requirements_test.txt') as test_file:
output.append(test_file.read())
output.append('\n')
filtered = {key: value for key, value in reqs.items()
if any(
re.search(r'(^|#){}($|[=><])'.format(re.escape(ign)),
key) is not None for ign in TEST_REQUIREMENTS)}
output.append(generate_requirements_list(filtered))
return ''.join(output)
def gather_constraints():
"""Construct output for constraint file."""
return '\n'.join(core_requirements() + [''])
def write_requirements_file(data):
"""Write the modules to the requirements_all.txt."""
with open('requirements_all.txt', 'w+', newline="\n") as req_file:
req_file.write(data)
def write_test_requirements_file(data):
"""Write the modules to the requirements_test_all.txt."""
with open('requirements_test_all.txt', 'w+', newline="\n") as req_file:
req_file.write(data)
def write_constraints_file(data):
"""Write constraints to a file."""
with open(CONSTRAINT_PATH, 'w+', newline="\n") as req_file:
req_file.write(data + CONSTRAINT_BASE)
def validate_requirements_file(data):
"""Validate if requirements_all.txt is up to date."""
with open('requirements_all.txt', 'r') as req_file:
return data == req_file.read()
def validate_requirements_test_file(data):
"""Validate if requirements_test_all.txt is up to date."""
with open('requirements_test_all.txt', 'r') as req_file:
return data == req_file.read()
def validate_constraints_file(data):
"""Validate if constraints is up to date."""
with open(CONSTRAINT_PATH, 'r') as req_file:
return data + CONSTRAINT_BASE == req_file.read()
def main(validate):
"""Run the script."""
if not os.path.isfile('requirements_all.txt'):
print('Run this from HA root dir')
return 1
data = gather_modules()
if data is None:
return 1
constraints = gather_constraints()
reqs_file = requirements_all_output(data)
reqs_test_file = requirements_test_output(data)
if validate:
errors = []
if not validate_requirements_file(reqs_file):
errors.append("requirements_all.txt is not up to date")
if not validate_requirements_test_file(reqs_test_file):
errors.append("requirements_test_all.txt is not up to date")
if not validate_constraints_file(constraints):
errors.append(
"home-assistant/package_constraints.txt is not up to date")
if errors:
print("******* ERROR")
print('\n'.join(errors))
print("Please run script/gen_requirements_all.py")
return 1
return 0
write_requirements_file(reqs_file)
write_test_requirements_file(reqs_test_file)
write_constraints_file(constraints)
return 0
if __name__ == '__main__':
_VAL = sys.argv[-1] == 'validate'
sys.exit(main(_VAL))
| 25.955399 | 78 | 0.617889 |
import fnmatch
import importlib
import os
import pathlib
import pkgutil
import re
import sys
from script.hassfest.model import Integration
COMMENT_REQUIREMENTS = (
'Adafruit-DHT',
'Adafruit_BBIO',
'avion',
'beacontools',
'blinkt',
'bluepy',
'bme680',
'credstash',
'decora',
'envirophat',
'evdev',
'face_recognition',
'fritzconnection',
'i2csense',
'opencv-python',
'py_noaa',
'VL53L1X2',
'pybluez',
'pycups',
'PySwitchbot',
'pySwitchmate',
'python-eq3bt',
'python-lirc',
'pyuserinput',
'raspihats',
'rpi-rf',
'RPi.GPIO',
'smbus-cffi',
)
TEST_REQUIREMENTS = (
'aioambient',
'aioautomatic',
'aiobotocore',
'aiohttp_cors',
'aiohue',
'aiounifi',
'apns2',
'av',
'axis',
'caldav',
'coinmarketcap',
'defusedxml',
'dsmr_parser',
'eebrightbox',
'emulated_roku',
'ephem',
'evohomeclient',
'feedparser-homeassistant',
'foobot_async',
'geojson_client',
'georss_generic_client',
'georss_ign_sismologia_client',
'google-api-python-client',
'gTTS-token',
'ha-ffmpeg',
'hangups',
'HAP-python',
'hass-nabucasa',
'haversine',
'hbmqtt',
'hdate',
'holidays',
'home-assistant-frontend',
'homekit[IP]',
'homematicip',
'httplib2',
'influxdb',
'jsonpath',
'libpurecool',
'libsoundtouch',
'luftdaten',
'mbddns',
'mficlient',
'numpy',
'oauth2client',
'paho-mqtt',
'pexpect',
'pilight',
'pmsensor',
'prometheus_client',
'pushbullet.py',
'py-canary',
'pyblackbird',
'pydeconz',
'pydispatcher',
'pyheos',
'pyhomematic',
'pylitejet',
'pymonoprice',
'pynx584',
'pyopenuv',
'pyotp',
'pyps4-homeassistant',
'pysmartapp',
'pysmartthings',
'pysonos',
'pyqwikswitch',
'PyRMVtransport',
'PyTransportNSW',
'pyspcwebgw',
'python-forecastio',
'python-nest',
'python_awair',
'pytradfri[async]',
'pyunifi',
'pyupnp-async',
'pywebpush',
'pyHS100',
'PyNaCl',
'regenmaschine',
'restrictedpython',
'rflink',
'ring_doorbell',
'rxv',
'simplisafe-python',
'sleepyq',
'smhi-pkg',
'somecomfort',
'sqlalchemy',
'srpenergy',
'statsd',
'toonapilib',
'uvcclient',
'vsure',
'warrant',
'pythonwhois',
'wakeonlan',
'vultr',
'YesssSMS',
'ruamel.yaml',
'zigpy-homeassistant',
'bellows-homeassistant',
)
IGNORE_PACKAGES = (
'homeassistant.components.hangouts.hangups_utils',
'homeassistant.components.cloud.client',
'homeassistant.components.homekit.*',
'homeassistant.components.recorder.models',
)
IGNORE_PIN = ('colorlog>2.1,<3', 'keyring>=9.3,<10.0', 'urllib3')
IGNORE_REQ = (
'colorama<=1',
)
URL_PIN = ('https://developers.home-assistant.io/docs/'
'creating_platform_code_review.html#1-requirements')
CONSTRAINT_PATH = os.path.join(os.path.dirname(__file__),
'../homeassistant/package_constraints.txt')
CONSTRAINT_BASE = """
pycryptodome>=3.6.6
# Breaks Python 3.6 and is not needed for our supported Python versions
enum34==1000000000.0.0
# This is a old unmaintained library and is replaced with pycryptodome
pycrypto==1000000000.0.0
# Contains code to modify Home Assistant to work around our rules
python-systemair-savecair==1000000000.0.0
# Newer version causes pylint to take forever
# https://github.com/timothycrosley/isort/issues/848
isort==4.3.4
"""
def explore_module(package, explore_children):
module = importlib.import_module(package)
found = []
if not hasattr(module, '__path__'):
return found
for _, name, _ in pkgutil.iter_modules(module.__path__, package + '.'):
found.append(name)
if explore_children:
found.extend(explore_module(name, False))
return found
def core_requirements():
with open('setup.py') as inp:
reqs_raw = re.search(
r'REQUIRES = \[(.*?)\]', inp.read(), re.S).group(1)
return re.findall(r"'(.*?)'", reqs_raw)
def comment_requirement(req):
return any(ign in req for ign in COMMENT_REQUIREMENTS)
def gather_modules():
reqs = {}
errors = []
gather_requirements_from_manifests(errors, reqs)
gather_requirements_from_modules(errors, reqs)
for key in reqs:
reqs[key] = sorted(reqs[key],
key=lambda name: (len(name.split('.')), name))
if errors:
print("******* ERROR")
print("Errors while importing: ", ', '.join(errors))
print("Make sure you import 3rd party libraries inside methods.")
return None
return reqs
def gather_requirements_from_manifests(errors, reqs):
integrations = Integration.load_dir(pathlib.Path(
'homeassistant/components'
))
for domain in sorted(integrations):
integration = integrations[domain]
if not integration.manifest:
errors.append(
'The manifest for component {} is invalid.'.format(domain)
)
continue
process_requirements(
errors,
integration.manifest['requirements'],
'homeassistant.components.{}'.format(domain),
reqs
)
def gather_requirements_from_modules(errors, reqs):
for package in sorted(
explore_module('homeassistant.scripts', True) +
explore_module('homeassistant.auth', True)):
try:
module = importlib.import_module(package)
except ImportError as err:
for pattern in IGNORE_PACKAGES:
if fnmatch.fnmatch(package, pattern):
break
else:
print("{}: {}".format(package.replace('.', '/') + '.py', err))
errors.append(package)
continue
if getattr(module, 'REQUIREMENTS', None):
process_requirements(errors, module.REQUIREMENTS, package, reqs)
def process_requirements(errors, module_requirements, package, reqs):
for req in module_requirements:
if req in IGNORE_REQ:
continue
if '://' in req:
errors.append(
"{}[Only pypi dependencies are allowed: {}]".format(
package, req))
if req.partition('==')[1] == '' and req not in IGNORE_PIN:
errors.append(
"{}[Please pin requirement {}, see {}]".format(
package, req, URL_PIN))
reqs.setdefault(req, []).append(package)
def generate_requirements_list(reqs):
output = []
for pkg, requirements in sorted(reqs.items(), key=lambda item: item[0]):
for req in sorted(requirements):
output.append('\n# {}'.format(req))
if comment_requirement(pkg):
output.append('\n# {}\n'.format(pkg))
else:
output.append('\n{}\n'.format(pkg))
return ''.join(output)
def requirements_all_output(reqs):
output = []
output.append('# Home Assistant core')
output.append('\n')
output.append('\n'.join(core_requirements()))
output.append('\n')
output.append(generate_requirements_list(reqs))
return ''.join(output)
def requirements_test_output(reqs):
output = []
output.append('# Home Assistant test')
output.append('\n')
with open('requirements_test.txt') as test_file:
output.append(test_file.read())
output.append('\n')
filtered = {key: value for key, value in reqs.items()
if any(
re.search(r'(^|#){}($|[=><])'.format(re.escape(ign)),
key) is not None for ign in TEST_REQUIREMENTS)}
output.append(generate_requirements_list(filtered))
return ''.join(output)
def gather_constraints():
return '\n'.join(core_requirements() + [''])
def write_requirements_file(data):
with open('requirements_all.txt', 'w+', newline="\n") as req_file:
req_file.write(data)
def write_test_requirements_file(data):
with open('requirements_test_all.txt', 'w+', newline="\n") as req_file:
req_file.write(data)
def write_constraints_file(data):
with open(CONSTRAINT_PATH, 'w+', newline="\n") as req_file:
req_file.write(data + CONSTRAINT_BASE)
def validate_requirements_file(data):
with open('requirements_all.txt', 'r') as req_file:
return data == req_file.read()
def validate_requirements_test_file(data):
with open('requirements_test_all.txt', 'r') as req_file:
return data == req_file.read()
def validate_constraints_file(data):
with open(CONSTRAINT_PATH, 'r') as req_file:
return data + CONSTRAINT_BASE == req_file.read()
def main(validate):
if not os.path.isfile('requirements_all.txt'):
print('Run this from HA root dir')
return 1
data = gather_modules()
if data is None:
return 1
constraints = gather_constraints()
reqs_file = requirements_all_output(data)
reqs_test_file = requirements_test_output(data)
if validate:
errors = []
if not validate_requirements_file(reqs_file):
errors.append("requirements_all.txt is not up to date")
if not validate_requirements_test_file(reqs_test_file):
errors.append("requirements_test_all.txt is not up to date")
if not validate_constraints_file(constraints):
errors.append(
"home-assistant/package_constraints.txt is not up to date")
if errors:
print("******* ERROR")
print('\n'.join(errors))
print("Please run script/gen_requirements_all.py")
return 1
return 0
write_requirements_file(reqs_file)
write_test_requirements_file(reqs_test_file)
write_constraints_file(constraints)
return 0
if __name__ == '__main__':
_VAL = sys.argv[-1] == 'validate'
sys.exit(main(_VAL))
| true | true |
f71b8a631ab134a126402e2d0c05bb00449922c8 | 150,997 | py | Python | fastkml/test_main.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 1 | 2021-02-05T19:50:13.000Z | 2021-02-05T19:50:13.000Z | fastkml/test_main.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 59 | 2020-06-17T22:21:51.000Z | 2022-02-10T05:00:01.000Z | fastkml/test_main.py | dennereed/paleocore | d6da6c39cde96050ee4b9e7213ec1200530cbeee | [
"MIT"
] | 2 | 2020-07-01T14:11:09.000Z | 2020-08-10T17:27:26.000Z | # -*- coding: utf-8 -*-
# Copyright (C) 2012 Christian Ledermann
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
try:
import unittest2 as unittest # Needed in Python 2.6
except:
import unittest
from fastkml import kml
from fastkml import styles
from fastkml import base
from fastkml import atom
from fastkml import config
from fastkml import gx # NOQA
import datetime
from dateutil.tz import tzutc, tzoffset
from fastkml.config import etree
from fastkml.geometry import Point, LineString, Polygon
from fastkml.geometry import MultiPoint, MultiLineString, MultiPolygon
from fastkml.geometry import LinearRing, GeometryCollection
from fastkml.geometry import Geometry
class BaseClassesTestCase(unittest.TestCase):
""" BaseClasses must raise a NotImplementedError on etree_element
and a TypeError on from_element """
def test_base_object(self):
bo = base._BaseObject(id='id0')
self.assertEqual(bo.id, 'id0')
self.assertEqual(bo.ns, config.NS)
self.assertEqual(bo.targetId, None)
self.assertEqual(bo.__name__, None)
bo.targetId = 'target'
self.assertEqual(bo.targetId, 'target')
bo.ns = ''
bo.id = None
self.assertEqual(bo.id, None)
self.assertEqual(bo.ns, '')
self.assertRaises(NotImplementedError, bo.etree_element)
element = etree.Element(config.NS + 'Base')
self.assertRaises(TypeError, bo.from_element)
self.assertRaises(TypeError, bo.from_element, element)
bo.__name__ = 'NotABaseObject'
self.assertRaises(TypeError, bo.from_element, element)
# Note that we can coax baseclasses not to throw errors
bo.__name__ = 'Base'
bo.ns = config.NS
bo.from_element(element)
self.assertEqual(bo.id, None)
self.assertEqual(bo.ns, config.NS)
self.assertFalse(bo.etree_element(), None)
self.assertTrue(len(bo.to_string()) > 1)
def test_feature(self):
f = kml._Feature(name='A Feature')
self.assertRaises(NotImplementedError, f.etree_element)
self.assertEqual(f.name, 'A Feature')
self.assertEqual(f.visibility, 1)
self.assertEqual(f.isopen, 0)
self.assertEqual(f._atom_author, None)
self.assertEqual(f._atom_link, None)
self.assertEqual(f.address, None)
# self.assertEqual(f.phoneNumber, None)
self.assertEqual(f._snippet, None)
self.assertEqual(f.description, None)
self.assertEqual(f._styleUrl, None)
self.assertEqual(f._styles, [])
self.assertEqual(f._time_span, None)
self.assertEqual(f._time_stamp, None)
# self.assertEqual(f.region, None)
# self.assertEqual(f.extended_data, None)
f.__name__ = 'Feature'
f.styleUrl = '#default'
self.assertTrue('Feature>' in str(f.to_string()))
self.assertTrue('#default' in str(f.to_string()))
def test_container(self):
f = kml._Container(name='A Container')
# apparently you can add documents to containes
# d = kml.Document()
# self.assertRaises(TypeError, f.append, d)
p = kml.Placemark()
f.append(p)
self.assertRaises(NotImplementedError, f.etree_element)
def test_overlay(self):
o = kml._Overlay(name='An Overlay')
self.assertEqual(o._color, None)
self.assertEqual(o._drawOrder, None)
self.assertEqual(o._icon, None)
self.assertRaises(NotImplementedError, o.etree_element)
def test_atom_link(self):
ns = '{http://www.opengis.net/kml/2.2}'
l = atom.Link(ns=ns)
self.assertEqual(l.ns, ns)
def test_atom_person(self):
ns = '{http://www.opengis.net/kml/2.2}'
p = atom._Person(ns=ns)
self.assertEqual(p.ns, ns)
class BuildKmlTestCase(unittest.TestCase):
""" Build a simple KML File """
def test_kml(self):
""" kml file without contents """
k = kml.KML()
self.assertEqual(len(list(k.features())), 0)
if config.LXML:
self.assertEqual(
str(k.to_string())[:43],
'<kml xmlns="http://www.opengis.net/kml/2.2"/>' [:43])
else:
if hasattr(etree, 'register_namespace'):
self.assertEqual(str(k.to_string())[:51], '<kml:kml xmlns:kml="http://www.opengis.net/kml/2.2" />'[:51])
else:
self.assertEqual(str(k.to_string())[:51], '<ns0:kml xmlns:ns0="http://www.opengis.net/kml/2.2" />'[:51])
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_folder(self):
""" KML file with folders """
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML()
f = kml.Folder(ns, 'id', 'name', 'description')
nf = kml.Folder(ns, 'nested-id', 'nested-name', 'nested-description')
f.append(nf)
k.append(f)
f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
k.append(f2)
self.assertEqual(len(list(k.features())), 2)
self.assertEqual(len(list(list(k.features())[0].features())), 1)
k2 = kml.KML()
s = k.to_string()
k2.from_string(s)
self.assertEqual(s, k2.to_string())
def test_placemark(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Point(0.0, 0.0, 0.0)
p2 = kml.Placemark(ns, 'id2', 'name2', 'description2')
p2.geometry = LineString([(0, 0, 0), (1, 1, 1)])
k.append(p)
k.append(p2)
self.assertEqual(len(list(k.features())), 2)
k2 = kml.KML()
k2.from_string(k.to_string(prettyprint=True))
self.assertEqual(k.to_string(), k2.to_string())
def test_schema(self):
ns = '{http://www.opengis.net/kml/2.2}'
self.assertRaises(ValueError, kml.Schema, ns)
s = kml.Schema(ns, 'some_id')
self.assertEqual(len(list(s.simple_fields)), 0)
s.append('int', 'Integer', 'An Integer')
self.assertEqual(list(s.simple_fields)[0]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[0]['displayName'], 'An Integer')
s.simple_fields = None
self.assertEqual(len(list(s.simple_fields)), 0)
self.assertRaises(
TypeError, s.append, ('none', 'Integer', 'An Integer'))
self.assertRaises(
TypeError, s.simple_fields, [('none', 'Integer', 'An Integer')])
self.assertRaises(
TypeError, s.simple_fields, ('int', 'Integer', 'An Integer'))
fields = {
'type': 'int',
'name': 'Integer',
'displayName': 'An Integer'
}
s.simple_fields = fields
self.assertEqual(list(s.simple_fields)[0]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[0]['displayName'], 'An Integer')
s.simple_fields = [['float', 'Float'], fields]
self.assertEqual(list(s.simple_fields)[0]['type'], 'float')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Float')
self.assertEqual(list(s.simple_fields)[0]['displayName'], None)
self.assertEqual(list(s.simple_fields)[1]['type'], 'int')
self.assertEqual(list(s.simple_fields)[1]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[1]['displayName'], 'An Integer')
def test_schema_data(self):
ns = '{http://www.opengis.net/kml/2.2}'
self.assertRaises(ValueError, kml.SchemaData, ns)
self.assertRaises(ValueError, kml.SchemaData, ns, '')
sd = kml.SchemaData(ns, '#default')
sd.append_data('text', 'Some Text')
self.assertEqual(len(sd.data), 1)
sd.append_data(value=1, name='Integer')
self.assertEqual(len(sd.data), 2)
self.assertEqual(sd.data[0], {'value': 'Some Text', 'name': 'text'})
self.assertEqual(sd.data[1], {'value': 1, 'name': 'Integer'})
data = (('text', 'Some new Text'), {'value': 2, 'name': 'Integer'})
sd.data = data
self.assertEqual(len(sd.data), 2)
self.assertEqual(
sd.data[0], {'value': 'Some new Text',
'name': 'text'})
self.assertEqual(sd.data[1], {'value': 2, 'name': 'Integer'})
def test_untyped_extended_data(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Point(0.0, 0.0, 0.0)
p.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(
name='info',
value='so much to see'), kml.UntypedExtendedDataElement(
name='weather',
display_name='Weather',
value='blue skies')
])
self.assertEqual(len(p.extended_data.elements), 2)
k.append(p)
k2 = kml.KML()
k2.from_string(k.to_string(prettyprint=True))
k.to_string()
extended_data = list(k2.features())[0].extended_data
self.assertTrue(extended_data is not None)
self.assertTrue(len(extended_data.elements), 2)
self.assertEqual(extended_data.elements[0].name, 'info')
self.assertEqual(extended_data.elements[0].value, 'so much to see')
self.assertEqual(extended_data.elements[0].display_name, None)
self.assertEqual(extended_data.elements[1].name, 'weather')
self.assertEqual(extended_data.elements[1].value, 'blue skies')
self.assertEqual(extended_data.elements[1].display_name, 'Weather')
def test_untyped_extended_data_nested(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
d = kml.Document(ns, 'docid', 'doc name', 'doc description')
d.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(name='type',
value='Document')
])
f = kml.Folder(ns, 'fid', 'f name', 'f description')
f.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(name='type',
value='Folder')
])
k.append(d)
d.append(f)
k2 = kml.KML()
k2.from_string(k.to_string())
document_data = list(k2.features())[0].extended_data
folder_data = list(list(k2.features())[0].features())[0].extended_data
self.assertEqual(document_data.elements[0].name, 'type')
self.assertEqual(document_data.elements[0].value, 'Document')
self.assertEqual(folder_data.elements[0].name, 'type')
self.assertEqual(folder_data.elements[0].value, 'Folder')
def test_document(self):
k = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'
d = kml.Document(ns, 'docid', 'doc name', 'doc description')
f = kml.Folder(ns, 'fid', 'f name', 'f description')
k.append(d)
d.append(f)
nf = kml.Folder(
ns, 'nested-fid', 'nested f name', 'nested f description')
f.append(nf)
f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
d.append(f2)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 1)])
p2 = kml.Placemark(ns, 'id2', 'name2', 'description2')
# p2 does not have a geometry!
f2.append(p)
nf.append(p2)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list((list(k.features())[0].features()))), 2)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_author(self):
d = kml.Document()
d.author = 'Christian Ledermann'
self.assertTrue('Christian Ledermann' in str(d.to_string()))
a = atom.Author(
name='Nobody',
uri='http://localhost',
email='cl@donotreply.com')
d.author = a
self.assertEqual(d.author, 'Nobody')
self.assertFalse('Christian Ledermann' in str(d.to_string()))
self.assertTrue('Nobody' in str(d.to_string()))
self.assertTrue('http://localhost' in str(d.to_string()))
self.assertTrue('cl@donotreply.com' in str(d.to_string()))
d2 = kml.Document()
d2.from_string(d.to_string())
self.assertEqual(d.to_string(), d2.to_string())
d.author = None
def test_link(self):
d = kml.Document()
d.link = 'http://localhost'
self.assertTrue('http://localhost' in str(d.to_string()))
l = atom.Link(href='#here')
d.link = l
self.assertTrue('#here' in str(d.to_string()))
self.assertRaises(TypeError, d.link, object)
d2 = kml.Document()
d2.from_string(d.to_string())
self.assertEqual(d.to_string(), d2.to_string())
d.link = None
def test_address(self):
address = '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
d = kml.Document()
d.address = address
self.assertTrue(address in str(d.to_string()))
self.assertTrue('address>' in str(d.to_string()))
def test_phone_number(self):
phone = '+1 234 567 8901'
d = kml.Document()
d.phoneNumber = phone
self.assertTrue(phone in str(d.to_string()))
self.assertTrue('phoneNumber>' in str(d.to_string()))
class KmlFromStringTestCase(unittest.TestCase):
def test_document(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
<Placemark>
<name>Document Feature 1</name>
<styleUrl>#exampleStyleDocument</styleUrl>
<Point>
<coordinates>-122.371,37.816,0</coordinates>
</Point>
</Placemark>
<Placemark targetId="someTargetId">
<name>Document Feature 2</name>
<styleUrl>#exampleStyleDocument</styleUrl>
<Point>
<coordinates>-122.370,37.817,0</coordinates>
</Point>
</Placemark>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list(list(k.features())[0].features())), 2)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_document_booleans(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<visibility>true</visibility>
<open>1</open>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].visibility, 1)
self.assertEqual(list(k.features())[0].isopen, 1)
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<visibility>0</visibility>
<open>false</open>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].visibility, 0)
self.assertEqual(list(k.features())[0].isopen, 0)
def test_folders(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
<name>Folder.kml</name>
<open>1</open>
<description>
A folder is a container that can hold multiple other objects
</description>
<Placemark>
<name>Folder object 1 (Placemark)</name>
<Point>
<coordinates>-122.377588,37.830266,0</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Folder object 2 (Polygon)</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-122.377830,37.830445,0
-122.377576,37.830631,0
-122.377840,37.830642,0
-122.377830,37.830445,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Folder object 3 (Path)</name>
<LineString>
<tessellate>1</tessellate>
<coordinates>
-122.378009,37.830128,0 -122.377885,37.830379,0
</coordinates>
</LineString>
</Placemark>
</Folder>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list(list(k.features())[0].features())), 3)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_placemark(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself
at the height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(list(k.features())[0].name, "Simple placemark")
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_extended_data(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description></description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
<ExtendedData>
<Data name="holeNumber">
<displayName><![CDATA[
<b>This is hole </b>
]]></displayName>
<value>1</value>
</Data>
<Data name="holePar">
<displayName><![CDATA[
<i>The par for this hole is </i>
]]></displayName>
<value>4</value>
</Data>
<SchemaData schemaUrl="#TrailHeadTypeId">
<SimpleData name="TrailHeadName">Mount Everest</SimpleData>
<SimpleData name="TrailLength">347.45</SimpleData>
<SimpleData name="ElevationGain">10000</SimpleData>
</SchemaData>
</ExtendedData>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
extended_data = list(k.features())[0].extended_data
self.assertEqual(extended_data.elements[0].name, 'holeNumber')
self.assertEqual(extended_data.elements[0].value, '1')
self.assertTrue(
'<b>This is hole </b>' in extended_data.elements[0].display_name)
self.assertEqual(extended_data.elements[1].name, 'holePar')
self.assertEqual(extended_data.elements[1].value, '4')
self.assertTrue(
'<i>The par for this hole is </i>' in
extended_data.elements[1].display_name)
sd = extended_data.elements[2]
self.assertEqual(sd.data[0]['name'], 'TrailHeadName')
self.assertEqual(sd.data[1]['value'], '347.45')
def test_polygon(self):
doc = """
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>South Africa</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
31.521,-29.257,0
31.326,-29.402,0
30.902,-29.91,0
30.623,-30.424,0
30.056,-31.14,0
28.926,-32.172,0
28.22,-32.772,0
27.465,-33.227,0
26.419,-33.615,0
25.91,-33.667,0
25.781,-33.945,0
25.173,-33.797,0
24.678,-33.987,0
23.594,-33.794,0
22.988,-33.916,0
22.574,-33.864,0
21.543,-34.259,0
20.689,-34.417,0
20.071,-34.795,0
19.616,-34.819,0
19.193,-34.463,0
18.855,-34.444,0
18.425,-33.998,0
18.377,-34.137,0
18.244,-33.868,0
18.25,-33.281,0
17.925,-32.611,0
18.248,-32.429,0
18.222,-31.662,0
17.567,-30.726,0
17.064,-29.879,0
17.063,-29.876,0
16.345,-28.577,0
16.824,-28.082,0
17.219,-28.356,0
17.387,-28.784,0
17.836,-28.856,0
18.465,-29.045,0
19.002,-28.972,0
19.895,-28.461,0
19.896,-24.768,0
20.166,-24.918,0
20.759,-25.868,0
20.666,-26.477,0
20.89,-26.829,0
21.606,-26.727,0
22.106,-26.28,0
22.58,-25.979,0
22.824,-25.5,0
23.312,-25.269,0
23.734,-25.39,0
24.211,-25.67,0
25.025,-25.72,0
25.665,-25.487,0
25.766,-25.175,0
25.942,-24.696,0
26.486,-24.616,0
26.786,-24.241,0
27.119,-23.574,0
28.017,-22.828,0
29.432,-22.091,0
29.839,-22.102,0
30.323,-22.272,0
30.66,-22.152,0
31.191,-22.252,0
31.67,-23.659,0
31.931,-24.369,0
31.752,-25.484,0
31.838,-25.843,0
31.333,-25.66,0
31.044,-25.731,0
30.95,-26.023,0
30.677,-26.398,0
30.686,-26.744,0
31.283,-27.286,0
31.868,-27.178,0
32.072,-26.734,0
32.83,-26.742,0
32.58,-27.47,0
32.462,-28.301,0
32.203,-28.752,0
31.521,-29.257,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
<innerBoundaryIs>
<LinearRing>
<coordinates>
28.978,-28.956,0
28.542,-28.648,0
28.074,-28.851,0
27.533,-29.243,0
26.999,-29.876,0
27.749,-30.645,0
28.107,-30.546,0
28.291,-30.226,0
28.848,-30.07,0
29.018,-29.744,0
29.325,-29.257,0
28.978,-28.956,0
</coordinates>
</LinearRing>
</innerBoundaryIs>
</Polygon>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(isinstance(list(k.features())[0].geometry, Polygon))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multipoints(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark id="feat_2">
<name>MultiPoint</name>
<styleUrl>#stylesel_9</styleUrl>
<MultiGeometry id="geom_0">
<Point id="geom_5">
<coordinates>16,-35,0.0</coordinates>
</Point>
<Point id="geom_6">
<coordinates>16,-33,0.0</coordinates>
</Point>
<Point id="geom_7">
<coordinates>16,-31,0.0</coordinates>
</Point>
<Point id="geom_8">
<coordinates>16,-29,0.0</coordinates>
</Point>
<Point id="geom_9">
<coordinates>16,-27,0.0</coordinates>
</Point>
<Point id="geom_10">
<coordinates>16,-25,0.0</coordinates>
</Point>
<Point id="geom_11">
<coordinates>16,-23,0.0</coordinates>
</Point>
<Point id="geom_12">
<coordinates>16,-21,0.0</coordinates>
</Point>
<Point id="geom_15">
<coordinates>18,-35,0.0</coordinates>
</Point>
<Point id="geom_16">
<coordinates>18,-33,0.0</coordinates>
</Point>
<Point id="geom_17">
<coordinates>18,-31,0.0</coordinates>
</Point>
<Point id="geom_18">
<coordinates>18,-29,0.0</coordinates>
</Point>
</MultiGeometry>
</Placemark></kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(isinstance(list(k.features())[0].geometry, MultiPoint))
self.assertEqual(len(list(k.features())[0].geometry.geoms), 12)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multilinestrings(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Dnipro (Dnieper)</name>
<MultiGeometry>
<LineString><coordinates>33.54,46.831,0 33.606,46.869,0 33.662,46.957,0 33.739,47.05,0 33.859,47.149,0 33.976,47.307,0 33.998,47.411,0 34.155,47.49,0 34.448,47.542,0 34.712,47.553,0 34.946,47.521,0 35.088,47.528,0 35.138,47.573,0 35.149,47.657,0 35.106,47.842,0 </coordinates></LineString>
<LineString><coordinates>33.194,49.094,0 32.884,49.225,0 32.603,49.302,0 31.886,49.555,0 </coordinates></LineString>
<LineString><coordinates>31.44,50,0 31.48,49.933,0 31.486,49.871,0 31.467,49.754,0 </coordinates></LineString>
<LineString><coordinates>30.508,51.217,0 30.478,50.904,0 30.479,50.749,0 30.515,50.597,0 </coordinates></LineString>
</MultiGeometry>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(k.features())[0].geometry, MultiLineString))
self.assertEqual(len(list(k.features())[0].geometry.geoms), 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multipolygon(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Italy</name>
<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>12.621,35.492,0 12.611,35.489,0 12.603,35.491,0 12.598,35.494,0 12.594,35.494,0 12.556,35.508,0 12.536,35.513,0 12.526,35.517,0 12.534,35.522,0 12.556,35.521,0 12.567,35.519,0 12.613,35.515,0 12.621,35.513,0 12.624,35.512,0 12.622,35.51,0 12.621,35.508,0 12.624,35.502,0 12.621,35.492,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.873,35.852,0 12.857,35.852,0 12.851,35.856,0 12.846,35.863,0 12.847,35.868,0 12.854,35.871,0 12.86,35.872,0 12.867,35.872,0 12.874,35.866,0 12.877,35.856,0 12.873,35.852,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>11.981,36.827,0 11.988,36.824,0 11.994,36.825,0 12,36.836,0 12.038,36.806,0 12.052,36.79,0 12.054,36.767,0 12.031,36.741,0 11.997,36.745,0 11.962,36.765,0 11.938,36.789,0 11.934,36.795,0 11.926,36.812,0 11.923,36.828,0 11.935,36.836,0 11.939,36.837,0 11.947,36.841,0 11.952,36.843,0 11.958,36.84,0 11.968,36.831,0 11.972,36.829,0 11.981,36.827,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.322,37.94,0 12.337,37.933,0 12.355,37.927,0 12.369,37.925,0 12.358,37.914,0 12.343,37.913,0 12.327,37.918,0 12.315,37.925,0 12.3,37.919,0 12.288,37.921,0 12.279,37.929,0 12.274,37.939,0 12.288,37.938,0 12.298,37.941,0 12.306,37.945,0 12.315,37.946,0 12.322,37.94,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.078,37.96,0 12.079,37.95,0 12.065,37.951,0 12.048,37.961,0 12.037,37.974,0 12.03,37.984,0 12.036,37.991,0 12.054,37.992,0 12.065,37.986,0 12.072,37.968,0 12.078,37.96,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>15.643,38.262,0 15.635,38.261,0 15.625,38.261,0 15.584,38.24,0 15.57,38.227,0 15.564,38.214,0 15.56,38.2,0 15.576,38.2,0 15.527,38.137,0 15.501,38.085,0 15.393,37.976,0 15.303,37.864,0 15.284,37.833,0 15.267,37.812,0 15.242,37.795,0 15.214,37.761,0 15.207,37.747,0 15.209,37.737,0 15.219,37.718,0 15.221,37.706,0 15.217,37.696,0 15.203,37.685,0 15.2,37.675,0 15.197,37.655,0 15.185,37.626,0 15.179,37.604,0 15.164,37.567,0 15.117,37.522,0 15.097,37.494,0 15.092,37.477,0 15.09,37.459,0 15.093,37.36,0 15.097,37.343,0 15.104,37.33,0 15.111,37.322,0 15.181,37.291,0 15.218,37.285,0 15.237,37.275,0 15.253,37.257,0 15.262,37.234,0 15.245,37.246,0 15.236,37.242,0 15.229,37.23,0 15.221,37.22,0 15.222,37.237,0 15.216,37.244,0 15.206,37.244,0 15.193,37.24,0 15.2,37.227,0 15.184,37.207,0 15.195,37.176,0 15.217,37.155,0 15.234,37.165,0 15.248,37.158,0 15.248,37.152,0 15.23,37.149,0 15.232,37.135,0 15.247,37.118,0 15.265,37.11,0 15.289,37.108,0 15.304,37.101,0 15.309,37.086,0 15.303,37.062,0 15.289,37.069,0 15.283,37.061,0 15.284,37.048,0 15.292,37.042,0 15.313,37.044,0 15.322,37.04,0 15.33,37.027,0 15.333,37.011,0 15.325,37.008,0 15.315,37.012,0 15.309,37.018,0 15.304,37.016,0 15.269,37,0 15.275,36.993,0 15.267,36.989,0 15.264,36.987,0 15.269,36.98,0 15.269,36.973,0 15.245,36.972,0 15.227,36.965,0 15.212,36.956,0 15.197,36.952,0 15.175,36.944,0 15.159,36.924,0 15.108,36.82,0 15.107,36.808,0 15.095,36.799,0 15.099,36.779,0 15.118,36.747,0 15.135,36.687,0 15.135,36.675,0 15.115,36.66,0 15.094,36.655,0 15.074,36.659,0 15.056,36.671,0 15.041,36.687,0 15.034,36.694,0 15.021,36.699,0 15.008,36.703,0 14.998,36.702,0 14.994,36.696,0 14.983,36.689,0 14.958,36.698,0 14.919,36.72,0 14.883,36.73,0 14.847,36.726,0 14.781,36.699,0 14.777,36.707,0 14.774,36.71,0 14.761,36.706,0 14.745,36.719,0 14.685,36.726,0 14.672,36.744,0 14.659,36.754,0 14.601,36.772,0 14.583,36.781,0 14.566,36.778,0 14.488,36.793,0 14.476,36.805,0 14.395,36.945,0 14.37,36.973,0 14.279,37.044,0 14.209,37.081,0 14.127,37.112,0 14.089,37.117,0 13.977,37.11,0 13.968,37.108,0 13.949,37.099,0 13.939,37.096,0 13.895,37.101,0 13.833,37.139,0 13.795,37.152,0 13.752,37.159,0 13.716,37.171,0 13.684,37.189,0 13.599,37.256,0 13.57,37.273,0 13.535,37.282,0 13.489,37.288,0 13.453,37.299,0 13.422,37.314,0 13.373,37.346,0 13.33,37.366,0 13.312,37.381,0 13.303,37.386,0 13.29,37.389,0 13.279,37.393,0 13.254,37.432,0 13.248,37.436,0 13.226,37.446,0 13.215,37.458,0 13.207,37.464,0 13.195,37.466,0 13.19,37.469,0 13.18,37.484,0 13.175,37.487,0 13.052,37.5,0 13.037,37.495,0 13.027,37.493,0 13.017,37.497,0 13.011,37.507,0 13.005,37.527,0 13.001,37.535,0 12.975,37.557,0 12.943,37.568,0 12.863,37.576,0 12.781,37.574,0 12.698,37.563,0 12.66,37.565,0 12.637,37.582,0 12.595,37.638,0 12.578,37.652,0 12.564,37.658,0 12.524,37.658,0 12.507,37.665,0 12.49,37.682,0 12.475,37.703,0 12.466,37.72,0 12.461,37.734,0 12.46,37.748,0 12.457,37.76,0 12.449,37.771,0 12.437,37.783,0 12.428,37.797,0 12.428,37.809,0 12.445,37.816,0 12.447,37.812,0 12.461,37.819,0 12.466,37.823,0 12.464,37.825,0 12.471,37.853,0 12.473,37.854,0 12.478,37.872,0 12.479,37.881,0 12.477,37.886,0 12.468,37.897,0 12.466,37.906,0 12.465,37.913,0 12.465,37.914,0 12.468,37.916,0 12.491,37.954,0 12.497,37.98,0 12.503,37.997,0 12.505,38.011,0 12.493,38.021,0 12.524,38.031,0 12.55,38.055,0 12.577,38.072,0 12.609,38.062,0 12.639,38.079,0 12.652,38.091,0 12.657,38.107,0 12.663,38.116,0 12.677,38.116,0 12.692,38.112,0 12.705,38.111,0 12.726,38.126,0 12.725,38.15,0 12.72,38.175,0 12.732,38.193,0 12.738,38.181,0 12.75,38.182,0 12.761,38.181,0 12.767,38.162,0 12.791,38.117,0 12.819,38.078,0 12.829,38.07,0 12.858,38.058,0 12.869,38.051,0 12.87,38.042,0 12.902,38.028,0 12.945,38.033,0 13.028,38.062,0 13.062,38.083,0 13.07,38.091,0 13.072,38.095,0 13.07,38.101,0 13.069,38.114,0 13.067,38.123,0 13.057,38.133,0 13.055,38.142,0 13.09,38.166,0 13.084,38.174,0 13.09,38.183,0 13.102,38.19,0 13.113,38.193,0 13.123,38.191,0 13.158,38.179,0 13.18,38.176,0 13.208,38.176,0 13.231,38.184,0 13.239,38.207,0 13.255,38.202,0 13.267,38.205,0 13.278,38.21,0 13.297,38.214,0 13.311,38.219,0 13.319,38.22,0 13.324,38.218,0 13.326,38.211,0 13.327,38.205,0 13.329,38.2,0 13.367,38.179,0 13.372,38.173,0 13.374,38.14,0 13.377,38.131,0 13.392,38.103,0 13.514,38.11,0 13.542,38.094,0 13.54,38.077,0 13.542,38.067,0 13.548,38.056,0 13.558,38.049,0 13.588,38.039,0 13.623,38.015,0 13.652,38.001,0 13.698,37.993,0 13.712,37.988,0 13.708,37.985,0 13.708,37.984,0 13.706,37.98,0 13.727,37.981,0 13.791,37.973,0 13.813,37.978,0 13.858,37.996,0 13.899,38.004,0 13.913,38.012,0 13.925,38.022,0 13.939,38.029,0 14.008,38.038,0 14.021,38.049,0 14.063,38.03,0 14.084,38.024,0 14.107,38.021,0 14.122,38.022,0 14.152,38.029,0 14.274,38.015,0 14.332,38.018,0 14.385,38.029,0 14.433,38.049,0 14.465,38.037,0 14.512,38.044,0 14.635,38.081,0 14.668,38.099,0 14.696,38.121,0 14.734,38.157,0 14.745,38.161,0 14.778,38.159,0 14.799,38.16,0 14.875,38.175,0 14.889,38.182,0 14.898,38.186,0 14.908,38.187,0 14.936,38.186,0 14.945,38.182,0 14.963,38.163,0 14.97,38.159,0 14.982,38.158,0 15.008,38.152,0 15.04,38.153,0 15.049,38.152,0 15.054,38.148,0 15.064,38.135,0 15.069,38.131,0 15.088,38.128,0 15.106,38.133,0 15.123,38.141,0 15.178,38.156,0 15.204,38.183,0 15.241,38.241,0 15.238,38.249,0 15.237,38.251,0 15.237,38.253,0 15.241,38.261,0 15.238,38.265,0 15.244,38.265,0 15.247,38.254,0 15.241,38.23,0 15.246,38.217,0 15.258,38.21,0 15.275,38.207,0 15.292,38.207,0 15.322,38.211,0 15.4,38.232,0 15.423,38.244,0 15.434,38.253,0 15.473,38.268,0 15.513,38.297,0 15.529,38.302,0 15.56,38.3,0 15.616,38.28,0 15.652,38.275,0 15.649,38.266,0 15.643,38.262,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.999,38.371,0 14.987,38.364,0 14.964,38.381,0 14.949,38.396,0 14.946,38.412,0 14.96,38.433,0 14.967,38.433,0 14.967,38.418,0 14.983,38.412,0 14.994,38.403,0 15.002,38.391,0 15.008,38.378,0 14.999,38.371,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.967,38.453,0 14.949,38.451,0 14.935,38.458,0 14.922,38.469,0 14.908,38.474,0 14.9,38.481,0 14.901,38.498,0 14.91,38.515,0 14.925,38.522,0 14.958,38.522,0 14.967,38.516,0 14.96,38.502,0 14.966,38.497,0 14.975,38.49,0 14.98,38.487,0 14.98,38.481,0 14.953,38.481,0 14.958,38.469,0 14.962,38.465,0 14.967,38.461,0 14.967,38.453,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.361,38.539,0 14.346,38.535,0 14.343,38.547,0 14.357,38.551,0 14.361,38.539,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.864,38.549,0 14.862,38.539,0 14.824,38.552,0 14.794,38.571,0 14.815,38.584,0 14.852,38.585,0 14.867,38.581,0 14.877,38.569,0 14.873,38.565,0 14.869,38.56,0 14.864,38.549,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.585,38.557,0 14.574,38.557,0 14.552,38.562,0 14.544,38.575,0 14.543,38.587,0 14.546,38.588,0 14.564,38.585,0 14.576,38.577,0 14.58,38.566,0 14.585,38.561,0 14.585,38.557,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.177,38.693,0 13.165,38.691,0 13.153,38.695,0 13.153,38.702,0 13.158,38.71,0 13.169,38.717,0 13.186,38.718,0 13.196,38.711,0 13.197,38.708,0 13.177,38.693,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>15.225,38.777,0 15.217,38.773,0 15.206,38.775,0 15.187,38.789,0 15.187,38.793,0 15.194,38.798,0 15.204,38.802,0 15.209,38.806,0 15.212,38.81,0 15.219,38.812,0 15.228,38.81,0 15.235,38.808,0 15.239,38.804,0 15.237,38.796,0 15.232,38.789,0 15.23,38.783,0 15.225,38.777,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.361,39.118,0 8.386,39.105,0 8.418,39.106,0 8.445,39.102,0 8.457,39.073,0 8.459,39.068,0 8.464,39.065,0 8.47,39.065,0 8.477,39.07,0 8.478,39.07,0 8.48,39.072,0 8.484,39.07,0 8.465,39.056,0 8.46,39.05,0 8.464,39.042,0 8.455,39.028,0 8.447,38.994,0 8.438,38.967,0 8.433,38.963,0 8.422,38.96,0 8.41,38.962,0 8.407,38.967,0 8.406,38.974,0 8.402,38.981,0 8.365,39.029,0 8.35,39.062,0 8.354,39.083,0 8.354,39.091,0 8.347,39.091,0 8.347,39.097,0 8.361,39.118,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.306,39.104,0 8.291,39.099,0 8.27,39.1,0 8.255,39.107,0 8.258,39.118,0 8.258,39.124,0 8.233,39.144,0 8.225,39.157,0 8.231,39.173,0 8.246,39.181,0 8.291,39.188,0 8.306,39.193,0 8.307,39.161,0 8.313,39.12,0 8.306,39.104,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.959,40.712,0 13.945,40.701,0 13.935,40.705,0 13.92,40.704,0 13.904,40.7,0 13.891,40.694,0 13.882,40.699,0 13.86,40.707,0 13.85,40.715,0 13.857,40.735,0 13.862,40.744,0 13.871,40.749,0 13.868,40.752,0 13.863,40.762,0 13.884,40.762,0 13.947,40.745,0 13.966,40.735,0 13.963,40.729,0 13.963,40.723,0 13.966,40.715,0 13.959,40.712,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.427,40.791,0 13.415,40.786,0 13.419,40.796,0 13.424,40.8,0 13.432,40.801,0 13.427,40.791,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.333,41.105,0 8.343,41.098,0 8.345,41.086,0 8.342,41.074,0 8.333,41.064,0 8.275,41.057,0 8.252,41.043,0 8.252,41.016,0 8.247,40.993,0 8.21,40.996,0 8.218,41.005,0 8.222,41.014,0 8.224,41.024,0 8.224,41.033,0 8.229,41.042,0 8.242,41.052,0 8.261,41.064,0 8.276,41.07,0 8.278,41.081,0 8.276,41.095,0 8.278,41.105,0 8.285,41.107,0 8.303,41.105,0 8.306,41.109,0 8.309,41.114,0 8.314,41.118,0 8.327,41.126,0 8.326,41.118,0 8.328,41.112,0 8.333,41.105,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.471,41.19,0 9.474,41.184,0 9.475,41.179,0 9.47,41.172,0 9.464,41.173,0 9.456,41.181,0 9.449,41.186,0 9.442,41.183,0 9.437,41.186,0 9.448,41.205,0 9.443,41.211,0 9.446,41.22,0 9.454,41.234,0 9.46,41.242,0 9.468,41.241,0 9.475,41.236,0 9.478,41.228,0 9.48,41.224,0 9.479,41.217,0 9.471,41.19,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.239,41.249,0 9.247,41.248,0 9.258,41.249,0 9.269,41.236,0 9.268,41.202,0 9.279,41.195,0 9.275,41.199,0 9.274,41.205,0 9.275,41.212,0 9.279,41.221,0 9.286,41.221,0 9.29,41.209,0 9.289,41.205,0 9.286,41.201,0 9.286,41.195,0 9.3,41.196,0 9.306,41.198,0 9.313,41.201,0 9.317,41.196,0 9.334,41.187,0 9.336,41.211,0 9.353,41.207,0 9.389,41.181,0 9.389,41.187,0 9.397,41.184,0 9.405,41.181,0 9.413,41.181,0 9.423,41.181,0 9.423,41.174,0 9.417,41.171,0 9.415,41.168,0 9.413,41.164,0 9.409,41.16,0 9.421,41.156,0 9.427,41.149,0 9.433,41.14,0 9.443,41.133,0 9.438,41.125,0 9.437,41.115,0 9.443,41.092,0 9.455,41.112,0 9.461,41.12,0 9.471,41.126,0 9.467,41.13,0 9.466,41.134,0 9.463,41.137,0 9.457,41.14,0 9.47,41.146,0 9.482,41.145,0 9.495,41.142,0 9.509,41.14,0 9.514,41.143,0 9.519,41.148,0 9.524,41.15,0 9.533,41.14,0 9.525,41.133,0 9.535,41.128,0 9.541,41.123,0 9.547,41.121,0 9.553,41.126,0 9.56,41.126,0 9.562,41.122,0 9.562,41.121,0 9.564,41.121,0 9.567,41.119,0 9.566,41.107,0 9.563,41.097,0 9.557,41.088,0 9.546,41.077,0 9.544,41.082,0 9.541,41.087,0 9.54,41.092,0 9.522,41.031,0 9.512,41.016,0 9.533,41.016,0 9.525,41.03,0 9.544,41.037,0 9.555,41.034,0 9.558,41.025,0 9.553,41.009,0 9.558,41.009,0 9.559,41.011,0 9.559,41.013,0 9.56,41.016,0 9.566,41.011,0 9.569,41.009,0 9.574,41.009,0 9.589,41.02,0 9.616,41.019,0 9.645,41.011,0 9.663,41.002,0 9.652,40.991,0 9.637,40.992,0 9.62,40.999,0 9.605,41.002,0 9.588,40.996,0 9.583,40.98,0 9.579,40.962,0 9.567,40.948,0 9.572,40.935,0 9.558,40.931,0 9.512,40.934,0 9.512,40.929,0 9.513,40.928,0 9.505,40.927,0 9.512,40.915,0 9.521,40.915,0 9.53,40.919,0 9.54,40.92,0 9.55,40.917,0 9.568,40.908,0 9.574,40.906,0 9.593,40.91,0 9.608,40.918,0 9.623,40.924,0 9.643,40.92,0 9.638,40.911,0 9.632,40.905,0 9.624,40.9,0 9.615,40.899,0 9.615,40.893,0 9.651,40.879,0 9.656,40.876,0 9.658,40.864,0 9.664,40.858,0 9.672,40.859,0 9.684,40.865,0 9.69,40.856,0 9.7,40.85,0 9.712,40.847,0 9.725,40.845,0 9.691,40.836,0 9.682,40.829,0 9.69,40.817,0 9.69,40.811,0 9.675,40.814,0 9.662,40.809,0 9.658,40.8,0 9.669,40.79,0 9.67,40.801,0 9.676,40.788,0 9.705,40.759,0 9.711,40.745,0 9.715,40.727,0 9.745,40.68,0 9.749,40.667,0 9.754,40.605,0 9.757,40.595,0 9.762,40.587,0 9.769,40.584,0 9.782,40.582,0 9.786,40.576,0 9.787,40.567,0 9.793,40.557,0 9.821,40.536,0 9.827,40.529,0 9.827,40.519,0 9.816,40.502,0 9.813,40.492,0 9.809,40.471,0 9.801,40.455,0 9.779,40.427,0 9.762,40.39,0 9.75,40.377,0 9.728,40.372,0 9.713,40.366,0 9.701,40.353,0 9.684,40.324,0 9.671,40.312,0 9.646,40.296,0 9.635,40.282,0 9.627,40.263,0 9.625,40.248,0 9.629,40.205,0 9.632,40.196,0 9.655,40.144,0 9.666,40.131,0 9.68,40.126,0 9.688,40.12,0 9.711,40.096,0 9.733,40.084,0 9.731,40.068,0 9.694,39.993,0 9.688,39.961,0 9.697,39.934,0 9.703,39.937,0 9.71,39.94,0 9.716,39.94,0 9.718,39.934,0 9.715,39.924,0 9.709,39.922,0 9.702,39.922,0 9.697,39.919,0 9.69,39.906,0 9.685,39.894,0 9.684,39.882,0 9.69,39.871,0 9.684,39.871,0 9.684,39.865,0 9.688,39.863,0 9.693,39.86,0 9.697,39.858,0 9.697,39.852,0 9.685,39.84,0 9.676,39.819,0 9.671,39.793,0 9.669,39.769,0 9.67,39.756,0 9.676,39.732,0 9.677,39.718,0 9.675,39.708,0 9.665,39.691,0 9.663,39.677,0 9.661,39.67,0 9.656,39.663,0 9.652,39.652,0 9.65,39.639,0 9.656,39.594,0 9.654,39.567,0 9.629,39.502,0 9.645,39.484,0 9.64,39.452,0 9.615,39.399,0 9.603,39.355,0 9.601,39.341,0 9.604,39.326,0 9.612,39.316,0 9.635,39.303,0 9.635,39.297,0 9.608,39.289,0 9.582,39.266,0 9.568,39.238,0 9.574,39.214,0 9.566,39.205,0 9.569,39.199,0 9.577,39.194,0 9.581,39.187,0 9.578,39.179,0 9.569,39.159,0 9.567,39.149,0 9.558,39.139,0 9.54,39.134,0 9.523,39.125,0 9.519,39.104,0 9.511,39.108,0 9.508,39.111,0 9.508,39.116,0 9.512,39.124,0 9.497,39.133,0 9.481,39.135,0 9.466,39.132,0 9.451,39.124,0 9.443,39.124,0 9.439,39.133,0 9.429,39.138,0 9.409,39.146,0 9.384,39.169,0 9.378,39.173,0 9.368,39.177,0 9.346,39.196,0 9.337,39.201,0 9.327,39.203,0 9.313,39.208,0 9.3,39.214,0 9.293,39.221,0 9.286,39.214,0 9.272,39.22,0 9.253,39.225,0 9.217,39.228,0 9.198,39.221,0 9.182,39.207,0 9.17,39.193,0 9.167,39.187,0 9.137,39.194,0 9.114,39.211,0 9.073,39.248,0 9.064,39.243,0 9.056,39.247,0 9.048,39.256,0 9.039,39.262,0 9.025,39.265,0 9.015,39.264,0 9.013,39.26,0 9.026,39.256,0 9.026,39.248,0 9.022,39.24,0 9.027,39.236,0 9.036,39.232,0 9.038,39.227,0 9.039,39.228,0 9.051,39.225,0 9.075,39.23,0 9.08,39.224,0 9.08,39.216,0 9.08,39.212,0 9.039,39.179,0 9.027,39.165,0 9.019,39.146,0 9.017,39.124,0 9.019,39.104,0 9.025,39.086,0 9.033,39.07,0 9.038,39.063,0 9.044,39.058,0 9.046,39.051,0 9.03,39.03,0 9.019,38.995,0 9.026,38.995,0 9.016,38.989,0 9.013,38.99,0 9.005,38.995,0 8.997,38.983,0 8.895,38.902,0 8.889,38.9,0 8.878,38.899,0 8.873,38.896,0 8.862,38.882,0 8.854,38.878,0 8.842,38.88,0 8.828,38.889,0 8.806,38.906,0 8.806,38.885,0 8.791,38.904,0 8.767,38.92,0 8.74,38.93,0 8.717,38.932,0 8.695,38.925,0 8.669,38.91,0 8.652,38.891,0 8.656,38.871,0 8.641,38.864,0 8.635,38.871,0 8.643,38.89,0 8.634,38.895,0 8.616,38.896,0 8.6,38.899,0 8.6,38.906,0 8.616,38.923,0 8.616,38.947,0 8.604,38.965,0 8.581,38.96,0 8.573,39.013,0 8.56,39.057,0 8.553,39.057,0 8.545,39.051,0 8.521,39.061,0 8.505,39.063,0 8.51,39.068,0 8.519,39.083,0 8.505,39.091,0 8.483,39.08,0 8.483,39.084,0 8.478,39.09,0 8.474,39.107,0 8.466,39.119,0 8.455,39.125,0 8.443,39.118,0 8.439,39.128,0 8.439,39.153,0 8.436,39.166,0 8.429,39.173,0 8.419,39.177,0 8.413,39.175,0 8.416,39.166,0 8.41,39.169,0 8.406,39.174,0 8.403,39.181,0 8.402,39.19,0 8.399,39.201,0 8.393,39.204,0 8.386,39.204,0 8.381,39.207,0 8.373,39.222,0 8.372,39.23,0 8.377,39.238,0 8.427,39.283,0 8.433,39.302,0 8.416,39.323,0 8.418,39.339,0 8.383,39.359,0 8.375,39.379,0 8.379,39.388,0 8.396,39.404,0 8.402,39.412,0 8.406,39.427,0 8.404,39.436,0 8.39,39.462,0 8.387,39.465,0 8.387,39.47,0 8.395,39.481,0 8.422,39.508,0 8.436,39.525,0 8.452,39.558,0 8.464,39.577,0 8.457,39.584,0 8.465,39.598,0 8.463,39.617,0 8.45,39.659,0 8.447,39.704,0 8.443,39.714,0 8.443,39.721,0 8.447,39.731,0 8.445,39.757,0 8.447,39.762,0 8.46,39.76,0 8.469,39.755,0 8.5,39.716,0 8.518,39.702,0 8.539,39.696,0 8.566,39.701,0 8.515,39.713,0 8.505,39.721,0 8.507,39.738,0 8.521,39.755,0 8.536,39.771,0 8.546,39.783,0 8.539,39.783,0 8.536,39.776,0 8.531,39.77,0 8.525,39.766,0 8.519,39.762,0 8.53,39.772,0 8.541,39.789,0 8.549,39.807,0 8.553,39.821,0 8.556,39.852,0 8.554,39.864,0 8.546,39.878,0 8.524,39.899,0 8.495,39.912,0 8.464,39.914,0 8.436,39.899,0 8.443,39.893,0 8.446,39.898,0 8.45,39.899,0 8.456,39.898,0 8.464,39.899,0 8.452,39.893,0 8.445,39.883,0 8.436,39.858,0 8.429,39.865,0 8.438,39.877,0 8.432,39.885,0 8.419,39.892,0 8.404,39.903,0 8.401,39.903,0 8.399,39.905,0 8.395,39.912,0 8.394,39.92,0 8.397,39.927,0 8.4,39.933,0 8.402,39.94,0 8.394,39.977,0 8.395,39.988,0 8.407,40.01,0 8.408,40.022,0 8.395,40.036,0 8.381,40.03,0 8.378,40.033,0 8.385,40.042,0 8.402,40.05,0 8.405,40.049,0 8.435,40.051,0 8.453,40.056,0 8.46,40.057,0 8.469,40.062,0 8.48,40.074,0 8.488,40.089,0 8.491,40.104,0 8.486,40.118,0 8.468,40.144,0 8.464,40.163,0 8.46,40.216,0 8.477,40.262,0 8.477,40.292,0 8.463,40.314,0 8.442,40.331,0 8.416,40.345,0 8.409,40.338,0 8.387,40.352,0 8.384,40.372,0 8.395,40.424,0 8.391,40.442,0 8.38,40.468,0 8.366,40.492,0 8.35,40.502,0 8.332,40.51,0 8.324,40.531,0 8.32,40.555,0 8.313,40.578,0 8.292,40.595,0 8.268,40.594,0 8.217,40.57,0 8.196,40.578,0 8.206,40.598,0 8.217,40.612,0 8.194,40.617,0 8.177,40.606,0 8.167,40.586,0 8.162,40.564,0 8.154,40.578,0 8.148,40.593,0 8.141,40.619,0 8.141,40.625,0 8.158,40.632,0 8.174,40.641,0 8.186,40.656,0 8.189,40.68,0 8.192,40.68,0 8.196,40.685,0 8.198,40.691,0 8.193,40.694,0 8.18,40.695,0 8.174,40.697,0 8.168,40.701,0 8.154,40.719,0 8.146,40.726,0 8.134,40.729,0 8.21,40.865,0 8.216,40.881,0 8.217,40.899,0 8.21,40.914,0 8.193,40.92,0 8.179,40.928,0 8.183,40.945,0 8.194,40.963,0 8.203,40.975,0 8.21,40.975,0 8.213,40.963,0 8.221,40.962,0 8.229,40.962,0 8.237,40.955,0 8.236,40.946,0 8.232,40.934,0 8.23,40.921,0 8.234,40.91,0 8.278,40.865,0 8.311,40.85,0 8.422,40.839,0 8.478,40.826,0 8.501,40.824,0 8.521,40.827,0 8.599,40.853,0 8.619,40.866,0 8.635,40.881,0 8.641,40.896,0 8.71,40.92,0 8.734,40.921,0 8.752,40.919,0 8.765,40.914,0 8.823,40.947,0 8.84,40.961,0 8.876,41.008,0 8.889,41.016,0 8.887,41.02,0 8.887,41.021,0 8.886,41.022,0 8.882,41.023,0 8.914,41.032,0 8.923,41.037,0 8.93,41.043,0 8.941,41.061,0 8.947,41.064,0 8.959,41.07,0 8.976,41.082,0 8.991,41.097,0 9.006,41.122,0 9.025,41.129,0 9.094,41.135,0 9.108,41.139,0 9.136,41.16,0 9.142,41.153,0 9.158,41.169,0 9.164,41.184,0 9.163,41.225,0 9.172,41.243,0 9.191,41.251,0 9.213,41.256,0 9.231,41.262,0 9.233,41.253,0 9.239,41.249,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.435,41.217,0 9.395,41.211,0 9.377,41.213,0 9.373,41.222,0 9.373,41.23,0 9.378,41.234,0 9.385,41.237,0 9.392,41.241,0 9.396,41.248,0 9.398,41.256,0 9.402,41.258,0 9.408,41.258,0 9.414,41.262,0 9.422,41.261,0 9.427,41.254,0 9.431,41.246,0 9.43,41.238,0 9.429,41.229,0 9.431,41.225,0 9.434,41.221,0 9.435,41.217,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.316,42.341,0 10.313,42.324,0 10.294,42.328,0 10.297,42.345,0 10.306,42.352,0 10.316,42.341,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.922,42.334,0 10.909,42.325,0 10.874,42.36,0 10.862,42.366,0 10.871,42.376,0 10.877,42.387,0 10.884,42.392,0 10.896,42.386,0 10.907,42.378,0 10.919,42.356,0 10.931,42.346,0 10.926,42.339,0 10.922,42.334,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.095,42.577,0 10.086,42.572,0 10.072,42.573,0 10.059,42.576,0 10.05,42.582,0 10.053,42.589,0 10.063,42.592,0 10.073,42.6,0 10.08,42.614,0 10.084,42.615,0 10.088,42.604,0 10.092,42.596,0 10.096,42.591,0 10.098,42.588,0 10.098,42.584,0 10.095,42.577,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.431,42.816,0 10.437,42.804,0 10.431,42.787,0 10.421,42.776,0 10.407,42.769,0 10.389,42.763,0 10.408,42.757,0 10.426,42.741,0 10.431,42.722,0 10.416,42.709,0 10.411,42.718,0 10.404,42.719,0 10.394,42.718,0 10.382,42.722,0 10.378,42.728,0 10.368,42.746,0 10.365,42.75,0 10.352,42.755,0 10.338,42.765,0 10.326,42.765,0 10.314,42.743,0 10.305,42.76,0 10.266,42.744,0 10.246,42.757,0 10.241,42.742,0 10.236,42.736,0 10.23,42.735,0 10.148,42.737,0 10.125,42.743,0 10.107,42.757,0 10.102,42.784,0 10.112,42.801,0 10.134,42.812,0 10.159,42.817,0 10.18,42.819,0 10.19,42.817,0 10.213,42.808,0 10.225,42.804,0 10.243,42.803,0 10.266,42.804,0 10.266,42.809,0 10.265,42.81,0 10.263,42.81,0 10.26,42.812,0 10.273,42.819,0 10.273,42.826,0 10.273,42.827,0 10.29,42.825,0 10.327,42.826,0 10.323,42.811,0 10.333,42.806,0 10.348,42.806,0 10.355,42.808,0 10.359,42.817,0 10.366,42.823,0 10.375,42.827,0 10.382,42.832,0 10.393,42.858,0 10.401,42.869,0 10.413,42.873,0 10.422,42.871,0 10.432,42.864,0 10.439,42.855,0 10.444,42.845,0 10.437,42.838,0 10.432,42.828,0 10.431,42.816,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.844,43.06,0 9.848,43.058,0 9.854,43.059,0 9.843,43.035,0 9.828,43.019,0 9.81,43.017,0 9.793,43.037,0 9.812,43.071,0 9.827,43.081,0 9.841,43.065,0 9.842,43.063,0 9.844,43.06,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.122,46.972,0 12.128,46.949,0 12.135,46.937,0 12.142,46.928,0 12.142,46.919,0 12.127,46.909,0 12.137,46.906,0 12.161,46.903,0 12.172,46.899,0 12.184,46.891,0 12.189,46.885,0 12.195,46.88,0 12.209,46.877,0 12.251,46.876,0 12.267,46.868,0 12.276,46.846,0 12.276,46.834,0 12.273,46.827,0 12.27,46.82,0 12.267,46.808,0 12.267,46.795,0 12.269,46.789,0 12.275,46.785,0 12.284,46.78,0 12.305,46.774,0 12.326,46.772,0 12.343,46.765,0 12.351,46.743,0 12.37,46.711,0 12.405,46.69,0 12.446,46.679,0 12.5,46.672,0 12.531,46.658,0 12.547,46.652,0 12.562,46.651,0 12.62,46.656,0 12.67,46.653,0 12.679,46.65,0 12.697,46.641,0 12.707,46.638,0 12.716,46.638,0 12.732,46.642,0 12.74,46.643,0 12.774,46.635,0 12.83,46.61,0 13.065,46.598,0 13.146,46.585,0 13.21,46.558,0 13.231,46.552,0 13.271,46.551,0 13.373,46.566,0 13.417,46.56,0 13.478,46.564,0 13.485,46.562,0 13.499,46.551,0 13.507,46.547,0 13.549,46.546,0 13.67,46.519,0 13.685,46.518,0 13.701,46.52,0 13.701,46.512,0 13.699,46.505,0 13.695,46.499,0 13.69,46.493,0 13.688,46.468,0 13.677,46.452,0 13.659,46.445,0 13.634,46.446,0 13.6,46.443,0 13.576,46.427,0 13.554,46.406,0 13.53,46.388,0 13.484,46.371,0 13.46,46.359,0 13.447,46.355,0 13.434,46.354,0 13.423,46.345,0 13.41,46.324,0 13.391,46.302,0 13.365,46.29,0 13.373,46.28,0 13.379,46.268,0 13.385,46.243,0 13.385,46.243,0 13.385,46.243,0 13.398,46.231,0 13.402,46.217,0 13.41,46.208,0 13.437,46.211,0 13.423,46.229,0 13.438,46.225,0 13.468,46.223,0 13.482,46.218,0 13.51,46.214,0 13.529,46.205,0 13.559,46.184,0 13.584,46.181,0 13.614,46.184,0 13.637,46.18,0 13.645,46.162,0 13.616,46.125,0 13.505,46.066,0 13.482,46.045,0 13.49,46.039,0 13.493,46.032,0 13.49,46.026,0 13.482,46.018,0 13.477,46.016,0 13.462,46.006,0 13.475,45.996,0 13.479,45.993,0 13.48,45.992,0 13.481,45.991,0 13.482,45.99,0 13.482,45.989,0 13.509,45.967,0 13.539,45.969,0 13.572,45.98,0 13.606,45.985,0 13.623,45.966,0 13.608,45.927,0 13.569,45.865,0 13.566,45.83,0 13.581,45.809,0 13.609,45.799,0 13.644,45.796,0 13.66,45.792,0 13.709,45.765,0 13.779,45.743,0 13.858,45.649,0 13.869,45.641,0 13.884,45.635,0 13.893,45.635,0 13.895,45.632,0 13.887,45.619,0 13.848,45.585,0 13.801,45.581,0 13.761,45.596,0 13.712,45.593,0 13.719,45.6,0 13.731,45.613,0 13.757,45.613,0 13.787,45.611,0 13.809,45.614,0 13.796,45.617,0 13.787,45.624,0 13.778,45.635,0 13.74,45.649,0 13.758,45.655,0 13.754,45.672,0 13.74,45.691,0 13.727,45.703,0 13.648,45.762,0 13.63,45.772,0 13.575,45.789,0 13.552,45.792,0 13.535,45.782,0 13.525,45.76,0 13.529,45.74,0 13.555,45.737,0 13.519,45.725,0 13.514,45.721,0 13.508,45.714,0 13.481,45.71,0 13.47,45.707,0 13.452,45.694,0 13.429,45.681,0 13.402,45.675,0 13.377,45.683,0 13.392,45.686,0 13.41,45.691,0 13.425,45.698,0 13.432,45.707,0 13.423,45.724,0 13.382,45.73,0 13.37,45.744,0 13.352,45.74,0 13.255,45.756,0 13.246,45.759,0 13.222,45.776,0 13.216,45.779,0 13.206,45.778,0 13.17,45.768,0 13.158,45.754,0 13.15,45.751,0 13.14,45.755,0 13.132,45.769,0 13.12,45.772,0 13.111,45.767,0 13.109,45.758,0 13.112,45.749,0 13.124,45.744,0 13.124,45.737,0 13.101,45.736,0 13.081,45.727,0 13.07,45.713,0 13.076,45.697,0 13.092,45.689,0 13.112,45.691,0 13.15,45.703,0 13.139,45.689,0 13.104,45.669,0 13.096,45.652,0 13.086,45.642,0 13.061,45.636,0 12.982,45.635,0 12.944,45.628,0 12.781,45.553,0 12.612,45.496,0 12.513,45.47,0 12.497,45.46,0 12.488,45.456,0 12.452,45.45,0 12.424,45.438,0 12.411,45.436,0 12.419,45.451,0 12.43,45.464,0 12.436,45.475,0 12.431,45.484,0 12.441,45.483,0 12.448,45.484,0 12.452,45.489,0 12.452,45.498,0 12.459,45.498,0 12.463,45.489,0 12.468,45.485,0 12.472,45.486,0 12.479,45.491,0 12.466,45.504,0 12.477,45.503,0 12.488,45.504,0 12.498,45.506,0 12.5,45.504,0 12.501,45.506,0 12.504,45.503,0 12.507,45.499,0 12.507,45.498,0 12.504,45.498,0 12.493,45.498,0 12.493,45.491,0 12.516,45.492,0 12.521,45.505,0 12.522,45.519,0 12.531,45.525,0 12.549,45.527,0 12.563,45.531,0 12.574,45.54,0 12.582,45.553,0 12.57,45.549,0 12.545,45.536,0 12.538,45.536,0 12.519,45.55,0 12.511,45.559,0 12.507,45.573,0 12.486,45.565,0 12.459,45.548,0 12.443,45.53,0 12.452,45.518,0 12.452,45.512,0 12.435,45.512,0 12.418,45.523,0 12.411,45.518,0 12.404,45.518,0 12.397,45.539,0 12.385,45.523,0 12.391,45.514,0 12.425,45.504,0 12.425,45.498,0 12.412,45.493,0 12.394,45.491,0 12.381,45.494,0 12.384,45.504,0 12.351,45.505,0 12.31,45.489,0 12.273,45.463,0 12.253,45.436,0 12.253,45.43,0 12.259,45.43,0 12.251,45.42,0 12.247,45.411,0 12.249,45.402,0 12.259,45.395,0 12.25,45.385,0 12.248,45.378,0 12.249,45.371,0 12.246,45.361,0 12.238,45.358,0 12.229,45.357,0 12.224,45.354,0 12.233,45.34,0 12.221,45.327,0 12.217,45.316,0 12.209,45.309,0 12.188,45.306,0 12.175,45.31,0 12.164,45.316,0 12.155,45.313,0 12.15,45.292,0 12.16,45.283,0 12.169,45.262,0 12.181,45.258,0 12.192,45.263,0 12.2,45.274,0 12.203,45.288,0 12.198,45.299,0 12.218,45.294,0 12.222,45.283,0 12.221,45.269,0 12.225,45.251,0 12.214,45.248,0 12.212,45.243,0 12.216,45.237,0 12.225,45.23,0 12.222,45.216,0 12.231,45.204,0 12.248,45.197,0 12.267,45.196,0 12.264,45.2,0 12.263,45.201,0 12.259,45.203,0 12.274,45.211,0 12.296,45.226,0 12.308,45.23,0 12.299,45.215,0 12.305,45.201,0 12.316,45.186,0 12.322,45.172,0 12.322,45.139,0 12.329,45.101,0 12.319,45.103,0 12.308,45.108,0 12.309,45.114,0 12.308,45.124,0 12.308,45.128,0 12.298,45.106,0 12.297,45.088,0 12.307,45.078,0 12.329,45.08,0 12.326,45.083,0 12.324,45.086,0 12.322,45.093,0 12.341,45.081,0 12.354,45.067,0 12.364,45.052,0 12.377,45.039,0 12.377,45.032,0 12.369,45.031,0 12.365,45.029,0 12.361,45.027,0 12.356,45.024,0 12.369,45.011,0 12.384,45.026,0 12.387,45.039,0 12.381,45.051,0 12.369,45.065,0 12.384,45.056,0 12.402,45.05,0 12.414,45.043,0 12.411,45.032,0 12.427,45.02,0 12.435,45.015,0 12.445,45.011,0 12.465,44.992,0 12.487,44.976,0 12.5,44.983,0 12.497,44.984,0 12.49,44.983,0 12.487,44.983,0 12.487,44.991,0 12.503,44.991,0 12.517,44.987,0 12.528,44.98,0 12.535,44.97,0 12.534,44.961,0 12.524,44.95,0 12.528,44.943,0 12.519,44.934,0 12.516,44.928,0 12.513,44.922,0 12.507,44.922,0 12.5,44.921,0 12.495,44.91,0 12.493,44.878,0 12.488,44.862,0 12.475,44.845,0 12.445,44.82,0 12.444,44.825,0 12.439,44.835,0 12.433,44.846,0 12.425,44.854,0 12.44,44.877,0 12.444,44.89,0 12.439,44.901,0 12.427,44.905,0 12.416,44.9,0 12.407,44.891,0 12.404,44.884,0 12.393,44.868,0 12.392,44.859,0 12.417,44.851,0 12.416,44.843,0 12.409,44.836,0 12.397,44.833,0 12.397,44.826,0 12.404,44.825,0 12.417,44.821,0 12.425,44.82,0 12.417,44.803,0 12.398,44.794,0 12.376,44.792,0 12.358,44.804,0 12.347,44.815,0 12.322,44.833,0 12.304,44.843,0 12.293,44.843,0 12.267,44.826,0 12.267,44.82,0 12.281,44.82,0 12.254,44.751,0 12.247,44.711,0 12.253,44.668,0 12.266,44.636,0 12.276,44.62,0 12.284,44.614,0 12.286,44.602,0 12.281,44.532,0 12.284,44.487,0 12.315,44.387,0 12.319,44.361,0 12.322,44.353,0 12.326,44.348,0 12.34,44.334,0 12.343,44.329,0 12.345,44.308,0 12.351,44.288,0 12.369,44.25,0 12.391,44.222,0 12.418,44.195,0 12.459,44.166,0 12.479,44.139,0 12.511,44.114,0 12.548,44.093,0 12.575,44.085,0 12.632,44.03,0 12.662,44.008,0 12.692,43.99,0 12.711,43.983,0 12.757,43.972,0 12.804,43.967,0 12.823,43.958,0 12.863,43.935,0 12.929,43.916,0 12.939,43.904,0 12.948,43.897,0 13.254,43.703,0 13.371,43.65,0 13.39,43.644,0 13.4,43.635,0 13.447,43.623,0 13.474,43.612,0 13.484,43.616,0 13.491,43.623,0 13.497,43.627,0 13.5,43.628,0 13.502,43.63,0 13.505,43.633,0 13.511,43.633,0 13.517,43.631,0 13.52,43.627,0 13.522,43.622,0 13.525,43.62,0 13.544,43.613,0 13.558,43.596,0 13.57,43.58,0 13.579,43.573,0 13.599,43.569,0 13.616,43.56,0 13.625,43.547,0 13.618,43.531,0 13.761,43.264,0 13.777,43.243,0 13.781,43.236,0 13.787,43.2,0 13.791,43.192,0 13.803,43.178,0 13.835,43.127,0 13.849,43.092,0 13.866,43.007,0 13.945,42.798,0 13.981,42.73,0 14.002,42.698,0 14.064,42.625,0 14.069,42.609,0 14.076,42.599,0 14.221,42.47,0 14.285,42.428,0 14.357,42.393,0 14.388,42.373,0 14.43,42.321,0 14.561,42.225,0 14.596,42.208,0 14.654,42.191,0 14.694,42.185,0 14.71,42.175,0 14.718,42.16,0 14.723,42.119,0 14.73,42.099,0 14.741,42.084,0 14.758,42.079,0 14.781,42.075,0 14.8,42.066,0 14.836,42.044,0 14.871,42.032,0 14.953,42.021,0 14.994,42.01,0 15.008,42.001,0 15.035,41.974,0 15.046,41.969,0 15.064,41.964,0 15.105,41.942,0 15.124,41.934,0 15.166,41.927,0 15.282,41.928,0 15.401,41.908,0 15.447,41.907,0 15.612,41.928,0 15.775,41.921,0 16.028,41.944,0 16.112,41.928,0 16.112,41.926,0 16.141,41.92,0 16.161,41.892,0 16.18,41.893,0 16.177,41.877,0 16.184,41.858,0 16.193,41.821,0 16.194,41.808,0 16.193,41.791,0 16.185,41.779,0 16.167,41.763,0 16.146,41.749,0 16.128,41.742,0 16.108,41.737,0 16.09,41.726,0 16.064,41.701,0 16.028,41.68,0 15.926,41.64,0 15.901,41.614,0 15.892,41.577,0 15.897,41.536,0 15.912,41.503,0 15.934,41.479,0 15.962,41.459,0 16.022,41.428,0 16.086,41.412,0 16.101,41.403,0 16.115,41.393,0 16.302,41.328,0 16.461,41.262,0 16.521,41.25,0 16.539,41.239,0 16.555,41.227,0 16.594,41.207,0 16.831,41.146,0 16.852,41.133,0 16.859,41.133,0 16.859,41.14,0 16.865,41.14,0 16.886,41.124,0 17.058,41.082,0 17.204,41.021,0 17.277,40.98,0 17.311,40.955,0 17.348,40.912,0 17.362,40.906,0 17.378,40.902,0 17.414,40.881,0 17.476,40.83,0 17.493,40.824,0 17.513,40.82,0 17.549,40.802,0 17.635,40.785,0 17.646,40.78,0 17.749,40.747,0 17.844,40.694,0 17.922,40.683,0 17.956,40.67,0 17.956,40.647,0 17.967,40.647,0 17.993,40.653,0 18.008,40.65,0 18.012,40.644,0 18.012,40.635,0 18.016,40.625,0 18.04,40.608,0 18.044,40.602,0 18.038,40.557,0 18.12,40.504,0 18.212,40.464,0 18.232,40.461,0 18.239,40.457,0 18.259,40.43,0 18.271,40.421,0 18.304,40.4,0 18.33,40.366,0 18.344,40.351,0 18.362,40.345,0 18.371,40.338,0 18.438,40.268,0 18.501,40.152,0 18.505,40.146,0 18.51,40.142,0 18.517,40.139,0 18.512,40.127,0 18.514,40.12,0 18.518,40.114,0 18.517,40.104,0 18.509,40.094,0 18.492,40.084,0 18.484,40.055,0 18.471,40.043,0 18.435,40.022,0 18.412,39.979,0 18.408,39.968,0 18.405,39.947,0 18.395,39.925,0 18.393,39.916,0 18.4,39.89,0 18.401,39.878,0 18.387,39.825,0 18.39,39.817,0 18.384,39.814,0 18.374,39.8,0 18.369,39.796,0 18.347,39.798,0 18.339,39.8,0 18.331,39.803,0 18.283,39.833,0 18.266,39.837,0 18.225,39.837,0 18.212,39.839,0 18.187,39.852,0 18.162,39.86,0 18.131,39.883,0 18.095,39.903,0 18.082,39.906,0 18.072,39.911,0 18.008,39.986,0 17.996,39.995,0 17.996,40.002,0 18.012,40.003,0 18.021,40.01,0 18.023,40.021,0 18.016,40.036,0 18.006,40.045,0 17.979,40.051,0 17.968,40.057,0 18.003,40.074,0 18.012,40.096,0 17.998,40.12,0 17.968,40.146,0 17.941,40.163,0 17.927,40.176,0 17.92,40.191,0 17.92,40.21,0 17.917,40.227,0 17.912,40.24,0 17.9,40.249,0 17.913,40.249,0 17.913,40.255,0 17.864,40.285,0 17.848,40.29,0 17.513,40.303,0 17.494,40.307,0 17.441,40.331,0 17.431,40.331,0 17.41,40.33,0 17.4,40.331,0 17.393,40.335,0 17.375,40.348,0 17.369,40.351,0 17.352,40.355,0 17.297,40.379,0 17.241,40.395,0 17.213,40.406,0 17.201,40.42,0 17.224,40.428,0 17.244,40.441,0 17.248,40.457,0 17.228,40.474,0 17.248,40.48,0 17.296,40.473,0 17.317,40.482,0 17.324,40.498,0 17.305,40.499,0 17.262,40.488,0 17.264,40.491,0 17.269,40.496,0 17.248,40.503,0 17.23,40.497,0 17.211,40.487,0 17.191,40.482,0 17.182,40.485,0 17.177,40.493,0 17.172,40.502,0 17.167,40.509,0 17.157,40.512,0 17.134,40.512,0 17.125,40.515,0 17.05,40.519,0 16.977,40.492,0 16.913,40.445,0 16.783,40.301,0 16.762,40.269,0 16.738,40.211,0 16.731,40.2,0 16.716,40.193,0 16.68,40.146,0 16.625,40.108,0 16.605,40.084,0 16.597,40.046,0 16.6,40.034,0 16.614,39.996,0 16.632,39.966,0 16.622,39.953,0 16.606,39.943,0 16.59,39.92,0 16.543,39.885,0 16.509,39.837,0 16.492,39.805,0 16.49,39.775,0 16.503,39.747,0 16.529,39.721,0 16.529,39.714,0 16.516,39.689,0 16.546,39.661,0 16.592,39.636,0 16.625,39.625,0 16.75,39.62,0 16.783,39.611,0 16.799,39.603,0 16.817,39.591,0 16.831,39.576,0 16.838,39.56,0 16.847,39.552,0 16.906,39.529,0 16.954,39.499,0 16.971,39.495,0 16.996,39.492,0 17.012,39.486,0 17.024,39.475,0 17.036,39.461,0 17.058,39.441,0 17.089,39.422,0 17.125,39.409,0 17.159,39.406,0 17.123,39.338,0 17.115,39.283,0 17.115,39.269,0 17.118,39.256,0 17.125,39.244,0 17.143,39.222,0 17.146,39.21,0 17.141,39.179,0 17.123,39.121,0 17.125,39.091,0 17.148,39.054,0 17.152,39.046,0 17.159,39.04,0 17.193,39.031,0 17.207,39.029,0 17.187,39.019,0 17.177,39.012,0 17.173,39.005,0 17.172,38.966,0 17.173,38.96,0 17.139,38.936,0 17.136,38.932,0 17.128,38.929,0 17.119,38.919,0 17.105,38.899,0 17.096,38.919,0 17.071,38.923,0 17.043,38.916,0 17.023,38.906,0 16.997,38.929,0 16.982,38.937,0 16.958,38.94,0 16.936,38.938,0 16.839,38.918,0 16.728,38.879,0 16.688,38.856,0 16.68,38.847,0 16.671,38.84,0 16.611,38.816,0 16.586,38.798,0 16.575,38.785,0 16.564,38.756,0 16.551,38.741,0 16.539,38.723,0 16.535,38.7,0 16.547,38.693,0 16.55,38.69,0 16.549,38.672,0 16.559,38.596,0 16.578,38.528,0 16.578,38.503,0 16.57,38.429,0 16.562,38.416,0 16.523,38.387,0 16.509,38.371,0 16.498,38.369,0 16.468,38.348,0 16.436,38.34,0 16.34,38.301,0 16.307,38.277,0 16.17,38.143,0 16.152,38.111,0 16.126,38.005,0 16.112,37.973,0 16.102,37.96,0 16.091,37.949,0 16.078,37.94,0 16.064,37.932,0 16.016,37.924,0 16.002,37.919,0 15.943,37.933,0 15.762,37.925,0 15.736,37.931,0 15.709,37.941,0 15.685,37.953,0 15.666,37.967,0 15.646,37.988,0 15.636,38.009,0 15.639,38.027,0 15.659,38.042,0 15.633,38.074,0 15.625,38.092,0 15.628,38.107,0 15.642,38.126,0 15.648,38.143,0 15.647,38.162,0 15.639,38.186,0 15.633,38.22,0 15.651,38.241,0 15.685,38.253,0 15.787,38.278,0 15.796,38.285,0 15.799,38.291,0 15.813,38.3,0 15.817,38.306,0 15.83,38.351,0 15.905,38.474,0 15.918,38.517,0 15.916,38.55,0 15.901,38.578,0 15.871,38.604,0 15.864,38.608,0 15.851,38.613,0 15.845,38.618,0 15.836,38.628,0 15.834,38.634,0 15.836,38.639,0 15.837,38.649,0 15.845,38.66,0 15.864,38.668,0 15.905,38.679,0 15.969,38.712,0 16.003,38.725,0 16.049,38.728,0 16.121,38.721,0 16.137,38.724,0 16.153,38.731,0 16.18,38.748,0 16.201,38.776,0 16.216,38.814,0 16.222,38.856,0 16.221,38.899,0 16.215,38.919,0 16.205,38.934,0 16.19,38.943,0 16.169,38.947,0 16.155,38.955,0 16.14,38.974,0 16.084,39.075,0 16.043,39.31,0 16.032,39.345,0 15.955,39.489,0 15.934,39.513,0 15.905,39.536,0 15.877,39.551,0 15.868,39.564,0 15.865,39.588,0 15.851,39.615,0 15.837,39.652,0 15.816,39.679,0 15.807,39.695,0 15.789,39.796,0 15.789,39.79,0 15.784,39.81,0 15.779,39.82,0 15.772,39.824,0 15.77,39.83,0 15.783,39.868,0 15.775,39.891,0 15.742,39.929,0 15.735,39.943,0 15.729,39.964,0 15.714,39.981,0 15.679,40.009,0 15.652,40.043,0 15.631,40.057,0 15.625,40.065,0 15.625,40.078,0 15.611,40.073,0 15.536,40.078,0 15.51,40.07,0 15.493,40.059,0 15.46,40.029,0 15.425,40.004,0 15.405,39.999,0 15.377,40.002,0 15.354,40.012,0 15.315,40.034,0 15.303,40.036,0 15.294,40.032,0 15.284,40.03,0 15.273,40.028,0 15.262,40.029,0 15.262,40.036,0 15.28,40.047,0 15.264,40.074,0 15.234,40.1,0 15.21,40.112,0 15.191,40.119,0 15.128,40.169,0 15.113,40.175,0 15.096,40.173,0 15.066,40.166,0 15.048,40.169,0 15.035,40.175,0 15.015,40.194,0 14.974,40.223,0 14.967,40.224,0 14.959,40.231,0 14.923,40.238,0 14.912,40.241,0 14.907,40.258,0 14.932,40.285,0 14.94,40.307,0 14.933,40.324,0 14.933,40.334,0 14.943,40.338,0 14.954,40.34,0 14.965,40.345,0 14.973,40.352,0 14.98,40.359,0 14.99,40.394,0 14.976,40.431,0 14.889,40.573,0 14.862,40.607,0 14.836,40.632,0 14.81,40.653,0 14.783,40.67,0 14.753,40.676,0 14.72,40.667,0 14.691,40.649,0 14.679,40.646,0 14.626,40.649,0 14.614,40.646,0 14.572,40.617,0 14.545,40.613,0 14.517,40.62,0 14.487,40.632,0 14.472,40.624,0 14.423,40.615,0 14.402,40.602,0 14.356,40.583,0 14.343,40.57,0 14.331,40.584,0 14.329,40.605,0 14.338,40.624,0 14.36,40.632,0 14.38,40.634,0 14.388,40.637,0 14.395,40.65,0 14.403,40.657,0 14.471,40.699,0 14.48,40.711,0 14.475,40.729,0 14.461,40.744,0 14.443,40.755,0 14.426,40.762,0 14.415,40.765,0 14.399,40.767,0 14.391,40.77,0 14.385,40.774,0 14.372,40.787,0 14.367,40.79,0 14.349,40.797,0 14.313,40.828,0 14.295,40.839,0 14.276,40.84,0 14.249,40.837,0 14.224,40.831,0 14.213,40.821,0 14.204,40.801,0 14.182,40.8,0 14.112,40.829,0 14.096,40.834,0 14.083,40.831,0 14.077,40.822,0 14.078,40.81,0 14.082,40.797,0 14.083,40.783,0 14.075,40.788,0 14.041,40.798,0 14.053,40.837,0 14.044,40.875,0 13.966,40.996,0 13.931,41.014,0 13.918,41.023,0 13.915,41.033,0 13.913,41.054,0 13.911,41.064,0 13.885,41.104,0 13.786,41.203,0 13.722,41.252,0 13.709,41.256,0 13.679,41.25,0 13.664,41.25,0 13.657,41.259,0 13.595,41.253,0 13.564,41.238,0 13.576,41.208,0 13.544,41.206,0 13.535,41.208,0 13.526,41.215,0 13.52,41.225,0 13.515,41.229,0 13.508,41.221,0 13.5,41.221,0 13.481,41.239,0 13.325,41.295,0 13.286,41.295,0 13.205,41.284,0 13.187,41.278,0 13.152,41.26,0 13.115,41.251,0 13.091,41.226,0 13.069,41.221,0 13.045,41.227,0 13.037,41.24,0 13.034,41.257,0 13.024,41.273,0 13.013,41.286,0 12.993,41.315,0 12.98,41.331,0 12.924,41.379,0 12.894,41.399,0 12.863,41.413,0 12.842,41.418,0 12.764,41.421,0 12.749,41.423,0 12.679,41.458,0 12.655,41.465,0 12.643,41.458,0 12.636,41.447,0 12.62,41.459,0 12.546,41.544,0 12.449,41.63,0 12.343,41.702,0 12.328,41.711,0 12.301,41.717,0 12.286,41.727,0 12.277,41.729,0 12.247,41.733,0 12.24,41.736,0 12.224,41.75,0 12.216,41.768,0 12.212,41.787,0 12.212,41.808,0 12.207,41.827,0 12.195,41.847,0 12.171,41.879,0 12.148,41.903,0 12.05,41.96,0 12.039,41.965,0 12.03,41.973,0 12.027,41.986,0 12.021,41.993,0 11.993,41.996,0 11.983,42,0 11.97,42.011,0 11.953,42.022,0 11.935,42.031,0 11.917,42.038,0 11.84,42.036,0 11.828,42.034,0 11.823,42.047,0 11.81,42.066,0 11.794,42.084,0 11.78,42.092,0 11.772,42.106,0 11.751,42.128,0 11.746,42.136,0 11.744,42.152,0 11.737,42.169,0 11.683,42.252,0 11.659,42.279,0 11.54,42.349,0 11.49,42.359,0 11.421,42.386,0 11.397,42.393,0 11.397,42.4,0 11.387,42.404,0 11.377,42.407,0 11.366,42.408,0 11.355,42.407,0 11.363,42.4,0 11.334,42.4,0 11.26,42.421,0 11.246,42.422,0 11.228,42.422,0 11.212,42.419,0 11.205,42.411,0 11.201,42.395,0 11.187,42.379,0 11.185,42.366,0 11.175,42.369,0 11.165,42.369,0 11.158,42.368,0 11.157,42.366,0 11.148,42.371,0 11.135,42.384,0 11.107,42.391,0 11.095,42.402,0 11.087,42.418,0 11.081,42.435,0 11.1,42.443,0 11.123,42.446,0 11.167,42.448,0 11.175,42.458,0 11.184,42.48,0 11.19,42.504,0 11.188,42.521,0 11.167,42.546,0 11.159,42.564,0 11.149,42.563,0 11.138,42.559,0 11.129,42.558,0 11.117,42.572,0 11.108,42.591,0 11.098,42.607,0 11.081,42.612,0 11.078,42.632,0 11.054,42.647,0 11.006,42.668,0 11.001,42.68,0 10.996,42.696,0 10.99,42.71,0 10.982,42.716,0 10.973,42.72,0 10.944,42.743,0 10.891,42.764,0 10.732,42.804,0 10.756,42.819,0 10.766,42.835,0 10.767,42.854,0 10.766,42.877,0 10.769,42.884,0 10.775,42.888,0 10.778,42.894,0 10.774,42.908,0 10.764,42.918,0 10.751,42.925,0 10.682,42.949,0 10.633,42.958,0 10.584,42.959,0 10.54,42.949,0 10.544,42.939,0 10.547,42.935,0 10.519,42.925,0 10.5,42.94,0 10.478,42.99,0 10.503,43.005,0 10.518,43.024,0 10.54,43.079,0 10.536,43.091,0 10.536,43.112,0 10.54,43.134,0 10.547,43.147,0 10.539,43.164,0 10.535,43.185,0 10.533,43.226,0 10.529,43.246,0 10.517,43.267,0 10.438,43.388,0 10.374,43.453,0 10.36,43.465,0 10.327,43.477,0 10.318,43.492,0 10.295,43.568,0 10.265,43.809,0 10.252,43.846,0 10.211,43.92,0 10.181,43.955,0 10.137,43.978,0 10.106,44.016,0 10.091,44.025,0 10.073,44.029,0 10.036,44.048,0 10.015,44.052,0 9.999,44.058,0 9.989,44.06,0 9.985,44.055,0 9.981,44.05,0 9.973,44.045,0 9.963,44.044,0 9.954,44.048,0 9.938,44.06,0 9.905,44.08,0 9.888,44.093,0 9.877,44.088,0 9.845,44.108,0 9.827,44.107,0 9.834,44.1,0 9.829,44.098,0 9.825,44.095,0 9.82,44.093,0 9.825,44.085,0 9.831,44.079,0 9.839,44.075,0 9.848,44.072,0 9.848,44.066,0 9.842,44.063,0 9.839,44.06,0 9.834,44.052,0 9.847,44.046,0 9.843,44.041,0 9.833,44.042,0 9.827,44.055,0 9.82,44.063,0 9.772,44.079,0 9.722,44.113,0 9.71,44.118,0 9.683,44.136,0 9.673,44.141,0 9.644,44.142,0 9.632,44.144,0 9.622,44.148,0 9.587,44.178,0 9.581,44.179,0 9.573,44.191,0 9.557,44.2,0 9.512,44.215,0 9.5,44.222,0 9.49,44.231,0 9.485,44.244,0 9.473,44.24,0 9.454,44.237,0 9.437,44.239,0 9.43,44.247,0 9.423,44.257,0 9.375,44.272,0 9.368,44.294,0 9.263,44.336,0 9.231,44.353,0 9.222,44.344,0 9.214,44.333,0 9.21,44.321,0 9.211,44.305,0 9.166,44.318,0 9.147,44.328,0 9.149,44.34,0 9.131,44.363,0 9.103,44.374,0 9.002,44.387,0 8.953,44.4,0 8.924,44.411,0 8.915,44.409,0 8.869,44.409,0 8.846,44.413,0 8.838,44.417,0 8.828,44.428,0 8.763,44.432,0 8.738,44.429,0 8.725,44.424,0 8.696,44.406,0 8.686,44.398,0 8.679,44.394,0 8.671,44.394,0 8.663,44.395,0 8.656,44.394,0 8.594,44.363,0 8.577,44.36,0 8.565,44.357,0 8.541,44.34,0 8.467,44.304,0 8.445,44.284,0 8.45,44.264,0 8.44,44.253,0 8.437,44.247,0 8.436,44.24,0 8.433,44.238,0 8.418,44.23,0 8.412,44.227,0 8.407,44.215,0 8.409,44.204,0 8.409,44.193,0 8.395,44.182,0 8.37,44.173,0 8.314,44.16,0 8.285,44.148,0 8.27,44.138,0 8.257,44.128,0 8.234,44.103,0 8.231,44.096,0 8.232,44.08,0 8.231,44.072,0 8.224,44.057,0 8.217,44.045,0 8.17,44.006,0 8.153,43.983,0 8.168,43.962,0 8.168,43.956,0 8.145,43.952,0 8.116,43.927,0 8.09,43.92,0 8.082,43.915,0 8.076,43.909,0 8.073,43.904,0 8.068,43.896,0 8.056,43.892,0 8.032,43.887,0 7.96,43.853,0 7.786,43.822,0 7.737,43.798,0 7.695,43.791,0 7.573,43.791,0 7.545,43.784,0 7.532,43.784,0 7.524,43.789,0 7.513,43.792,0 7.503,43.792,0 7.483,43.84,0 7.478,43.866,0 7.493,43.886,0 7.537,43.921,0 7.557,43.944,0 7.609,43.976,0 7.631,43.994,0 7.639,44.005,0 7.647,44.027,0 7.653,44.04,0 7.664,44.049,0 7.679,44.057,0 7.69,44.067,0 7.692,44.085,0 7.676,44.109,0 7.654,44.125,0 7.642,44.144,0 7.656,44.176,0 7.625,44.18,0 7.584,44.161,0 7.555,44.159,0 7.381,44.123,0 7.341,44.124,0 7.331,44.125,0 7.322,44.132,0 7.316,44.14,0 7.309,44.147,0 7.296,44.151,0 7.27,44.154,0 7.251,44.16,0 7.145,44.207,0 7.105,44.218,0 7.046,44.24,0 7.033,44.243,0 7.02,44.242,0 7.008,44.239,0 6.996,44.238,0 6.983,44.242,0 6.973,44.249,0 6.969,44.258,0 6.966,44.268,0 6.959,44.277,0 6.95,44.285,0 6.93,44.295,0 6.921,44.302,0 6.916,44.31,0 6.904,44.33,0 6.896,44.34,0 6.874,44.358,0 6.87,44.363,0 6.866,44.372,0 6.866,44.377,0 6.869,44.383,0 6.877,44.414,0 6.884,44.423,0 6.918,44.436,0 6.892,44.452,0 6.861,44.475,0 6.839,44.503,0 6.836,44.534,0 6.846,44.547,0 6.897,44.575,0 6.932,44.618,0 6.946,44.625,0 6.934,44.647,0 6.941,44.667,0 6.96,44.683,0 6.983,44.692,0 7.001,44.692,0 7.037,44.685,0 7.055,44.685,0 7.049,44.698,0 7.019,44.739,0 7.015,44.747,0 7.01,44.772,0 6.998,44.794,0 6.999,44.795,0 7.004,44.811,0 7.006,44.812,0 7.006,44.816,0 7.007,44.819,0 7.007,44.822,0 7.005,44.828,0 7.001,44.833,0 6.983,44.847,0 6.933,44.862,0 6.915,44.863,0 6.866,44.856,0 6.847,44.859,0 6.778,44.888,0 6.745,44.908,0 6.728,44.929,0 6.73,44.985,0 6.723,45.013,0 6.697,45.027,0 6.662,45.029,0 6.652,45.036,0 6.64,45.05,0 6.637,45.059,0 6.638,45.067,0 6.637,45.074,0 6.62,45.084,0 6.603,45.103,0 6.615,45.115,0 6.633,45.126,0 6.667,45.14,0 6.676,45.141,0 6.694,45.14,0 6.702,45.141,0 6.711,45.145,0 6.729,45.155,0 6.736,45.157,0 6.771,45.153,0 6.808,45.139,0 6.844,45.13,0 6.877,45.141,0 6.879,45.147,0 6.873,45.152,0 6.868,45.157,0 6.873,45.166,0 6.881,45.168,0 6.905,45.169,0 6.914,45.17,0 6.928,45.18,0 6.946,45.201,0 6.959,45.21,0 6.994,45.221,0 7.03,45.228,0 7.038,45.226,0 7.05,45.215,0 7.055,45.214,0 7.062,45.219,0 7.081,45.243,0 7.108,45.259,0 7.108,45.275,0 7.098,45.295,0 7.093,45.324,0 7.098,45.33,0 7.13,45.357,0 7.151,45.383,0 7.16,45.398,0 7.161,45.411,0 7.153,45.415,0 7.11,45.428,0 7.097,45.435,0 7.089,45.447,0 7.082,45.459,0 7.072,45.47,0 7.028,45.493,0 6.983,45.511,0 6.975,45.526,0 6.97,45.567,0 6.966,45.574,0 6.955,45.586,0 6.953,45.594,0 6.956,45.603,0 6.967,45.62,0 6.969,45.626,0 6.963,45.641,0 6.951,45.647,0 6.919,45.653,0 6.905,45.66,0 6.883,45.676,0 6.869,45.679,0 6.843,45.683,0 6.816,45.697,0 6.796,45.718,0 6.785,45.76,0 6.782,45.777,0 6.783,45.795,0 6.788,45.812,0 6.801,45.826,0 6.816,45.833,0 6.846,45.836,0 6.846,45.838,0 6.849,45.842,0 6.853,45.847,0 6.858,45.849,0 6.862,45.849,0 6.87,45.845,0 6.873,45.845,0 6.88,45.846,0 6.905,45.845,0 6.926,45.85,0 6.949,45.858,0 6.969,45.87,0 6.983,45.886,0 6.989,45.899,0 6.997,45.911,0 7.008,45.921,0 7.022,45.925,0 7.067,45.89,0 7.09,45.881,0 7.121,45.876,0 7.154,45.877,0 7.184,45.88,0 7.245,45.898,0 7.274,45.91,0 7.287,45.913,0 7.362,45.908,0 7.394,45.916,0 7.453,45.946,0 7.483,45.955,0 7.504,45.957,0 7.515,45.967,0 7.524,45.978,0 7.541,45.984,0 7.643,45.966,0 7.659,45.96,0 7.674,45.95,0 7.693,45.931,0 7.694,45.929,0 7.706,45.926,0 7.715,45.927,0 7.722,45.93,0 7.732,45.93,0 7.78,45.918,0 7.808,45.918,0 7.825,45.915,0 7.831,45.914,0 7.844,45.919,0 7.846,45.923,0 7.845,45.928,0 7.848,45.938,0 7.872,45.969,0 7.898,45.982,0 7.969,45.993,0 7.979,45.995,0 7.986,45.999,0 7.998,46.011,0 7.999,46.013,0 8.009,46.028,0 8.011,46.03,0 8.016,46.058,0 8.016,46.069,0 8.018,46.081,0 8.025,46.091,0 8.035,46.097,0 8.056,46.098,0 8.067,46.101,0 8.111,46.127,0 8.132,46.159,0 8.13,46.196,0 8.1,46.236,0 8.077,46.25,0 8.073,46.254,0 8.077,46.262,0 8.087,46.272,0 8.107,46.286,0 8.128,46.292,0 8.172,46.299,0 8.193,46.309,0 8.242,46.354,0 8.27,46.364,0 8.282,46.37,0 8.291,46.378,0 8.297,46.388,0 8.297,46.398,0 8.29,46.401,0 8.287,46.405,0 8.295,46.418,0 8.316,46.434,0 8.343,46.444,0 8.399,46.452,0 8.428,46.449,0 8.442,46.435,0 8.446,46.412,0 8.446,46.382,0 8.443,46.353,0 8.427,46.302,0 8.423,46.276,0 8.427,46.251,0 8.438,46.235,0 8.457,46.225,0 8.483,46.218,0 8.51,46.208,0 8.539,46.188,0 8.602,46.123,0 8.612,46.119,0 8.631,46.115,0 8.677,46.096,0 8.695,46.095,0 8.702,46.098,0 8.718,46.108,0 8.724,46.11,0 8.732,46.107,0 8.739,46.098,0 8.747,46.094,0 8.763,46.093,0 8.794,46.093,0 8.809,46.09,0 8.834,46.066,0 8.82,46.043,0 8.791,46.019,0 8.773,45.991,0 8.77,45.986,0 8.768,45.983,0 8.785,45.982,0 8.8,45.979,0 8.858,45.957,0 8.864,45.953,0 8.871,45.947,0 8.881,45.931,0 8.898,45.91,0 8.907,45.896,0 8.912,45.883,0 8.914,45.866,0 8.91,45.854,0 8.904,45.842,0 8.9,45.826,0 8.94,45.835,0 8.972,45.825,0 9.002,45.821,0 9.034,45.848,0 9.059,45.882,0 9.063,45.899,0 9.052,45.916,0 9.042,45.92,0 9.021,45.923,0 9.011,45.927,0 9.002,45.936,0 8.993,45.954,0 8.983,45.962,0 8.981,45.964,0 8.98,45.967,0 8.981,45.969,0 8.983,45.972,0 9.016,45.993,0 8.998,46.028,0 9.002,46.039,0 9.028,46.053,0 9.05,46.058,0 9.059,46.062,0 9.067,46.071,0 9.07,46.083,0 9.068,46.106,0 9.072,46.119,0 9.091,46.138,0 9.163,46.172,0 9.171,46.183,0 9.176,46.194,0 9.181,46.204,0 9.192,46.21,0 9.204,46.214,0 9.216,46.221,0 9.225,46.231,0 9.24,46.267,0 9.269,46.309,0 9.275,46.331,0 9.274,46.344,0 9.26,46.38,0 9.26,46.394,0 9.263,46.407,0 9.261,46.417,0 9.248,46.423,0 9.238,46.437,0 9.246,46.461,0 9.263,46.485,0 9.282,46.497,0 9.331,46.502,0 9.351,46.498,0 9.352,46.485,0 9.377,46.469,0 9.385,46.466,0 9.395,46.469,0 9.4,46.475,0 9.404,46.483,0 9.411,46.489,0 9.427,46.497,0 9.435,46.498,0 9.438,46.492,0 9.444,46.396,0 9.442,46.381,0 9.444,46.375,0 9.452,46.37,0 9.474,46.362,0 9.483,46.357,0 9.503,46.321,0 9.515,46.309,0 9.536,46.299,0 9.56,46.293,0 9.674,46.292,0 9.693,46.297,0 9.708,46.312,0 9.709,46.32,0 9.707,46.331,0 9.709,46.342,0 9.72,46.351,0 9.731,46.351,0 9.755,46.341,0 9.768,46.339,0 9.789,46.343,0 9.855,46.367,0 9.899,46.372,0 9.918,46.371,0 9.939,46.367,0 9.964,46.356,0 9.971,46.34,0 9.971,46.32,0 9.978,46.298,0 9.992,46.284,0 10.032,46.26,0 10.042,46.243,0 10.043,46.22,0 10.076,46.22,0 10.118,46.231,0 10.146,46.243,0 10.159,46.262,0 10.146,46.28,0 10.105,46.309,0 10.096,46.321,0 10.092,46.329,0 10.092,46.338,0 10.097,46.352,0 10.105,46.361,0 10.126,46.374,0 10.133,46.381,0 10.141,46.403,0 10.133,46.414,0 10.116,46.419,0 10.071,46.425,0 10.042,46.433,0 10.026,46.446,0 10.044,46.467,0 10.035,46.471,0 10.03,46.477,0 10.028,46.484,0 10.027,46.493,0 10.031,46.504,0 10.031,46.526,0 10.033,46.533,0 10.041,46.542,0 10.063,46.557,0 10.071,46.564,0 10.083,46.597,0 10.088,46.604,0 10.097,46.608,0 10.192,46.627,0 10.218,46.627,0 10.234,46.618,0 10.236,46.607,0 10.23,46.586,0 10.235,46.575,0 10.276,46.566,0 10.284,46.561,0 10.289,46.556,0 10.295,46.551,0 10.307,46.547,0 10.319,46.546,0 10.354,46.548,0 10.426,46.535,0 10.444,46.538,0 10.458,46.554,0 10.466,46.578,0 10.467,46.604,0 10.459,46.624,0 10.438,46.636,0 10.396,46.639,0 10.378,46.653,0 10.369,46.672,0 10.374,46.682,0 10.385,46.689,0 10.394,46.701,0 10.397,46.715,0 10.396,46.726,0 10.4,46.736,0 10.417,46.743,0 10.429,46.756,0 10.426,46.769,0 10.419,46.784,0 10.417,46.799,0 10.439,46.817,0 10.445,46.823,0 10.449,46.832,0 10.454,46.864,0 10.486,46.846,0 10.528,46.843,0 10.629,46.862,0 10.647,46.864,0 10.662,46.861,0 10.739,46.83,0 10.749,46.819,0 10.744,46.813,0 10.722,46.8,0 10.717,46.795,0 10.723,46.786,0 10.734,46.786,0 10.755,46.791,0 10.766,46.788,0 10.795,46.777,0 10.805,46.777,0 10.824,46.78,0 10.834,46.78,0 10.843,46.777,0 10.86,46.767,0 10.87,46.764,0 10.88,46.765,0 10.914,46.772,0 10.931,46.774,0 10.966,46.772,0 10.983,46.768,0 10.997,46.769,0 11.011,46.779,0 11.033,46.806,0 11.037,46.808,0 11.049,46.812,0 11.053,46.815,0 11.055,46.82,0 11.053,46.83,0 11.054,46.834,0 11.073,46.865,0 11.084,46.9,0 11.092,46.912,0 11.157,46.957,0 11.174,46.964,0 11.244,46.979,0 11.314,46.987,0 11.349,46.982,0 11.381,46.972,0 11.411,46.97,0 11.445,46.993,0 11.445,46.993,0 11.453,47.001,0 11.462,47.006,0 11.472,47.007,0 11.489,47.004,0 11.496,47.002,0 11.502,46.998,0 11.507,46.993,0 11.515,46.989,0 11.524,46.988,0 11.534,46.99,0 11.543,46.993,0 11.543,46.993,0 11.544,46.993,0 11.544,46.993,0 11.573,46.999,0 11.596,47,0 11.648,46.993,0 11.648,46.993,0 11.65,46.993,0 11.657,46.993,0 11.665,46.993,0 11.684,46.992,0 11.716,46.975,0 11.735,46.971,0 11.746,46.972,0 11.766,46.983,0 11.777,46.988,0 11.823,46.993,0 11.857,47.012,0 11.9,47.028,0 11.944,47.038,0 12.015,47.04,0 12.116,47.077,0 12.181,47.085,0 12.204,47.08,0 12.204,47.053,0 12.182,47.034,0 12.122,47.011,0 12.111,46.993,0 12.118,46.983,0 12.122,46.972,0 </coordinates></LinearRing></outerBoundaryIs><innerBoundaryIs><LinearRing><coordinates>12.4,43.903,0 12.429,43.892,0 12.461,43.895,0 12.479,43.917,0 12.478,43.92,0 12.478,43.923,0 12.48,43.926,0 12.483,43.929,0 12.49,43.939,0 12.492,43.956,0 12.489,43.973,0 12.482,43.983,0 12.453,43.979,0 12.421,43.967,0 12.396,43.948,0 12.386,43.925,0 12.4,43.903,0 </coordinates></LinearRing></innerBoundaryIs><innerBoundaryIs><LinearRing><coordinates>12.444,41.902,0 12.449,41.9,0 12.455,41.9,0 12.458,41.902,0 12.455,41.908,0 12.447,41.907,0 12.444,41.902,0 </coordinates></LinearRing></innerBoundaryIs></Polygon></MultiGeometry>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(k.features())[0].geometry, MultiPolygon))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_atom(self):
pass
def test_schema(self):
doc = """<Schema name="TrailHeadType" id="TrailHeadTypeId">
<SimpleField type="string" name="TrailHeadName">
<displayName><![CDATA[<b>Trail Head Name</b>]]></displayName>
</SimpleField>
<SimpleField type="double" name="TrailLength">
<displayName><![CDATA[<i>The length in miles</i>]]></displayName>
</SimpleField>
<SimpleField type="int" name="ElevationGain">
<displayName><![CDATA[<i>change in altitude</i>]]></displayName>
</SimpleField>
</Schema> """
s = kml.Schema(ns='', id='default')
s.from_string(doc)
self.assertEqual(len(list(s.simple_fields)), 3)
self.assertEqual(list(s.simple_fields)[0]['type'], 'string')
self.assertEqual(list(s.simple_fields)[1]['type'], 'double')
self.assertEqual(list(s.simple_fields)[2]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'TrailHeadName')
self.assertEqual(list(s.simple_fields)[1]['name'], 'TrailLength')
self.assertEqual(list(s.simple_fields)[2]['name'], 'ElevationGain')
self.assertEqual(list(s.simple_fields)[0][
'displayName'
], '<b>Trail Head Name</b>')
self.assertEqual(list(s.simple_fields)[1][
'displayName'
], '<i>The length in miles</i>')
self.assertEqual(list(s.simple_fields)[2][
'displayName'
], '<i>change in altitude</i>')
s1 = kml.Schema(ns='', id='default')
s1.from_string(s.to_string())
self.assertEqual(len(list(s1.simple_fields)), 3)
self.assertEqual(list(s1.simple_fields)[0]['type'], 'string')
self.assertEqual(list(s1.simple_fields)[1]['name'], 'TrailLength')
self.assertEqual(list(s1.simple_fields)[2][
'displayName'
], '<i>change in altitude</i>')
self.assertEqual(s.to_string(), s1.to_string())
doc1 = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
%s
</Document>
</kml>""" % doc
k = kml.KML()
k.from_string(doc1)
d = list(k.features())[0]
s2 = list(d.schemata())[0]
s.ns = config.NS
self.assertEqual(s.to_string(), s2.to_string())
k1 = kml.KML()
k1.from_string(k.to_string())
self.assertTrue('Schema' in k1.to_string())
self.assertTrue('SimpleField' in k1.to_string())
self.assertEqual(k1.to_string(), k.to_string())
def test_schema_data(self):
doc = """<SchemaData schemaUrl="#TrailHeadTypeId">
<SimpleData name="TrailHeadName">Pi in the sky</SimpleData>
<SimpleData name="TrailLength">3.14159</SimpleData>
<SimpleData name="ElevationGain">10</SimpleData>
</SchemaData>"""
sd = kml.SchemaData(ns='', schema_url='#default')
sd.from_string(doc)
self.assertEqual(sd.schema_url, '#TrailHeadTypeId')
self.assertEqual(
sd.data[0], {'name': 'TrailHeadName',
'value': 'Pi in the sky'})
self.assertEqual(
sd.data[1], {'name': 'TrailLength',
'value': '3.14159'})
self.assertEqual(sd.data[2], {'name': 'ElevationGain', 'value': '10'})
sd1 = kml.SchemaData(ns='', schema_url='#default')
sd1.from_string(sd.to_string())
self.assertEqual(sd1.schema_url, '#TrailHeadTypeId')
self.assertEqual(sd.to_string(), sd1.to_string())
def test_snippet(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<Snippet maxLines="2" >Short Desc</Snippet>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].snippet['text'], 'Short Desc')
self.assertEqual(list(k.features())[0].snippet['maxLines'], 2)
list(k.features())[0]._snippet['maxLines'] = 3
self.assertEqual(list(k.features())[0].snippet['maxLines'], 3)
self.assertTrue('maxLines="3"' in k.to_string())
list(k.features())[0].snippet = {'text': 'Annother Snippet'}
self.assertFalse('maxLines' in k.to_string())
self.assertTrue('Annother Snippet' in k.to_string())
list(k.features())[0].snippet = 'Diffrent Snippet'
self.assertFalse('maxLines' in k.to_string())
self.assertTrue('Diffrent Snippet' in k.to_string())
def test_from_wrong_string(self):
doc = kml.KML()
self.assertRaises(TypeError, doc.from_string, '<xml></xml>')
def test_address(self):
doc = kml.Document()
doc.from_string("""
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2" id="pm-id">
<kml:name>pm-name</kml:name>
<kml:description>pm-description</kml:description>
<kml:visibility>1</kml:visibility>
<kml:address>1600 Amphitheatre Parkway, Mountain View, CA 94043, USA</kml:address>
</kml:Document>
""")
doc2 = kml.Document()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_phone_number(self):
doc = kml.Document()
doc.from_string("""
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2" id="pm-id">
<kml:name>pm-name</kml:name>
<kml:description>pm-description</kml:description>
<kml:visibility>1</kml:visibility>
<kml:phoneNumber>+1 234 567 8901</kml:phoneNumber>
</kml:Document>
""")
doc2 = kml.Document()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_groundoverlay(self):
doc = kml.KML()
doc.from_string(
"""
<kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
<name>Ground Overlays</name>
<description>Examples of ground overlays</description>
<GroundOverlay>
<name>Large-scale overlay on terrain</name>
<description>Overlay shows Mount Etna erupting
on July 13th, 2001.</description>
<Icon>
<href>http://developers.google.com/kml/documentation/images/etna.jpg</href>
</Icon>
<LatLonBox>
<north>37.91904192681665</north>
<south>37.46543388598137</south>
<east>15.35832653742206</east>
<west>14.60128369746704</west>
<rotation>-0.1556640799496235</rotation>
</LatLonBox>
</GroundOverlay>
</Folder>
</kml>
""")
doc2 = kml.KML()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_linarring_placemark(self):
doc = kml.KML()
doc.from_string( """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<LinearRing>
<coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,0.0</coordinates>
</LinearRing>
</Placemark> </kml>""")
doc2 = kml.KML()
doc2.from_string(doc.to_string())
self.assertTrue(
isinstance(list(doc.features())[0].geometry, LinearRing))
self.assertEqual(doc.to_string(), doc2.to_string())
class StyleTestCase(unittest.TestCase):
def test_styleurl(self):
f = kml.Document()
f.styleUrl = '#somestyle'
self.assertEqual(f.styleUrl, '#somestyle')
self.assertTrue(isinstance(f._styleUrl, styles.StyleUrl))
s = styles.StyleUrl(config.NS, url='#otherstyle')
f.styleUrl = s
self.assertTrue(isinstance(f._styleUrl, styles.StyleUrl))
self.assertEqual(f.styleUrl, '#otherstyle')
f2 = kml.Document()
f2.from_string(f.to_string())
self.assertEqual(f.to_string(), f2.to_string())
def test_style(self):
lstyle = styles.LineStyle(color='red', width=2.0)
style = styles.Style(styles=[lstyle])
f = kml.Document(styles=[style])
f2 = kml.Document()
f2.from_string(f.to_string(prettyprint=True))
self.assertEqual(f.to_string(), f2.to_string())
def test_polystyle_fill(self):
style = styles.PolyStyle()
def test_polystyle_outline(self):
style = styles.PolyStyle()
class StyleUsageTestCase(unittest.TestCase):
def test_create_document_style(self):
style = styles.Style(styles=[styles.PolyStyle(color='7f000000')])
doc = kml.Document(styles=[style])
doc2 = kml.Document()
doc2.append_style(style)
expected = """
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:visibility>1</kml:visibility>
<kml:Style>
<kml:PolyStyle>
<kml:color>7f000000</kml:color>
<kml:fill>1</kml:fill>
<kml:outline>1</kml:outline>
</kml:PolyStyle>
</kml:Style>
</kml:Document>
"""
doc3 = kml.Document()
doc3.from_string(expected)
self.assertEqual(doc.to_string(), doc2.to_string())
self.assertEqual(doc2.to_string(), doc3.to_string())
self.assertEqual(doc.to_string(), doc3.to_string())
def test_create_placemark_style(self):
style = styles.Style(styles=[styles.PolyStyle(color='7f000000')])
place = kml.Placemark(styles=[style])
place2 = kml.Placemark()
place2.append_style(style)
expected = """
<kml:Placemark xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:visibility>1</kml:visibility>
<kml:Style>
<kml:PolyStyle>
<kml:color>7f000000</kml:color>
<kml:fill>1</kml:fill>
<kml:outline>1</kml:outline>
</kml:PolyStyle>
</kml:Style>
</kml:Placemark>
"""
place3 = kml.Placemark()
place3.from_string(expected)
self.assertEqual(place.to_string(), place2.to_string())
self.assertEqual(place2.to_string(), place3.to_string())
self.assertEqual(place.to_string(), place3.to_string())
class StyleFromStringTestCase(unittest.TestCase):
def test_styleurl(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<styleUrl>#default</styleUrl>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(list(k.features())[0].styleUrl, '#default')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_balloonstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<Style id="exampleBalloonStyle">
<BalloonStyle>
<!-- a background color for the balloon -->
<bgColor>ffffffbb</bgColor>
<!-- styling of the balloon text -->
<textColor>ff000000</textColor>
<text><![CDATA[
<b><font color="#CC0000" size="+3">$[name]</font></b>
<br/><br/>
<font face="Courier">$[description]</font>
<br/><br/>
Extra text that will appear in the description balloon
<br/><br/>
<!-- insert the to/from hyperlinks -->
$[geDirections]
]]></text>
<!-- kml:displayModeEnum -->
<displayMode>default</displayMode>
</BalloonStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.BalloonStyle))
self.assertEqual(style.bgColor, 'ffffffbb')
self.assertEqual(style.textColor, 'ff000000')
self.assertEqual(style.displayMode, 'default')
self.assertTrue('$[geDirections]' in style.text)
self.assertTrue('$[description]' in style.text)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k2.to_string(), k.to_string())
def test_balloonstyle_old_color(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<Style id="exampleBalloonStyle">
<BalloonStyle>
<!-- a background color for the balloon -->
<color>ffffffbb</color>
</BalloonStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.BalloonStyle))
self.assertEqual(style.bgColor, 'ffffffbb')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k2.to_string(), k.to_string())
def test_labelstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.LabelStyle))
self.assertEqual(style.color, 'ff0000cc')
self.assertEqual(style.colorMode, None)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_iconstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Style id="randomColorIcon">
<IconStyle>
<color>ff00ff00</color>
<colorMode>random</colorMode>
<scale>1.1</scale>
<heading>0</heading>
<Icon>
<href>http://maps.google.com/icon21.png</href>
</Icon>
</IconStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list((k.features()))), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.IconStyle))
self.assertEqual(style.color, 'ff00ff00')
self.assertEqual(style.scale, 1.1)
self.assertEqual(style.colorMode, 'random')
self.assertEqual(style.heading, 0.0)
self.assertEqual(style.icon_href, 'http://maps.google.com/icon21.png')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_linestyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>LineStyle.kml</name>
<open>1</open>
<Style id="linestyleExample">
<LineStyle>
<color>7f0000ff</color>
<width>4</width>
</LineStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.LineStyle))
self.assertEqual(style.color, '7f0000ff')
self.assertEqual(style.width, 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<color>ff0000cc</color>
<colorMode>random</colorMode>
</PolyStyle>
</Style>
</Document>
</kml>"""
# XXX fill and outline
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.color, 'ff0000cc')
self.assertEqual(style.colorMode, 'random')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle_float_fill(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<fill>0.0</fill>
</PolyStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.fill, 0)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle_float_outline(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<outline>0.0</outline>
</PolyStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.outline, 0)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_styles(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<!-- Begin Style Definitions -->
<Style id="myDefaultStyles">
<IconStyle>
<color>a1ff00ff</color>
<scale>1.399999976158142</scale>
<Icon>
<href>http://myserver.com/icon.jpg</href>
</Icon>
</IconStyle>
<LabelStyle>
<color>7fffaaff</color>
<scale>1.5</scale>
</LabelStyle>
<LineStyle>
<color>ff0000ff</color>
<width>15</width>
</LineStyle>
<PolyStyle>
<color>7f7faaaa</color>
<colorMode>random</colorMode>
</PolyStyle>
</Style>
<!-- End Style Definitions -->
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())
self.assertEqual(len(style), 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_stylemapurl(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<styleUrl>#normalState</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#highlightState</styleUrl>
</Pair>
</StyleMap>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(
list(list(k.features())[0].styles())[0], styles.StyleMap))
sm = list(list(list(k.features())[0].styles()))[0]
self.assertTrue(isinstance(sm.normal, styles.StyleUrl))
self.assertEqual(sm.normal.url, '#normalState')
self.assertTrue(isinstance(sm.highlight, styles.StyleUrl))
self.assertEqual(sm.highlight.url, '#highlightState')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_stylemapstyles(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
</Pair>
<Pair>
<key>highlight</key>
<Style id="examplePolyStyle">
<PolyStyle>
<color>ff0000cc</color>
<colorMode>random</colorMode>
</PolyStyle>
<LineStyle>
<color>ff0000ff</color>
<width>15</width>
</LineStyle>
</Style>
</Pair>
</StyleMap>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(
list(list(k.features())[0].styles())[0], styles.StyleMap))
sm = list(list(list(k.features())[0].styles()))[0]
self.assertTrue(isinstance(sm.normal, styles.Style))
self.assertEqual(len(list(sm.normal.styles())), 1)
self.assertTrue(
isinstance(list(sm.normal.styles())[0], styles.LabelStyle))
self.assertTrue(isinstance(sm.highlight, styles.Style))
self.assertTrue(isinstance(sm.highlight, styles.Style))
self.assertEqual(len(list(sm.highlight.styles())), 2)
self.assertTrue(
isinstance(list(sm.highlight.styles())[0], styles.LineStyle))
self.assertTrue(
isinstance(list(sm.highlight.styles())[1], styles.PolyStyle))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_get_style_by_url(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<styleUrl>#normalState</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#highlightState</styleUrl>
</Pair>
</StyleMap>
<Style id="linestyleExample">
<LineStyle>
<color>7f0000ff</color>
<width>4</width>
</LineStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
document = list(k.features())[0]
style = document.get_style_by_url(
'http://localhost:8080/somepath#exampleStyleDocument')
self.assertTrue(isinstance(list(style.styles())[0], styles.LabelStyle))
style = document.get_style_by_url('somepath#linestyleExample')
self.assertTrue(isinstance(list(style.styles())[0], styles.LineStyle))
style = document.get_style_by_url('#styleMapExample')
self.assertTrue(isinstance(style, styles.StyleMap))
class DateTimeTestCase(unittest.TestCase):
def test_timestamp(self):
now = datetime.datetime.now()
ts = kml.TimeStamp(timestamp=now)
self.assertEqual(ts.timestamp, [now, 'dateTime'])
self.assertTrue('TimeStamp>' in str(ts.to_string()))
self.assertTrue('when>' in str(ts.to_string()))
self.assertTrue(now.isoformat() in str(ts.to_string()))
y2k = datetime.date(2000, 1, 1)
ts = kml.TimeStamp(timestamp=y2k)
self.assertEqual(ts.timestamp, [y2k, 'date'])
self.assertTrue('2000-01-01' in str(ts.to_string()))
def test_timestamp_resolution(self):
now = datetime.datetime.now()
ts = kml.TimeStamp(timestamp=now)
self.assertTrue(now.isoformat() in str(ts.to_string()))
ts.timestamp[1] = 'date'
self.assertTrue(now.date().isoformat() in str(ts.to_string()))
self.assertFalse(now.isoformat() in str(ts.to_string()))
year = str(now.year)
ym = now.strftime('%Y-%m')
ts.timestamp[1] = 'gYearMonth'
self.assertTrue(ym in str(ts.to_string()))
self.assertFalse(now.date().isoformat() in str(ts.to_string()))
ts.timestamp[1] = 'gYear'
self.assertTrue(year in str(ts.to_string()))
self.assertFalse(ym in str(ts.to_string()))
ts.timestamp = None
self.assertRaises(TypeError, ts.to_string)
def test_timespan(self):
now = datetime.datetime.now()
y2k = datetime.datetime(2000, 1, 1)
ts = kml.TimeSpan(end=now, begin=y2k)
self.assertEqual(ts.end, [now, 'dateTime'])
self.assertEqual(ts.begin, [y2k, 'dateTime'])
self.assertTrue('TimeSpan>' in str(ts.to_string()))
self.assertTrue('begin>' in str(ts.to_string()))
self.assertTrue('end>' in str(ts.to_string()))
self.assertTrue(now.isoformat() in str(ts.to_string()))
self.assertTrue(y2k.isoformat() in str(ts.to_string()))
ts.end = None
self.assertFalse(now.isoformat() in str(ts.to_string()))
self.assertTrue(y2k.isoformat() in str(ts.to_string()))
ts.begin = None
self.assertRaises(ValueError, ts.to_string)
def test_feature_timestamp(self):
now = datetime.datetime.now()
f = kml.Document()
f.timeStamp = now
self.assertEqual(f.timeStamp, now)
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('TimeStamp>' in str(f.to_string()))
self.assertTrue('when>' in str(f.to_string()))
f.timeStamp = now.date()
self.assertTrue(now.date().isoformat() in str(f.to_string()))
self.assertFalse(now.isoformat() in str(f.to_string()))
f.timeStamp = None
self.assertFalse('TimeStamp>' in str(f.to_string()))
def test_feature_timespan(self):
now = datetime.datetime.now()
y2k = datetime.date(2000, 1, 1)
f = kml.Document()
f.begin = y2k
f.end = now
self.assertEqual(f.begin, y2k)
self.assertEqual(f.end, now)
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
f.end = None
self.assertFalse(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertFalse('end>' in str(f.to_string()))
f.begin = None
self.assertFalse('TimeSpan>' in str(f.to_string()))
def test_feature_timespan_stamp(self):
now = datetime.datetime.now()
y2k = datetime.date(2000, 1, 1)
f = kml.Document()
f.begin = y2k
f.end = now
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
self.assertFalse('TimeStamp>' in str(f.to_string()))
self.assertFalse('when>' in str(f.to_string()))
# when we set a timestamp an existing timespan will be deleted
f.timeStamp = now
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('TimeStamp>' in str(f.to_string()))
self.assertTrue('when>' in str(f.to_string()))
self.assertFalse('2000-01-01' in str(f.to_string()))
self.assertFalse('TimeSpan>' in str(f.to_string()))
self.assertFalse('begin>' in str(f.to_string()))
self.assertFalse('end>' in str(f.to_string()))
# when we set a timespan an existing timestamp will be deleted
f.end = y2k
self.assertFalse(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertFalse('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
self.assertFalse('TimeStamp>' in str(f.to_string()))
self.assertFalse('when>' in str(f.to_string()))
# We manipulate our Feature so it has timespan and stamp
ts = kml.TimeStamp(timestamp=now)
f._time_stamp = ts
# this raises an exception as only either timespan or timestamp
# are allowed not both
self.assertRaises(ValueError, f.to_string)
def test_read_timestamp(self):
ts = kml.TimeStamp(ns='')
doc = """
<TimeStamp>
<when>1997</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYear')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 1, 1, 0, 0))
doc = """
<TimeStamp>
<when>1997-07</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYearMonth')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 7, 1, 0, 0))
doc = """
<TimeStamp>
<when>199808</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYearMonth')
self.assertEqual(ts.timestamp[0], datetime.datetime(1998, 8, 1, 0, 0))
doc = """
<TimeStamp>
<when>1997-07-16</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'date')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 7, 16, 0, 0))
# dateTime (YYYY-MM-DDThh:mm:ssZ)
# Here, T is the separator between the calendar and the hourly notation
# of time, and Z indicates UTC. (Seconds are required.)
doc = """
<TimeStamp>
<when>1997-07-16T07:30:15Z</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'dateTime')
self.assertEqual(ts.timestamp[0], datetime.datetime(
1997, 7, 16, 7, 30, 15,
tzinfo=tzutc()))
doc = """
<TimeStamp>
<when>1997-07-16T10:30:15+03:00</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'dateTime')
self.assertEqual(ts.timestamp[0], datetime.datetime(
1997, 7, 16, 10, 30, 15,
tzinfo=tzoffset(None, 10800)))
def test_read_timespan(self):
ts = kml.TimeSpan(ns='')
doc = """
<TimeSpan>
<begin>1876-08-01</begin>
<end>1997-07-16T07:30:15Z</end>
</TimeSpan>
"""
ts.from_string(doc)
self.assertEqual(ts.begin[1], 'date')
self.assertEqual(ts.begin[0], datetime.datetime(1876, 8, 1, 0, 0))
self.assertEqual(ts.end[1], 'dateTime')
self.assertEqual(ts.end[0], datetime.datetime(
1997, 7, 16, 7, 30, 15,
tzinfo=tzutc()))
def test_featurefromstring(self):
d = kml.Document(ns='')
doc = """<Document>
<name>Document.kml</name>
<open>1</open>
<TimeStamp>
<when>1997-07-16T10:30:15+03:00</when>
</TimeStamp>
<TimeSpan>
<begin>1876-08-01</begin>
<end>1997-07-16T07:30:15Z</end>
</TimeSpan>
</Document>"""
d.from_string(doc)
class AtomTestCase(unittest.TestCase):
def test_author(self):
a = atom.Author(name="Christian Ledermann")
self.assertEqual(a.name, "Christian Ledermann")
a.uri = 'http://iwlearn.net'
a.email = 'christian@gmail.com'
self.assertTrue("Christian Ledermann" in str(a.to_string()))
self.assertTrue('http://iwlearn.net' in str(a.to_string()))
self.assertTrue('christian@gmail.com' in str(a.to_string()))
self.assertTrue('name>' in str(a.to_string()))
self.assertTrue('uri>' in str(a.to_string()))
self.assertTrue('email>' in str(a.to_string()))
# print (a.to_string())
a.email = 'christian'
self.assertFalse('email>' in str(a.to_string()))
a2 = atom.Author()
a2.from_string(a.to_string())
self.assertEqual(a.to_string(), a2.to_string())
def test_link(self):
l = atom.Link(href="http://localhost/", rel="alternate")
self.assertEqual(l.href, "http://localhost/")
self.assertEqual(l.rel, "alternate")
l.title = "Title"
l.type = "text/html"
l.hreflang = 'en'
l.length = "4096"
self.assertTrue('href="http://localhost/"' in str(l.to_string()))
self.assertTrue('rel="alternate"' in str(l.to_string()))
self.assertTrue('title="Title"' in str(l.to_string()))
self.assertTrue('hreflang="en"' in str(l.to_string()))
self.assertTrue('type="text/html"' in str(l.to_string()))
self.assertTrue('length="4096"' in str(l.to_string()))
self.assertTrue('link' in str(l.to_string()))
self.assertTrue('="http://www.w3.org/2005/Atom"' in str(l.to_string()))
l2 = atom.Link()
l2.from_string(l.to_string())
self.assertEqual(l.to_string(), l2.to_string())
l.href = None
self.assertRaises(ValueError, l.to_string)
class SetGeometryTestCase(unittest.TestCase):
def test_altitude_mode(self):
geom = Geometry()
geom.geometry = Point(0, 1)
self.assertEqual(geom.altitude_mode, None)
self.assertFalse('altitudeMode' in str(geom.to_string()))
geom.altitude_mode = 'unknown'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'clampToSeaFloor'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'relativeToSeaFloor'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'clampToGround'
self.assertFalse('altitudeMode' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertTrue(
'altitudeMode>relativeToGround</' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertTrue('altitudeMode>absolute</' in str(geom.to_string()))
def test_extrude(self):
geom = Geometry()
self.assertEqual(geom.extrude, False)
geom.geometry = Point(0, 1)
geom.extrude = False
self.assertFalse('extrude' in str(geom.to_string()))
geom.extrude = True
geom.altitude_mode = 'clampToGround'
self.assertFalse('extrude' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertTrue('extrude>1</' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertTrue('extrude>1</' in str(geom.to_string()))
def test_tesselate(self):
geom = Geometry()
self.assertEqual(geom.tessellate, False)
geom.geometry = LineString([(0, 0), (1, 1)])
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'clampToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.tessellate = True
geom.altitude_mode = None
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'clampToGround'
self.assertTrue('tessellate>1</' in str(geom.to_string()))
# for geometries != LineString tesselate is ignored
geom.geometry = Point(0, 1)
self.assertFalse('tessellate' in str(geom.to_string()))
geom.geometry = Polygon([(0, 0), (1, 0), (1, 1), (0, 0)])
self.assertFalse('tessellate' in str(geom.to_string()))
def test_point(self):
p = Point(0, 1)
g = Geometry(geometry=p)
self.assertEqual(g.geometry, p)
g = Geometry(geometry=p.__geo_interface__)
self.assertEqual(g.geometry.__geo_interface__, p.__geo_interface__)
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
def test_linestring(self):
l = LineString([(0, 0), (1, 1)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,1.000000</' in
str(g.to_string()))
g2 = Geometry()
g2.from_string(g.to_string())
self.assertEqual(g.to_string(), g2.to_string())
def test_linearring(self):
l = LinearRing([(0, 0), (1, 0), (1, 1), (0, 0)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
def test_polygon(self):
# without holes
l = Polygon([(0, 0), (1, 0), (1, 1), (0, 0)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertFalse('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
# with holes
p = Polygon(
[(-1, -1), (2, -1), (2, 2), (-1, -1)], [[(0, 0), (1, 0), (1, 1),
(0, 0)]], )
g = Geometry(geometry=p)
self.assertEqual(g.geometry, p)
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertTrue('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</'
in str(g.to_string()))
def test_multipoint(self):
p0 = Point(0, 1)
p1 = Point(1, 1)
g = Geometry(geometry=MultiPoint([p0, p1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
self.assertTrue(
'coordinates>1.000000,1.000000</' in str(g.to_string()))
def test_multilinestring(self):
l0 = LineString([(0, 0), (1, 0)])
l1 = LineString([(0, 1), (1, 1)])
g = Geometry(geometry=MultiLineString([l0, l1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000</' in
str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000 1.000000,1.000000</' in
str(g.to_string()))
def test_multipolygon(self):
# with holes
p0 = Polygon(
[(-1, -1), (2, -1), (2, 2), (-1, -1)], [[(0, 0), (1, 0), (1, 1),
(0, 0)]])
# without holes
p1 = Polygon([(3, 0), (4, 0), (4, 1), (3, 0)])
g = Geometry(geometry=MultiPolygon([p0, p1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertTrue('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</'
in str(g.to_string()))
def test_geometrycollection(self):
po = Polygon([(3, 0), (4, 0), (4, 1), (3, 0)])
lr = LinearRing([(0, -1), (1, -1), (1, 1), (0, -1)])
ls = LineString([(0, 0), (1, 1)])
p = Point(0, 1)
# geo_if = {'type': 'GeometryCollection', 'geometries': [
# po.__geo_interface__, p.__geo_interface__,
# ls.__geo_interface__, lr.__geo_interface__]}
g = Geometry(geometry=GeometryCollection([po, p, ls, lr]))
# g1 = Geometry(geometry=as_shape(geo_if))
# self.assertEqual(g1.__geo_interface__, g.__geo_interface__)
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertFalse('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</'
in str(g.to_string()))
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,1.000000</' in
str(g.to_string()))
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
class GetGeometryTestCase(unittest.TestCase):
def test_altitude_mode(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:altitudeMode>clampToGround</kml:altitudeMode>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.altitude_mode, None)
g.from_string(doc)
self.assertEqual(g.altitude_mode, 'clampToGround')
def test_extrude(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:extrude>1</kml:extrude>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.extrude, False)
g.from_string(doc)
self.assertEqual(g.extrude, True)
def test_tesselate(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:tessellate>1</kml:tessellate>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.tessellate, False)
g.from_string(doc)
self.assertEqual(g.tessellate, True)
def test_point(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__,
{'type': 'Point',
'coordinates': (0.0, 1.0)})
def test_linestring(self):
doc = """<kml:LineString xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,0.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__,
{'type': 'LineString',
'coordinates': ((0.0, 0.0), (1.0, 1.0))})
def test_linearring(self):
doc = """<kml:LinearRing xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'LinearRing',
'coordinates': ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0))
})
def test_polygon(self):
doc = """<kml:Polygon xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'Polygon',
'coordinates': ((
(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)
), )
})
doc = """<kml:Polygon xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
<kml:innerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:innerBoundaryIs>
</kml:Polygon>
"""
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'Polygon',
'coordinates': (
((-1.0, -1.0), (2.0, -1.0), (2.0, 2.0),
(-1.0, -1.0)), ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0),
(0.0, 0.0)),
)
})
def test_multipoint(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Point>
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>
<kml:Point>
<kml:coordinates>1.000000,1.000000</kml:coordinates>
</kml:Point>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_multilinestring(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:LineString>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000</kml:coordinates>
</kml:LineString>
<kml:LineString>
<kml:coordinates>0.000000,1.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_multipolygon(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
<kml:innerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:innerBoundaryIs>
</kml:Polygon>
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_geometrycollection(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>3,0 4,0 4,1 3,0</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
<kml:Point>
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>
<kml:LineString>
<kml:coordinates>0.000000,0.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>
<kml:LinearRing>
<kml:coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,1.0 0.0,0.0</kml:coordinates>
</kml:LinearRing>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 4)
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:LinearRing>
<kml:coordinates>3.0,0.0 4.0,0.0 4.0,1.0 3.0,0.0</kml:coordinates>
</kml:LinearRing>
<kml:LinearRing>
<kml:coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,0.0</kml:coordinates>
</kml:LinearRing>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
self.assertEqual(g.geometry.geom_type, 'GeometryCollection')
class Force3DTestCase(unittest.TestCase):
def setUp(self):
config.FORCE3D = False
def tearDown(self):
# Important: Set FORCE3D back to False!
config.FORCE3D = False
def test3d(self):
config.FORCE3D = True
ns = ''
p2 = kml.Placemark(ns, 'id', 'name', 'description')
p2.geometry = Polygon([(0, 0), (1, 1), (1, 0)])
p3 = kml.Placemark(ns, 'id', 'name', 'description')
p3.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 0)])
self.assertEqual(p2.to_string(), p3.to_string())
def testno3d(self):
config.FORCE3D = False
ns = ''
p2 = kml.Placemark(ns, 'id', 'name', 'description')
p2.geometry = Polygon([(0, 0), (1, 1), (1, 0)])
p3 = kml.Placemark(ns, 'id', 'name', 'description')
p3.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 0)])
self.assertNotEqual(p2.to_string(), p3.to_string())
class BaseFeatureTestCase(unittest.TestCase):
def test_address_string(self):
f = kml._Feature()
address = '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
f.address = address
self.assertEqual(f.address, address)
def test_address_none(self):
f = kml._Feature()
f.address = None
self.assertEqual(f.address, None)
def test_address_value_error(self):
f = kml._Feature()
with self.assertRaises(ValueError):
f.address = 123
def test_phone_number_string(self):
f = kml._Feature()
f.phoneNumber = '+1-234-567-8901'
self.assertEqual(f.phoneNumber, '+1-234-567-8901')
def test_phone_number_none(self):
f = kml._Feature()
f.phoneNumber = None
self.assertEqual(f.phoneNumber, None)
def test_phone_number_value_error(self):
f = kml._Feature()
with self.assertRaises(ValueError):
f.phoneNumber = 123
class BaseOverlayTestCase(unittest.TestCase):
def test_color_string(self):
o = kml._Overlay(name='An Overlay')
o.color = '00010203'
self.assertEqual(o.color, '00010203')
def test_color_none(self):
o = kml._Overlay(name='An Overlay')
o.color = '00010203'
self.assertEqual(o.color, '00010203')
o.color = None
self.assertEqual(o.color, None)
def test_color_value_error(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.color = object()
def test_draw_order_string(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = '1'
self.assertEqual(o.drawOrder, '1')
def test_draw_order_int(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = 1
self.assertEqual(o.drawOrder, '1')
def test_draw_order_none(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = '1'
self.assertEqual(o.drawOrder, '1')
o.drawOrder = None
self.assertEqual(o.drawOrder, None)
def test_draw_order_value_error(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.drawOrder = object()
def test_icon_without_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = 'http://example.com/'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_open_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_close_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = 'http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_to_none(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
o.icon = None
self.assertEqual(o.icon, None)
def test_icon_raise_exception(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.icon = 12345
class GroundOverlayTestCase(unittest.TestCase):
def setUp(self):
self.g = kml.GroundOverlay()
def test_altitude_int(self):
self.g.altitude = 123
self.assertEqual(self.g.altitude, '123')
def test_altitude_float(self):
self.g.altitude = 123.4
self.assertEqual(self.g.altitude, '123.4')
def test_altitude_string(self):
self.g.altitude = '123'
self.assertEqual(self.g.altitude, '123')
def test_altitude_value_error(self):
with self.assertRaises(ValueError):
self.g.altitude = object()
def test_altitude_none(self):
self.g.altitude = '123'
self.assertEqual(self.g.altitude, '123')
self.g.altitude = None
self.assertEqual(self.g.altitude, None)
def test_altitude_mode_default(self):
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_error(self):
self.g.altitudeMode = ''
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_clamp(self):
self.g.altitudeMode = 'clampToGround'
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_absolute(self):
self.g.altitudeMode = 'absolute'
self.assertEqual(self.g.altitudeMode, 'absolute')
def test_latlonbox_function(self):
self.g.latLonBox(10, 20, 30, 40, 50)
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_string(self):
self.g.north = '10'
self.g.south = '20'
self.g.east = '30'
self.g.west = '40'
self.g.rotation = '50'
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_int(self):
self.g.north = 10
self.g.south = 20
self.g.east = 30
self.g.west = 40
self.g.rotation = 50
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_float(self):
self.g.north = 10.0
self.g.south = 20.0
self.g.east = 30.0
self.g.west = 40.0
self.g.rotation = 50.0
self.assertEqual(self.g.north, '10.0')
self.assertEqual(self.g.south, '20.0')
self.assertEqual(self.g.east, '30.0')
self.assertEqual(self.g.west, '40.0')
self.assertEqual(self.g.rotation, '50.0')
def test_latlonbox_value_error(self):
with self.assertRaises(ValueError):
self.g.north = object()
with self.assertRaises(ValueError):
self.g.south = object()
with self.assertRaises(ValueError):
self.g.east = object()
with self.assertRaises(ValueError):
self.g.west = object()
with self.assertRaises(ValueError):
self.g.rotation = object()
self.assertEqual(self.g.north, None)
self.assertEqual(self.g.south, None)
self.assertEqual(self.g.east, None)
self.assertEqual(self.g.west, None)
self.assertEqual(self.g.rotation, None)
def test_latlonbox_empty_string(self):
self.g.north = ''
self.g.south = ''
self.g.east = ''
self.g.west = ''
self.g.rotation = ''
self.assertEqual(self.g.north, '')
self.assertEqual(self.g.south, '')
self.assertEqual(self.g.east, '')
self.assertEqual(self.g.west, '')
self.assertEqual(self.g.rotation, '')
def test_latlonbox_none(self):
self.g.north = None
self.g.south = None
self.g.east = None
self.g.west = None
self.g.rotation = None
self.assertEqual(self.g.north, None)
self.assertEqual(self.g.south, None)
self.assertEqual(self.g.east, None)
self.assertEqual(self.g.west, None)
self.assertEqual(self.g.rotation, None)
class GroundOverlayStringTestCase(unittest.TestCase):
def test_default_to_string(self):
g = kml.GroundOverlay()
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_to_string(self):
g = kml.GroundOverlay()
g.icon = 'http://example.com'
g.drawOrder = 1
g.color = '00010203'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:color>00010203</kml:color>'
'<kml:drawOrder>1</kml:drawOrder>'
'<kml:icon><href>http://example.com</href></kml:icon>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_int(self):
g = kml.GroundOverlay()
g.altitude = 123
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_float(self):
g = kml.GroundOverlay()
g.altitude = 123.4
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_string(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_absolute(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 'absolute'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>absolute</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_unknown_string(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 'unknown string'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_value(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 1234
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_no_rotation(self):
g = kml.GroundOverlay()
g.latLonBox(10, 20, 30, 40)
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>0</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_rotation(self):
g = kml.GroundOverlay()
g.latLonBox(10, 20, 30, 40, 50)
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>50</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_nswer(self):
g = kml.GroundOverlay()
g.north = 10
g.south = 20
g.east = 30
g.west = 40
g.rotation = 50
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>50</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(BaseClassesTestCase))
suite.addTest(unittest.makeSuite(BuildKmlTestCase))
suite.addTest(unittest.makeSuite(KmlFromStringTestCase))
suite.addTest(unittest.makeSuite(StyleTestCase))
suite.addTest(unittest.makeSuite(StyleFromStringTestCase))
suite.addTest(unittest.makeSuite(DateTimeTestCase))
suite.addTest(unittest.makeSuite(AtomTestCase))
suite.addTest(unittest.makeSuite(SetGeometryTestCase))
suite.addTest(unittest.makeSuite(GetGeometryTestCase))
suite.addTest(unittest.makeSuite(Force3DTestCase))
suite.addTest(unittest.makeSuite(BaseOverlayTestCase))
suite.addTest(unittest.makeSuite(GroundOverlayTestCase))
return suite
if __name__ == '__main__':
unittest.main()
| 58.187669 | 53,811 | 0.602939 |
try:
import unittest2 as unittest
except:
import unittest
from fastkml import kml
from fastkml import styles
from fastkml import base
from fastkml import atom
from fastkml import config
from fastkml import gx
import datetime
from dateutil.tz import tzutc, tzoffset
from fastkml.config import etree
from fastkml.geometry import Point, LineString, Polygon
from fastkml.geometry import MultiPoint, MultiLineString, MultiPolygon
from fastkml.geometry import LinearRing, GeometryCollection
from fastkml.geometry import Geometry
class BaseClassesTestCase(unittest.TestCase):
def test_base_object(self):
bo = base._BaseObject(id='id0')
self.assertEqual(bo.id, 'id0')
self.assertEqual(bo.ns, config.NS)
self.assertEqual(bo.targetId, None)
self.assertEqual(bo.__name__, None)
bo.targetId = 'target'
self.assertEqual(bo.targetId, 'target')
bo.ns = ''
bo.id = None
self.assertEqual(bo.id, None)
self.assertEqual(bo.ns, '')
self.assertRaises(NotImplementedError, bo.etree_element)
element = etree.Element(config.NS + 'Base')
self.assertRaises(TypeError, bo.from_element)
self.assertRaises(TypeError, bo.from_element, element)
bo.__name__ = 'NotABaseObject'
self.assertRaises(TypeError, bo.from_element, element)
bo.__name__ = 'Base'
bo.ns = config.NS
bo.from_element(element)
self.assertEqual(bo.id, None)
self.assertEqual(bo.ns, config.NS)
self.assertFalse(bo.etree_element(), None)
self.assertTrue(len(bo.to_string()) > 1)
def test_feature(self):
f = kml._Feature(name='A Feature')
self.assertRaises(NotImplementedError, f.etree_element)
self.assertEqual(f.name, 'A Feature')
self.assertEqual(f.visibility, 1)
self.assertEqual(f.isopen, 0)
self.assertEqual(f._atom_author, None)
self.assertEqual(f._atom_link, None)
self.assertEqual(f.address, None)
self.assertEqual(f._snippet, None)
self.assertEqual(f.description, None)
self.assertEqual(f._styleUrl, None)
self.assertEqual(f._styles, [])
self.assertEqual(f._time_span, None)
self.assertEqual(f._time_stamp, None)
f.__name__ = 'Feature'
f.styleUrl = '#default'
self.assertTrue('Feature>' in str(f.to_string()))
self.assertTrue('#default' in str(f.to_string()))
def test_container(self):
f = kml._Container(name='A Container')
p = kml.Placemark()
f.append(p)
self.assertRaises(NotImplementedError, f.etree_element)
def test_overlay(self):
o = kml._Overlay(name='An Overlay')
self.assertEqual(o._color, None)
self.assertEqual(o._drawOrder, None)
self.assertEqual(o._icon, None)
self.assertRaises(NotImplementedError, o.etree_element)
def test_atom_link(self):
ns = '{http://www.opengis.net/kml/2.2}'
l = atom.Link(ns=ns)
self.assertEqual(l.ns, ns)
def test_atom_person(self):
ns = '{http://www.opengis.net/kml/2.2}'
p = atom._Person(ns=ns)
self.assertEqual(p.ns, ns)
class BuildKmlTestCase(unittest.TestCase):
def test_kml(self):
k = kml.KML()
self.assertEqual(len(list(k.features())), 0)
if config.LXML:
self.assertEqual(
str(k.to_string())[:43],
'<kml xmlns="http://www.opengis.net/kml/2.2"/>' [:43])
else:
if hasattr(etree, 'register_namespace'):
self.assertEqual(str(k.to_string())[:51], '<kml:kml xmlns:kml="http://www.opengis.net/kml/2.2" />'[:51])
else:
self.assertEqual(str(k.to_string())[:51], '<ns0:kml xmlns:ns0="http://www.opengis.net/kml/2.2" />'[:51])
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_folder(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML()
f = kml.Folder(ns, 'id', 'name', 'description')
nf = kml.Folder(ns, 'nested-id', 'nested-name', 'nested-description')
f.append(nf)
k.append(f)
f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
k.append(f2)
self.assertEqual(len(list(k.features())), 2)
self.assertEqual(len(list(list(k.features())[0].features())), 1)
k2 = kml.KML()
s = k.to_string()
k2.from_string(s)
self.assertEqual(s, k2.to_string())
def test_placemark(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Point(0.0, 0.0, 0.0)
p2 = kml.Placemark(ns, 'id2', 'name2', 'description2')
p2.geometry = LineString([(0, 0, 0), (1, 1, 1)])
k.append(p)
k.append(p2)
self.assertEqual(len(list(k.features())), 2)
k2 = kml.KML()
k2.from_string(k.to_string(prettyprint=True))
self.assertEqual(k.to_string(), k2.to_string())
def test_schema(self):
ns = '{http://www.opengis.net/kml/2.2}'
self.assertRaises(ValueError, kml.Schema, ns)
s = kml.Schema(ns, 'some_id')
self.assertEqual(len(list(s.simple_fields)), 0)
s.append('int', 'Integer', 'An Integer')
self.assertEqual(list(s.simple_fields)[0]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[0]['displayName'], 'An Integer')
s.simple_fields = None
self.assertEqual(len(list(s.simple_fields)), 0)
self.assertRaises(
TypeError, s.append, ('none', 'Integer', 'An Integer'))
self.assertRaises(
TypeError, s.simple_fields, [('none', 'Integer', 'An Integer')])
self.assertRaises(
TypeError, s.simple_fields, ('int', 'Integer', 'An Integer'))
fields = {
'type': 'int',
'name': 'Integer',
'displayName': 'An Integer'
}
s.simple_fields = fields
self.assertEqual(list(s.simple_fields)[0]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[0]['displayName'], 'An Integer')
s.simple_fields = [['float', 'Float'], fields]
self.assertEqual(list(s.simple_fields)[0]['type'], 'float')
self.assertEqual(list(s.simple_fields)[0]['name'], 'Float')
self.assertEqual(list(s.simple_fields)[0]['displayName'], None)
self.assertEqual(list(s.simple_fields)[1]['type'], 'int')
self.assertEqual(list(s.simple_fields)[1]['name'], 'Integer')
self.assertEqual(list(s.simple_fields)[1]['displayName'], 'An Integer')
def test_schema_data(self):
ns = '{http://www.opengis.net/kml/2.2}'
self.assertRaises(ValueError, kml.SchemaData, ns)
self.assertRaises(ValueError, kml.SchemaData, ns, '')
sd = kml.SchemaData(ns, '#default')
sd.append_data('text', 'Some Text')
self.assertEqual(len(sd.data), 1)
sd.append_data(value=1, name='Integer')
self.assertEqual(len(sd.data), 2)
self.assertEqual(sd.data[0], {'value': 'Some Text', 'name': 'text'})
self.assertEqual(sd.data[1], {'value': 1, 'name': 'Integer'})
data = (('text', 'Some new Text'), {'value': 2, 'name': 'Integer'})
sd.data = data
self.assertEqual(len(sd.data), 2)
self.assertEqual(
sd.data[0], {'value': 'Some new Text',
'name': 'text'})
self.assertEqual(sd.data[1], {'value': 2, 'name': 'Integer'})
def test_untyped_extended_data(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Point(0.0, 0.0, 0.0)
p.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(
name='info',
value='so much to see'), kml.UntypedExtendedDataElement(
name='weather',
display_name='Weather',
value='blue skies')
])
self.assertEqual(len(p.extended_data.elements), 2)
k.append(p)
k2 = kml.KML()
k2.from_string(k.to_string(prettyprint=True))
k.to_string()
extended_data = list(k2.features())[0].extended_data
self.assertTrue(extended_data is not None)
self.assertTrue(len(extended_data.elements), 2)
self.assertEqual(extended_data.elements[0].name, 'info')
self.assertEqual(extended_data.elements[0].value, 'so much to see')
self.assertEqual(extended_data.elements[0].display_name, None)
self.assertEqual(extended_data.elements[1].name, 'weather')
self.assertEqual(extended_data.elements[1].value, 'blue skies')
self.assertEqual(extended_data.elements[1].display_name, 'Weather')
def test_untyped_extended_data_nested(self):
ns = '{http://www.opengis.net/kml/2.2}'
k = kml.KML(ns=ns)
d = kml.Document(ns, 'docid', 'doc name', 'doc description')
d.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(name='type',
value='Document')
])
f = kml.Folder(ns, 'fid', 'f name', 'f description')
f.extended_data = kml.UntypedExtendedData(elements=[
kml.UntypedExtendedDataElement(name='type',
value='Folder')
])
k.append(d)
d.append(f)
k2 = kml.KML()
k2.from_string(k.to_string())
document_data = list(k2.features())[0].extended_data
folder_data = list(list(k2.features())[0].features())[0].extended_data
self.assertEqual(document_data.elements[0].name, 'type')
self.assertEqual(document_data.elements[0].value, 'Document')
self.assertEqual(folder_data.elements[0].name, 'type')
self.assertEqual(folder_data.elements[0].value, 'Folder')
def test_document(self):
k = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'
d = kml.Document(ns, 'docid', 'doc name', 'doc description')
f = kml.Folder(ns, 'fid', 'f name', 'f description')
k.append(d)
d.append(f)
nf = kml.Folder(
ns, 'nested-fid', 'nested f name', 'nested f description')
f.append(nf)
f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
d.append(f2)
p = kml.Placemark(ns, 'id', 'name', 'description')
p.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 1)])
p2 = kml.Placemark(ns, 'id2', 'name2', 'description2')
f2.append(p)
nf.append(p2)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list((list(k.features())[0].features()))), 2)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_author(self):
d = kml.Document()
d.author = 'Christian Ledermann'
self.assertTrue('Christian Ledermann' in str(d.to_string()))
a = atom.Author(
name='Nobody',
uri='http://localhost',
email='cl@donotreply.com')
d.author = a
self.assertEqual(d.author, 'Nobody')
self.assertFalse('Christian Ledermann' in str(d.to_string()))
self.assertTrue('Nobody' in str(d.to_string()))
self.assertTrue('http://localhost' in str(d.to_string()))
self.assertTrue('cl@donotreply.com' in str(d.to_string()))
d2 = kml.Document()
d2.from_string(d.to_string())
self.assertEqual(d.to_string(), d2.to_string())
d.author = None
def test_link(self):
d = kml.Document()
d.link = 'http://localhost'
self.assertTrue('http://localhost' in str(d.to_string()))
l = atom.Link(href='#here')
d.link = l
self.assertTrue('#here' in str(d.to_string()))
self.assertRaises(TypeError, d.link, object)
d2 = kml.Document()
d2.from_string(d.to_string())
self.assertEqual(d.to_string(), d2.to_string())
d.link = None
def test_address(self):
address = '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
d = kml.Document()
d.address = address
self.assertTrue(address in str(d.to_string()))
self.assertTrue('address>' in str(d.to_string()))
def test_phone_number(self):
phone = '+1 234 567 8901'
d = kml.Document()
d.phoneNumber = phone
self.assertTrue(phone in str(d.to_string()))
self.assertTrue('phoneNumber>' in str(d.to_string()))
class KmlFromStringTestCase(unittest.TestCase):
def test_document(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
<Placemark>
<name>Document Feature 1</name>
<styleUrl>#exampleStyleDocument</styleUrl>
<Point>
<coordinates>-122.371,37.816,0</coordinates>
</Point>
</Placemark>
<Placemark targetId="someTargetId">
<name>Document Feature 2</name>
<styleUrl>#exampleStyleDocument</styleUrl>
<Point>
<coordinates>-122.370,37.817,0</coordinates>
</Point>
</Placemark>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list(list(k.features())[0].features())), 2)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_document_booleans(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<visibility>true</visibility>
<open>1</open>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].visibility, 1)
self.assertEqual(list(k.features())[0].isopen, 1)
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document targetId="someTargetId">
<name>Document.kml</name>
<visibility>0</visibility>
<open>false</open>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].visibility, 0)
self.assertEqual(list(k.features())[0].isopen, 0)
def test_folders(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
<name>Folder.kml</name>
<open>1</open>
<description>
A folder is a container that can hold multiple other objects
</description>
<Placemark>
<name>Folder object 1 (Placemark)</name>
<Point>
<coordinates>-122.377588,37.830266,0</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Folder object 2 (Polygon)</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-122.377830,37.830445,0
-122.377576,37.830631,0
-122.377840,37.830642,0
-122.377830,37.830445,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Folder object 3 (Path)</name>
<LineString>
<tessellate>1</tessellate>
<coordinates>
-122.378009,37.830128,0 -122.377885,37.830379,0
</coordinates>
</LineString>
</Placemark>
</Folder>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(len(list(list(k.features())[0].features())), 3)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_placemark(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself
at the height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(list(k.features())[0].name, "Simple placemark")
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_extended_data(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description></description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
<ExtendedData>
<Data name="holeNumber">
<displayName><![CDATA[
<b>This is hole </b>
]]></displayName>
<value>1</value>
</Data>
<Data name="holePar">
<displayName><![CDATA[
<i>The par for this hole is </i>
]]></displayName>
<value>4</value>
</Data>
<SchemaData schemaUrl="#TrailHeadTypeId">
<SimpleData name="TrailHeadName">Mount Everest</SimpleData>
<SimpleData name="TrailLength">347.45</SimpleData>
<SimpleData name="ElevationGain">10000</SimpleData>
</SchemaData>
</ExtendedData>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
extended_data = list(k.features())[0].extended_data
self.assertEqual(extended_data.elements[0].name, 'holeNumber')
self.assertEqual(extended_data.elements[0].value, '1')
self.assertTrue(
'<b>This is hole </b>' in extended_data.elements[0].display_name)
self.assertEqual(extended_data.elements[1].name, 'holePar')
self.assertEqual(extended_data.elements[1].value, '4')
self.assertTrue(
'<i>The par for this hole is </i>' in
extended_data.elements[1].display_name)
sd = extended_data.elements[2]
self.assertEqual(sd.data[0]['name'], 'TrailHeadName')
self.assertEqual(sd.data[1]['value'], '347.45')
def test_polygon(self):
doc = """
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>South Africa</name>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
31.521,-29.257,0
31.326,-29.402,0
30.902,-29.91,0
30.623,-30.424,0
30.056,-31.14,0
28.926,-32.172,0
28.22,-32.772,0
27.465,-33.227,0
26.419,-33.615,0
25.91,-33.667,0
25.781,-33.945,0
25.173,-33.797,0
24.678,-33.987,0
23.594,-33.794,0
22.988,-33.916,0
22.574,-33.864,0
21.543,-34.259,0
20.689,-34.417,0
20.071,-34.795,0
19.616,-34.819,0
19.193,-34.463,0
18.855,-34.444,0
18.425,-33.998,0
18.377,-34.137,0
18.244,-33.868,0
18.25,-33.281,0
17.925,-32.611,0
18.248,-32.429,0
18.222,-31.662,0
17.567,-30.726,0
17.064,-29.879,0
17.063,-29.876,0
16.345,-28.577,0
16.824,-28.082,0
17.219,-28.356,0
17.387,-28.784,0
17.836,-28.856,0
18.465,-29.045,0
19.002,-28.972,0
19.895,-28.461,0
19.896,-24.768,0
20.166,-24.918,0
20.759,-25.868,0
20.666,-26.477,0
20.89,-26.829,0
21.606,-26.727,0
22.106,-26.28,0
22.58,-25.979,0
22.824,-25.5,0
23.312,-25.269,0
23.734,-25.39,0
24.211,-25.67,0
25.025,-25.72,0
25.665,-25.487,0
25.766,-25.175,0
25.942,-24.696,0
26.486,-24.616,0
26.786,-24.241,0
27.119,-23.574,0
28.017,-22.828,0
29.432,-22.091,0
29.839,-22.102,0
30.323,-22.272,0
30.66,-22.152,0
31.191,-22.252,0
31.67,-23.659,0
31.931,-24.369,0
31.752,-25.484,0
31.838,-25.843,0
31.333,-25.66,0
31.044,-25.731,0
30.95,-26.023,0
30.677,-26.398,0
30.686,-26.744,0
31.283,-27.286,0
31.868,-27.178,0
32.072,-26.734,0
32.83,-26.742,0
32.58,-27.47,0
32.462,-28.301,0
32.203,-28.752,0
31.521,-29.257,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
<innerBoundaryIs>
<LinearRing>
<coordinates>
28.978,-28.956,0
28.542,-28.648,0
28.074,-28.851,0
27.533,-29.243,0
26.999,-29.876,0
27.749,-30.645,0
28.107,-30.546,0
28.291,-30.226,0
28.848,-30.07,0
29.018,-29.744,0
29.325,-29.257,0
28.978,-28.956,0
</coordinates>
</LinearRing>
</innerBoundaryIs>
</Polygon>
</Placemark>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(isinstance(list(k.features())[0].geometry, Polygon))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multipoints(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark id="feat_2">
<name>MultiPoint</name>
<styleUrl>#stylesel_9</styleUrl>
<MultiGeometry id="geom_0">
<Point id="geom_5">
<coordinates>16,-35,0.0</coordinates>
</Point>
<Point id="geom_6">
<coordinates>16,-33,0.0</coordinates>
</Point>
<Point id="geom_7">
<coordinates>16,-31,0.0</coordinates>
</Point>
<Point id="geom_8">
<coordinates>16,-29,0.0</coordinates>
</Point>
<Point id="geom_9">
<coordinates>16,-27,0.0</coordinates>
</Point>
<Point id="geom_10">
<coordinates>16,-25,0.0</coordinates>
</Point>
<Point id="geom_11">
<coordinates>16,-23,0.0</coordinates>
</Point>
<Point id="geom_12">
<coordinates>16,-21,0.0</coordinates>
</Point>
<Point id="geom_15">
<coordinates>18,-35,0.0</coordinates>
</Point>
<Point id="geom_16">
<coordinates>18,-33,0.0</coordinates>
</Point>
<Point id="geom_17">
<coordinates>18,-31,0.0</coordinates>
</Point>
<Point id="geom_18">
<coordinates>18,-29,0.0</coordinates>
</Point>
</MultiGeometry>
</Placemark></kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(isinstance(list(k.features())[0].geometry, MultiPoint))
self.assertEqual(len(list(k.features())[0].geometry.geoms), 12)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multilinestrings(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Dnipro (Dnieper)</name>
<MultiGeometry>
<LineString><coordinates>33.54,46.831,0 33.606,46.869,0 33.662,46.957,0 33.739,47.05,0 33.859,47.149,0 33.976,47.307,0 33.998,47.411,0 34.155,47.49,0 34.448,47.542,0 34.712,47.553,0 34.946,47.521,0 35.088,47.528,0 35.138,47.573,0 35.149,47.657,0 35.106,47.842,0 </coordinates></LineString>
<LineString><coordinates>33.194,49.094,0 32.884,49.225,0 32.603,49.302,0 31.886,49.555,0 </coordinates></LineString>
<LineString><coordinates>31.44,50,0 31.48,49.933,0 31.486,49.871,0 31.467,49.754,0 </coordinates></LineString>
<LineString><coordinates>30.508,51.217,0 30.478,50.904,0 30.479,50.749,0 30.515,50.597,0 </coordinates></LineString>
</MultiGeometry>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(k.features())[0].geometry, MultiLineString))
self.assertEqual(len(list(k.features())[0].geometry.geoms), 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_multipolygon(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Italy</name>
<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>12.621,35.492,0 12.611,35.489,0 12.603,35.491,0 12.598,35.494,0 12.594,35.494,0 12.556,35.508,0 12.536,35.513,0 12.526,35.517,0 12.534,35.522,0 12.556,35.521,0 12.567,35.519,0 12.613,35.515,0 12.621,35.513,0 12.624,35.512,0 12.622,35.51,0 12.621,35.508,0 12.624,35.502,0 12.621,35.492,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.873,35.852,0 12.857,35.852,0 12.851,35.856,0 12.846,35.863,0 12.847,35.868,0 12.854,35.871,0 12.86,35.872,0 12.867,35.872,0 12.874,35.866,0 12.877,35.856,0 12.873,35.852,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>11.981,36.827,0 11.988,36.824,0 11.994,36.825,0 12,36.836,0 12.038,36.806,0 12.052,36.79,0 12.054,36.767,0 12.031,36.741,0 11.997,36.745,0 11.962,36.765,0 11.938,36.789,0 11.934,36.795,0 11.926,36.812,0 11.923,36.828,0 11.935,36.836,0 11.939,36.837,0 11.947,36.841,0 11.952,36.843,0 11.958,36.84,0 11.968,36.831,0 11.972,36.829,0 11.981,36.827,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.322,37.94,0 12.337,37.933,0 12.355,37.927,0 12.369,37.925,0 12.358,37.914,0 12.343,37.913,0 12.327,37.918,0 12.315,37.925,0 12.3,37.919,0 12.288,37.921,0 12.279,37.929,0 12.274,37.939,0 12.288,37.938,0 12.298,37.941,0 12.306,37.945,0 12.315,37.946,0 12.322,37.94,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.078,37.96,0 12.079,37.95,0 12.065,37.951,0 12.048,37.961,0 12.037,37.974,0 12.03,37.984,0 12.036,37.991,0 12.054,37.992,0 12.065,37.986,0 12.072,37.968,0 12.078,37.96,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>15.643,38.262,0 15.635,38.261,0 15.625,38.261,0 15.584,38.24,0 15.57,38.227,0 15.564,38.214,0 15.56,38.2,0 15.576,38.2,0 15.527,38.137,0 15.501,38.085,0 15.393,37.976,0 15.303,37.864,0 15.284,37.833,0 15.267,37.812,0 15.242,37.795,0 15.214,37.761,0 15.207,37.747,0 15.209,37.737,0 15.219,37.718,0 15.221,37.706,0 15.217,37.696,0 15.203,37.685,0 15.2,37.675,0 15.197,37.655,0 15.185,37.626,0 15.179,37.604,0 15.164,37.567,0 15.117,37.522,0 15.097,37.494,0 15.092,37.477,0 15.09,37.459,0 15.093,37.36,0 15.097,37.343,0 15.104,37.33,0 15.111,37.322,0 15.181,37.291,0 15.218,37.285,0 15.237,37.275,0 15.253,37.257,0 15.262,37.234,0 15.245,37.246,0 15.236,37.242,0 15.229,37.23,0 15.221,37.22,0 15.222,37.237,0 15.216,37.244,0 15.206,37.244,0 15.193,37.24,0 15.2,37.227,0 15.184,37.207,0 15.195,37.176,0 15.217,37.155,0 15.234,37.165,0 15.248,37.158,0 15.248,37.152,0 15.23,37.149,0 15.232,37.135,0 15.247,37.118,0 15.265,37.11,0 15.289,37.108,0 15.304,37.101,0 15.309,37.086,0 15.303,37.062,0 15.289,37.069,0 15.283,37.061,0 15.284,37.048,0 15.292,37.042,0 15.313,37.044,0 15.322,37.04,0 15.33,37.027,0 15.333,37.011,0 15.325,37.008,0 15.315,37.012,0 15.309,37.018,0 15.304,37.016,0 15.269,37,0 15.275,36.993,0 15.267,36.989,0 15.264,36.987,0 15.269,36.98,0 15.269,36.973,0 15.245,36.972,0 15.227,36.965,0 15.212,36.956,0 15.197,36.952,0 15.175,36.944,0 15.159,36.924,0 15.108,36.82,0 15.107,36.808,0 15.095,36.799,0 15.099,36.779,0 15.118,36.747,0 15.135,36.687,0 15.135,36.675,0 15.115,36.66,0 15.094,36.655,0 15.074,36.659,0 15.056,36.671,0 15.041,36.687,0 15.034,36.694,0 15.021,36.699,0 15.008,36.703,0 14.998,36.702,0 14.994,36.696,0 14.983,36.689,0 14.958,36.698,0 14.919,36.72,0 14.883,36.73,0 14.847,36.726,0 14.781,36.699,0 14.777,36.707,0 14.774,36.71,0 14.761,36.706,0 14.745,36.719,0 14.685,36.726,0 14.672,36.744,0 14.659,36.754,0 14.601,36.772,0 14.583,36.781,0 14.566,36.778,0 14.488,36.793,0 14.476,36.805,0 14.395,36.945,0 14.37,36.973,0 14.279,37.044,0 14.209,37.081,0 14.127,37.112,0 14.089,37.117,0 13.977,37.11,0 13.968,37.108,0 13.949,37.099,0 13.939,37.096,0 13.895,37.101,0 13.833,37.139,0 13.795,37.152,0 13.752,37.159,0 13.716,37.171,0 13.684,37.189,0 13.599,37.256,0 13.57,37.273,0 13.535,37.282,0 13.489,37.288,0 13.453,37.299,0 13.422,37.314,0 13.373,37.346,0 13.33,37.366,0 13.312,37.381,0 13.303,37.386,0 13.29,37.389,0 13.279,37.393,0 13.254,37.432,0 13.248,37.436,0 13.226,37.446,0 13.215,37.458,0 13.207,37.464,0 13.195,37.466,0 13.19,37.469,0 13.18,37.484,0 13.175,37.487,0 13.052,37.5,0 13.037,37.495,0 13.027,37.493,0 13.017,37.497,0 13.011,37.507,0 13.005,37.527,0 13.001,37.535,0 12.975,37.557,0 12.943,37.568,0 12.863,37.576,0 12.781,37.574,0 12.698,37.563,0 12.66,37.565,0 12.637,37.582,0 12.595,37.638,0 12.578,37.652,0 12.564,37.658,0 12.524,37.658,0 12.507,37.665,0 12.49,37.682,0 12.475,37.703,0 12.466,37.72,0 12.461,37.734,0 12.46,37.748,0 12.457,37.76,0 12.449,37.771,0 12.437,37.783,0 12.428,37.797,0 12.428,37.809,0 12.445,37.816,0 12.447,37.812,0 12.461,37.819,0 12.466,37.823,0 12.464,37.825,0 12.471,37.853,0 12.473,37.854,0 12.478,37.872,0 12.479,37.881,0 12.477,37.886,0 12.468,37.897,0 12.466,37.906,0 12.465,37.913,0 12.465,37.914,0 12.468,37.916,0 12.491,37.954,0 12.497,37.98,0 12.503,37.997,0 12.505,38.011,0 12.493,38.021,0 12.524,38.031,0 12.55,38.055,0 12.577,38.072,0 12.609,38.062,0 12.639,38.079,0 12.652,38.091,0 12.657,38.107,0 12.663,38.116,0 12.677,38.116,0 12.692,38.112,0 12.705,38.111,0 12.726,38.126,0 12.725,38.15,0 12.72,38.175,0 12.732,38.193,0 12.738,38.181,0 12.75,38.182,0 12.761,38.181,0 12.767,38.162,0 12.791,38.117,0 12.819,38.078,0 12.829,38.07,0 12.858,38.058,0 12.869,38.051,0 12.87,38.042,0 12.902,38.028,0 12.945,38.033,0 13.028,38.062,0 13.062,38.083,0 13.07,38.091,0 13.072,38.095,0 13.07,38.101,0 13.069,38.114,0 13.067,38.123,0 13.057,38.133,0 13.055,38.142,0 13.09,38.166,0 13.084,38.174,0 13.09,38.183,0 13.102,38.19,0 13.113,38.193,0 13.123,38.191,0 13.158,38.179,0 13.18,38.176,0 13.208,38.176,0 13.231,38.184,0 13.239,38.207,0 13.255,38.202,0 13.267,38.205,0 13.278,38.21,0 13.297,38.214,0 13.311,38.219,0 13.319,38.22,0 13.324,38.218,0 13.326,38.211,0 13.327,38.205,0 13.329,38.2,0 13.367,38.179,0 13.372,38.173,0 13.374,38.14,0 13.377,38.131,0 13.392,38.103,0 13.514,38.11,0 13.542,38.094,0 13.54,38.077,0 13.542,38.067,0 13.548,38.056,0 13.558,38.049,0 13.588,38.039,0 13.623,38.015,0 13.652,38.001,0 13.698,37.993,0 13.712,37.988,0 13.708,37.985,0 13.708,37.984,0 13.706,37.98,0 13.727,37.981,0 13.791,37.973,0 13.813,37.978,0 13.858,37.996,0 13.899,38.004,0 13.913,38.012,0 13.925,38.022,0 13.939,38.029,0 14.008,38.038,0 14.021,38.049,0 14.063,38.03,0 14.084,38.024,0 14.107,38.021,0 14.122,38.022,0 14.152,38.029,0 14.274,38.015,0 14.332,38.018,0 14.385,38.029,0 14.433,38.049,0 14.465,38.037,0 14.512,38.044,0 14.635,38.081,0 14.668,38.099,0 14.696,38.121,0 14.734,38.157,0 14.745,38.161,0 14.778,38.159,0 14.799,38.16,0 14.875,38.175,0 14.889,38.182,0 14.898,38.186,0 14.908,38.187,0 14.936,38.186,0 14.945,38.182,0 14.963,38.163,0 14.97,38.159,0 14.982,38.158,0 15.008,38.152,0 15.04,38.153,0 15.049,38.152,0 15.054,38.148,0 15.064,38.135,0 15.069,38.131,0 15.088,38.128,0 15.106,38.133,0 15.123,38.141,0 15.178,38.156,0 15.204,38.183,0 15.241,38.241,0 15.238,38.249,0 15.237,38.251,0 15.237,38.253,0 15.241,38.261,0 15.238,38.265,0 15.244,38.265,0 15.247,38.254,0 15.241,38.23,0 15.246,38.217,0 15.258,38.21,0 15.275,38.207,0 15.292,38.207,0 15.322,38.211,0 15.4,38.232,0 15.423,38.244,0 15.434,38.253,0 15.473,38.268,0 15.513,38.297,0 15.529,38.302,0 15.56,38.3,0 15.616,38.28,0 15.652,38.275,0 15.649,38.266,0 15.643,38.262,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.999,38.371,0 14.987,38.364,0 14.964,38.381,0 14.949,38.396,0 14.946,38.412,0 14.96,38.433,0 14.967,38.433,0 14.967,38.418,0 14.983,38.412,0 14.994,38.403,0 15.002,38.391,0 15.008,38.378,0 14.999,38.371,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.967,38.453,0 14.949,38.451,0 14.935,38.458,0 14.922,38.469,0 14.908,38.474,0 14.9,38.481,0 14.901,38.498,0 14.91,38.515,0 14.925,38.522,0 14.958,38.522,0 14.967,38.516,0 14.96,38.502,0 14.966,38.497,0 14.975,38.49,0 14.98,38.487,0 14.98,38.481,0 14.953,38.481,0 14.958,38.469,0 14.962,38.465,0 14.967,38.461,0 14.967,38.453,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.361,38.539,0 14.346,38.535,0 14.343,38.547,0 14.357,38.551,0 14.361,38.539,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.864,38.549,0 14.862,38.539,0 14.824,38.552,0 14.794,38.571,0 14.815,38.584,0 14.852,38.585,0 14.867,38.581,0 14.877,38.569,0 14.873,38.565,0 14.869,38.56,0 14.864,38.549,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>14.585,38.557,0 14.574,38.557,0 14.552,38.562,0 14.544,38.575,0 14.543,38.587,0 14.546,38.588,0 14.564,38.585,0 14.576,38.577,0 14.58,38.566,0 14.585,38.561,0 14.585,38.557,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.177,38.693,0 13.165,38.691,0 13.153,38.695,0 13.153,38.702,0 13.158,38.71,0 13.169,38.717,0 13.186,38.718,0 13.196,38.711,0 13.197,38.708,0 13.177,38.693,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>15.225,38.777,0 15.217,38.773,0 15.206,38.775,0 15.187,38.789,0 15.187,38.793,0 15.194,38.798,0 15.204,38.802,0 15.209,38.806,0 15.212,38.81,0 15.219,38.812,0 15.228,38.81,0 15.235,38.808,0 15.239,38.804,0 15.237,38.796,0 15.232,38.789,0 15.23,38.783,0 15.225,38.777,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.361,39.118,0 8.386,39.105,0 8.418,39.106,0 8.445,39.102,0 8.457,39.073,0 8.459,39.068,0 8.464,39.065,0 8.47,39.065,0 8.477,39.07,0 8.478,39.07,0 8.48,39.072,0 8.484,39.07,0 8.465,39.056,0 8.46,39.05,0 8.464,39.042,0 8.455,39.028,0 8.447,38.994,0 8.438,38.967,0 8.433,38.963,0 8.422,38.96,0 8.41,38.962,0 8.407,38.967,0 8.406,38.974,0 8.402,38.981,0 8.365,39.029,0 8.35,39.062,0 8.354,39.083,0 8.354,39.091,0 8.347,39.091,0 8.347,39.097,0 8.361,39.118,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.306,39.104,0 8.291,39.099,0 8.27,39.1,0 8.255,39.107,0 8.258,39.118,0 8.258,39.124,0 8.233,39.144,0 8.225,39.157,0 8.231,39.173,0 8.246,39.181,0 8.291,39.188,0 8.306,39.193,0 8.307,39.161,0 8.313,39.12,0 8.306,39.104,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.959,40.712,0 13.945,40.701,0 13.935,40.705,0 13.92,40.704,0 13.904,40.7,0 13.891,40.694,0 13.882,40.699,0 13.86,40.707,0 13.85,40.715,0 13.857,40.735,0 13.862,40.744,0 13.871,40.749,0 13.868,40.752,0 13.863,40.762,0 13.884,40.762,0 13.947,40.745,0 13.966,40.735,0 13.963,40.729,0 13.963,40.723,0 13.966,40.715,0 13.959,40.712,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>13.427,40.791,0 13.415,40.786,0 13.419,40.796,0 13.424,40.8,0 13.432,40.801,0 13.427,40.791,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>8.333,41.105,0 8.343,41.098,0 8.345,41.086,0 8.342,41.074,0 8.333,41.064,0 8.275,41.057,0 8.252,41.043,0 8.252,41.016,0 8.247,40.993,0 8.21,40.996,0 8.218,41.005,0 8.222,41.014,0 8.224,41.024,0 8.224,41.033,0 8.229,41.042,0 8.242,41.052,0 8.261,41.064,0 8.276,41.07,0 8.278,41.081,0 8.276,41.095,0 8.278,41.105,0 8.285,41.107,0 8.303,41.105,0 8.306,41.109,0 8.309,41.114,0 8.314,41.118,0 8.327,41.126,0 8.326,41.118,0 8.328,41.112,0 8.333,41.105,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.471,41.19,0 9.474,41.184,0 9.475,41.179,0 9.47,41.172,0 9.464,41.173,0 9.456,41.181,0 9.449,41.186,0 9.442,41.183,0 9.437,41.186,0 9.448,41.205,0 9.443,41.211,0 9.446,41.22,0 9.454,41.234,0 9.46,41.242,0 9.468,41.241,0 9.475,41.236,0 9.478,41.228,0 9.48,41.224,0 9.479,41.217,0 9.471,41.19,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.239,41.249,0 9.247,41.248,0 9.258,41.249,0 9.269,41.236,0 9.268,41.202,0 9.279,41.195,0 9.275,41.199,0 9.274,41.205,0 9.275,41.212,0 9.279,41.221,0 9.286,41.221,0 9.29,41.209,0 9.289,41.205,0 9.286,41.201,0 9.286,41.195,0 9.3,41.196,0 9.306,41.198,0 9.313,41.201,0 9.317,41.196,0 9.334,41.187,0 9.336,41.211,0 9.353,41.207,0 9.389,41.181,0 9.389,41.187,0 9.397,41.184,0 9.405,41.181,0 9.413,41.181,0 9.423,41.181,0 9.423,41.174,0 9.417,41.171,0 9.415,41.168,0 9.413,41.164,0 9.409,41.16,0 9.421,41.156,0 9.427,41.149,0 9.433,41.14,0 9.443,41.133,0 9.438,41.125,0 9.437,41.115,0 9.443,41.092,0 9.455,41.112,0 9.461,41.12,0 9.471,41.126,0 9.467,41.13,0 9.466,41.134,0 9.463,41.137,0 9.457,41.14,0 9.47,41.146,0 9.482,41.145,0 9.495,41.142,0 9.509,41.14,0 9.514,41.143,0 9.519,41.148,0 9.524,41.15,0 9.533,41.14,0 9.525,41.133,0 9.535,41.128,0 9.541,41.123,0 9.547,41.121,0 9.553,41.126,0 9.56,41.126,0 9.562,41.122,0 9.562,41.121,0 9.564,41.121,0 9.567,41.119,0 9.566,41.107,0 9.563,41.097,0 9.557,41.088,0 9.546,41.077,0 9.544,41.082,0 9.541,41.087,0 9.54,41.092,0 9.522,41.031,0 9.512,41.016,0 9.533,41.016,0 9.525,41.03,0 9.544,41.037,0 9.555,41.034,0 9.558,41.025,0 9.553,41.009,0 9.558,41.009,0 9.559,41.011,0 9.559,41.013,0 9.56,41.016,0 9.566,41.011,0 9.569,41.009,0 9.574,41.009,0 9.589,41.02,0 9.616,41.019,0 9.645,41.011,0 9.663,41.002,0 9.652,40.991,0 9.637,40.992,0 9.62,40.999,0 9.605,41.002,0 9.588,40.996,0 9.583,40.98,0 9.579,40.962,0 9.567,40.948,0 9.572,40.935,0 9.558,40.931,0 9.512,40.934,0 9.512,40.929,0 9.513,40.928,0 9.505,40.927,0 9.512,40.915,0 9.521,40.915,0 9.53,40.919,0 9.54,40.92,0 9.55,40.917,0 9.568,40.908,0 9.574,40.906,0 9.593,40.91,0 9.608,40.918,0 9.623,40.924,0 9.643,40.92,0 9.638,40.911,0 9.632,40.905,0 9.624,40.9,0 9.615,40.899,0 9.615,40.893,0 9.651,40.879,0 9.656,40.876,0 9.658,40.864,0 9.664,40.858,0 9.672,40.859,0 9.684,40.865,0 9.69,40.856,0 9.7,40.85,0 9.712,40.847,0 9.725,40.845,0 9.691,40.836,0 9.682,40.829,0 9.69,40.817,0 9.69,40.811,0 9.675,40.814,0 9.662,40.809,0 9.658,40.8,0 9.669,40.79,0 9.67,40.801,0 9.676,40.788,0 9.705,40.759,0 9.711,40.745,0 9.715,40.727,0 9.745,40.68,0 9.749,40.667,0 9.754,40.605,0 9.757,40.595,0 9.762,40.587,0 9.769,40.584,0 9.782,40.582,0 9.786,40.576,0 9.787,40.567,0 9.793,40.557,0 9.821,40.536,0 9.827,40.529,0 9.827,40.519,0 9.816,40.502,0 9.813,40.492,0 9.809,40.471,0 9.801,40.455,0 9.779,40.427,0 9.762,40.39,0 9.75,40.377,0 9.728,40.372,0 9.713,40.366,0 9.701,40.353,0 9.684,40.324,0 9.671,40.312,0 9.646,40.296,0 9.635,40.282,0 9.627,40.263,0 9.625,40.248,0 9.629,40.205,0 9.632,40.196,0 9.655,40.144,0 9.666,40.131,0 9.68,40.126,0 9.688,40.12,0 9.711,40.096,0 9.733,40.084,0 9.731,40.068,0 9.694,39.993,0 9.688,39.961,0 9.697,39.934,0 9.703,39.937,0 9.71,39.94,0 9.716,39.94,0 9.718,39.934,0 9.715,39.924,0 9.709,39.922,0 9.702,39.922,0 9.697,39.919,0 9.69,39.906,0 9.685,39.894,0 9.684,39.882,0 9.69,39.871,0 9.684,39.871,0 9.684,39.865,0 9.688,39.863,0 9.693,39.86,0 9.697,39.858,0 9.697,39.852,0 9.685,39.84,0 9.676,39.819,0 9.671,39.793,0 9.669,39.769,0 9.67,39.756,0 9.676,39.732,0 9.677,39.718,0 9.675,39.708,0 9.665,39.691,0 9.663,39.677,0 9.661,39.67,0 9.656,39.663,0 9.652,39.652,0 9.65,39.639,0 9.656,39.594,0 9.654,39.567,0 9.629,39.502,0 9.645,39.484,0 9.64,39.452,0 9.615,39.399,0 9.603,39.355,0 9.601,39.341,0 9.604,39.326,0 9.612,39.316,0 9.635,39.303,0 9.635,39.297,0 9.608,39.289,0 9.582,39.266,0 9.568,39.238,0 9.574,39.214,0 9.566,39.205,0 9.569,39.199,0 9.577,39.194,0 9.581,39.187,0 9.578,39.179,0 9.569,39.159,0 9.567,39.149,0 9.558,39.139,0 9.54,39.134,0 9.523,39.125,0 9.519,39.104,0 9.511,39.108,0 9.508,39.111,0 9.508,39.116,0 9.512,39.124,0 9.497,39.133,0 9.481,39.135,0 9.466,39.132,0 9.451,39.124,0 9.443,39.124,0 9.439,39.133,0 9.429,39.138,0 9.409,39.146,0 9.384,39.169,0 9.378,39.173,0 9.368,39.177,0 9.346,39.196,0 9.337,39.201,0 9.327,39.203,0 9.313,39.208,0 9.3,39.214,0 9.293,39.221,0 9.286,39.214,0 9.272,39.22,0 9.253,39.225,0 9.217,39.228,0 9.198,39.221,0 9.182,39.207,0 9.17,39.193,0 9.167,39.187,0 9.137,39.194,0 9.114,39.211,0 9.073,39.248,0 9.064,39.243,0 9.056,39.247,0 9.048,39.256,0 9.039,39.262,0 9.025,39.265,0 9.015,39.264,0 9.013,39.26,0 9.026,39.256,0 9.026,39.248,0 9.022,39.24,0 9.027,39.236,0 9.036,39.232,0 9.038,39.227,0 9.039,39.228,0 9.051,39.225,0 9.075,39.23,0 9.08,39.224,0 9.08,39.216,0 9.08,39.212,0 9.039,39.179,0 9.027,39.165,0 9.019,39.146,0 9.017,39.124,0 9.019,39.104,0 9.025,39.086,0 9.033,39.07,0 9.038,39.063,0 9.044,39.058,0 9.046,39.051,0 9.03,39.03,0 9.019,38.995,0 9.026,38.995,0 9.016,38.989,0 9.013,38.99,0 9.005,38.995,0 8.997,38.983,0 8.895,38.902,0 8.889,38.9,0 8.878,38.899,0 8.873,38.896,0 8.862,38.882,0 8.854,38.878,0 8.842,38.88,0 8.828,38.889,0 8.806,38.906,0 8.806,38.885,0 8.791,38.904,0 8.767,38.92,0 8.74,38.93,0 8.717,38.932,0 8.695,38.925,0 8.669,38.91,0 8.652,38.891,0 8.656,38.871,0 8.641,38.864,0 8.635,38.871,0 8.643,38.89,0 8.634,38.895,0 8.616,38.896,0 8.6,38.899,0 8.6,38.906,0 8.616,38.923,0 8.616,38.947,0 8.604,38.965,0 8.581,38.96,0 8.573,39.013,0 8.56,39.057,0 8.553,39.057,0 8.545,39.051,0 8.521,39.061,0 8.505,39.063,0 8.51,39.068,0 8.519,39.083,0 8.505,39.091,0 8.483,39.08,0 8.483,39.084,0 8.478,39.09,0 8.474,39.107,0 8.466,39.119,0 8.455,39.125,0 8.443,39.118,0 8.439,39.128,0 8.439,39.153,0 8.436,39.166,0 8.429,39.173,0 8.419,39.177,0 8.413,39.175,0 8.416,39.166,0 8.41,39.169,0 8.406,39.174,0 8.403,39.181,0 8.402,39.19,0 8.399,39.201,0 8.393,39.204,0 8.386,39.204,0 8.381,39.207,0 8.373,39.222,0 8.372,39.23,0 8.377,39.238,0 8.427,39.283,0 8.433,39.302,0 8.416,39.323,0 8.418,39.339,0 8.383,39.359,0 8.375,39.379,0 8.379,39.388,0 8.396,39.404,0 8.402,39.412,0 8.406,39.427,0 8.404,39.436,0 8.39,39.462,0 8.387,39.465,0 8.387,39.47,0 8.395,39.481,0 8.422,39.508,0 8.436,39.525,0 8.452,39.558,0 8.464,39.577,0 8.457,39.584,0 8.465,39.598,0 8.463,39.617,0 8.45,39.659,0 8.447,39.704,0 8.443,39.714,0 8.443,39.721,0 8.447,39.731,0 8.445,39.757,0 8.447,39.762,0 8.46,39.76,0 8.469,39.755,0 8.5,39.716,0 8.518,39.702,0 8.539,39.696,0 8.566,39.701,0 8.515,39.713,0 8.505,39.721,0 8.507,39.738,0 8.521,39.755,0 8.536,39.771,0 8.546,39.783,0 8.539,39.783,0 8.536,39.776,0 8.531,39.77,0 8.525,39.766,0 8.519,39.762,0 8.53,39.772,0 8.541,39.789,0 8.549,39.807,0 8.553,39.821,0 8.556,39.852,0 8.554,39.864,0 8.546,39.878,0 8.524,39.899,0 8.495,39.912,0 8.464,39.914,0 8.436,39.899,0 8.443,39.893,0 8.446,39.898,0 8.45,39.899,0 8.456,39.898,0 8.464,39.899,0 8.452,39.893,0 8.445,39.883,0 8.436,39.858,0 8.429,39.865,0 8.438,39.877,0 8.432,39.885,0 8.419,39.892,0 8.404,39.903,0 8.401,39.903,0 8.399,39.905,0 8.395,39.912,0 8.394,39.92,0 8.397,39.927,0 8.4,39.933,0 8.402,39.94,0 8.394,39.977,0 8.395,39.988,0 8.407,40.01,0 8.408,40.022,0 8.395,40.036,0 8.381,40.03,0 8.378,40.033,0 8.385,40.042,0 8.402,40.05,0 8.405,40.049,0 8.435,40.051,0 8.453,40.056,0 8.46,40.057,0 8.469,40.062,0 8.48,40.074,0 8.488,40.089,0 8.491,40.104,0 8.486,40.118,0 8.468,40.144,0 8.464,40.163,0 8.46,40.216,0 8.477,40.262,0 8.477,40.292,0 8.463,40.314,0 8.442,40.331,0 8.416,40.345,0 8.409,40.338,0 8.387,40.352,0 8.384,40.372,0 8.395,40.424,0 8.391,40.442,0 8.38,40.468,0 8.366,40.492,0 8.35,40.502,0 8.332,40.51,0 8.324,40.531,0 8.32,40.555,0 8.313,40.578,0 8.292,40.595,0 8.268,40.594,0 8.217,40.57,0 8.196,40.578,0 8.206,40.598,0 8.217,40.612,0 8.194,40.617,0 8.177,40.606,0 8.167,40.586,0 8.162,40.564,0 8.154,40.578,0 8.148,40.593,0 8.141,40.619,0 8.141,40.625,0 8.158,40.632,0 8.174,40.641,0 8.186,40.656,0 8.189,40.68,0 8.192,40.68,0 8.196,40.685,0 8.198,40.691,0 8.193,40.694,0 8.18,40.695,0 8.174,40.697,0 8.168,40.701,0 8.154,40.719,0 8.146,40.726,0 8.134,40.729,0 8.21,40.865,0 8.216,40.881,0 8.217,40.899,0 8.21,40.914,0 8.193,40.92,0 8.179,40.928,0 8.183,40.945,0 8.194,40.963,0 8.203,40.975,0 8.21,40.975,0 8.213,40.963,0 8.221,40.962,0 8.229,40.962,0 8.237,40.955,0 8.236,40.946,0 8.232,40.934,0 8.23,40.921,0 8.234,40.91,0 8.278,40.865,0 8.311,40.85,0 8.422,40.839,0 8.478,40.826,0 8.501,40.824,0 8.521,40.827,0 8.599,40.853,0 8.619,40.866,0 8.635,40.881,0 8.641,40.896,0 8.71,40.92,0 8.734,40.921,0 8.752,40.919,0 8.765,40.914,0 8.823,40.947,0 8.84,40.961,0 8.876,41.008,0 8.889,41.016,0 8.887,41.02,0 8.887,41.021,0 8.886,41.022,0 8.882,41.023,0 8.914,41.032,0 8.923,41.037,0 8.93,41.043,0 8.941,41.061,0 8.947,41.064,0 8.959,41.07,0 8.976,41.082,0 8.991,41.097,0 9.006,41.122,0 9.025,41.129,0 9.094,41.135,0 9.108,41.139,0 9.136,41.16,0 9.142,41.153,0 9.158,41.169,0 9.164,41.184,0 9.163,41.225,0 9.172,41.243,0 9.191,41.251,0 9.213,41.256,0 9.231,41.262,0 9.233,41.253,0 9.239,41.249,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.435,41.217,0 9.395,41.211,0 9.377,41.213,0 9.373,41.222,0 9.373,41.23,0 9.378,41.234,0 9.385,41.237,0 9.392,41.241,0 9.396,41.248,0 9.398,41.256,0 9.402,41.258,0 9.408,41.258,0 9.414,41.262,0 9.422,41.261,0 9.427,41.254,0 9.431,41.246,0 9.43,41.238,0 9.429,41.229,0 9.431,41.225,0 9.434,41.221,0 9.435,41.217,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.316,42.341,0 10.313,42.324,0 10.294,42.328,0 10.297,42.345,0 10.306,42.352,0 10.316,42.341,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.922,42.334,0 10.909,42.325,0 10.874,42.36,0 10.862,42.366,0 10.871,42.376,0 10.877,42.387,0 10.884,42.392,0 10.896,42.386,0 10.907,42.378,0 10.919,42.356,0 10.931,42.346,0 10.926,42.339,0 10.922,42.334,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.095,42.577,0 10.086,42.572,0 10.072,42.573,0 10.059,42.576,0 10.05,42.582,0 10.053,42.589,0 10.063,42.592,0 10.073,42.6,0 10.08,42.614,0 10.084,42.615,0 10.088,42.604,0 10.092,42.596,0 10.096,42.591,0 10.098,42.588,0 10.098,42.584,0 10.095,42.577,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>10.431,42.816,0 10.437,42.804,0 10.431,42.787,0 10.421,42.776,0 10.407,42.769,0 10.389,42.763,0 10.408,42.757,0 10.426,42.741,0 10.431,42.722,0 10.416,42.709,0 10.411,42.718,0 10.404,42.719,0 10.394,42.718,0 10.382,42.722,0 10.378,42.728,0 10.368,42.746,0 10.365,42.75,0 10.352,42.755,0 10.338,42.765,0 10.326,42.765,0 10.314,42.743,0 10.305,42.76,0 10.266,42.744,0 10.246,42.757,0 10.241,42.742,0 10.236,42.736,0 10.23,42.735,0 10.148,42.737,0 10.125,42.743,0 10.107,42.757,0 10.102,42.784,0 10.112,42.801,0 10.134,42.812,0 10.159,42.817,0 10.18,42.819,0 10.19,42.817,0 10.213,42.808,0 10.225,42.804,0 10.243,42.803,0 10.266,42.804,0 10.266,42.809,0 10.265,42.81,0 10.263,42.81,0 10.26,42.812,0 10.273,42.819,0 10.273,42.826,0 10.273,42.827,0 10.29,42.825,0 10.327,42.826,0 10.323,42.811,0 10.333,42.806,0 10.348,42.806,0 10.355,42.808,0 10.359,42.817,0 10.366,42.823,0 10.375,42.827,0 10.382,42.832,0 10.393,42.858,0 10.401,42.869,0 10.413,42.873,0 10.422,42.871,0 10.432,42.864,0 10.439,42.855,0 10.444,42.845,0 10.437,42.838,0 10.432,42.828,0 10.431,42.816,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>9.844,43.06,0 9.848,43.058,0 9.854,43.059,0 9.843,43.035,0 9.828,43.019,0 9.81,43.017,0 9.793,43.037,0 9.812,43.071,0 9.827,43.081,0 9.841,43.065,0 9.842,43.063,0 9.844,43.06,0 </coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>12.122,46.972,0 12.128,46.949,0 12.135,46.937,0 12.142,46.928,0 12.142,46.919,0 12.127,46.909,0 12.137,46.906,0 12.161,46.903,0 12.172,46.899,0 12.184,46.891,0 12.189,46.885,0 12.195,46.88,0 12.209,46.877,0 12.251,46.876,0 12.267,46.868,0 12.276,46.846,0 12.276,46.834,0 12.273,46.827,0 12.27,46.82,0 12.267,46.808,0 12.267,46.795,0 12.269,46.789,0 12.275,46.785,0 12.284,46.78,0 12.305,46.774,0 12.326,46.772,0 12.343,46.765,0 12.351,46.743,0 12.37,46.711,0 12.405,46.69,0 12.446,46.679,0 12.5,46.672,0 12.531,46.658,0 12.547,46.652,0 12.562,46.651,0 12.62,46.656,0 12.67,46.653,0 12.679,46.65,0 12.697,46.641,0 12.707,46.638,0 12.716,46.638,0 12.732,46.642,0 12.74,46.643,0 12.774,46.635,0 12.83,46.61,0 13.065,46.598,0 13.146,46.585,0 13.21,46.558,0 13.231,46.552,0 13.271,46.551,0 13.373,46.566,0 13.417,46.56,0 13.478,46.564,0 13.485,46.562,0 13.499,46.551,0 13.507,46.547,0 13.549,46.546,0 13.67,46.519,0 13.685,46.518,0 13.701,46.52,0 13.701,46.512,0 13.699,46.505,0 13.695,46.499,0 13.69,46.493,0 13.688,46.468,0 13.677,46.452,0 13.659,46.445,0 13.634,46.446,0 13.6,46.443,0 13.576,46.427,0 13.554,46.406,0 13.53,46.388,0 13.484,46.371,0 13.46,46.359,0 13.447,46.355,0 13.434,46.354,0 13.423,46.345,0 13.41,46.324,0 13.391,46.302,0 13.365,46.29,0 13.373,46.28,0 13.379,46.268,0 13.385,46.243,0 13.385,46.243,0 13.385,46.243,0 13.398,46.231,0 13.402,46.217,0 13.41,46.208,0 13.437,46.211,0 13.423,46.229,0 13.438,46.225,0 13.468,46.223,0 13.482,46.218,0 13.51,46.214,0 13.529,46.205,0 13.559,46.184,0 13.584,46.181,0 13.614,46.184,0 13.637,46.18,0 13.645,46.162,0 13.616,46.125,0 13.505,46.066,0 13.482,46.045,0 13.49,46.039,0 13.493,46.032,0 13.49,46.026,0 13.482,46.018,0 13.477,46.016,0 13.462,46.006,0 13.475,45.996,0 13.479,45.993,0 13.48,45.992,0 13.481,45.991,0 13.482,45.99,0 13.482,45.989,0 13.509,45.967,0 13.539,45.969,0 13.572,45.98,0 13.606,45.985,0 13.623,45.966,0 13.608,45.927,0 13.569,45.865,0 13.566,45.83,0 13.581,45.809,0 13.609,45.799,0 13.644,45.796,0 13.66,45.792,0 13.709,45.765,0 13.779,45.743,0 13.858,45.649,0 13.869,45.641,0 13.884,45.635,0 13.893,45.635,0 13.895,45.632,0 13.887,45.619,0 13.848,45.585,0 13.801,45.581,0 13.761,45.596,0 13.712,45.593,0 13.719,45.6,0 13.731,45.613,0 13.757,45.613,0 13.787,45.611,0 13.809,45.614,0 13.796,45.617,0 13.787,45.624,0 13.778,45.635,0 13.74,45.649,0 13.758,45.655,0 13.754,45.672,0 13.74,45.691,0 13.727,45.703,0 13.648,45.762,0 13.63,45.772,0 13.575,45.789,0 13.552,45.792,0 13.535,45.782,0 13.525,45.76,0 13.529,45.74,0 13.555,45.737,0 13.519,45.725,0 13.514,45.721,0 13.508,45.714,0 13.481,45.71,0 13.47,45.707,0 13.452,45.694,0 13.429,45.681,0 13.402,45.675,0 13.377,45.683,0 13.392,45.686,0 13.41,45.691,0 13.425,45.698,0 13.432,45.707,0 13.423,45.724,0 13.382,45.73,0 13.37,45.744,0 13.352,45.74,0 13.255,45.756,0 13.246,45.759,0 13.222,45.776,0 13.216,45.779,0 13.206,45.778,0 13.17,45.768,0 13.158,45.754,0 13.15,45.751,0 13.14,45.755,0 13.132,45.769,0 13.12,45.772,0 13.111,45.767,0 13.109,45.758,0 13.112,45.749,0 13.124,45.744,0 13.124,45.737,0 13.101,45.736,0 13.081,45.727,0 13.07,45.713,0 13.076,45.697,0 13.092,45.689,0 13.112,45.691,0 13.15,45.703,0 13.139,45.689,0 13.104,45.669,0 13.096,45.652,0 13.086,45.642,0 13.061,45.636,0 12.982,45.635,0 12.944,45.628,0 12.781,45.553,0 12.612,45.496,0 12.513,45.47,0 12.497,45.46,0 12.488,45.456,0 12.452,45.45,0 12.424,45.438,0 12.411,45.436,0 12.419,45.451,0 12.43,45.464,0 12.436,45.475,0 12.431,45.484,0 12.441,45.483,0 12.448,45.484,0 12.452,45.489,0 12.452,45.498,0 12.459,45.498,0 12.463,45.489,0 12.468,45.485,0 12.472,45.486,0 12.479,45.491,0 12.466,45.504,0 12.477,45.503,0 12.488,45.504,0 12.498,45.506,0 12.5,45.504,0 12.501,45.506,0 12.504,45.503,0 12.507,45.499,0 12.507,45.498,0 12.504,45.498,0 12.493,45.498,0 12.493,45.491,0 12.516,45.492,0 12.521,45.505,0 12.522,45.519,0 12.531,45.525,0 12.549,45.527,0 12.563,45.531,0 12.574,45.54,0 12.582,45.553,0 12.57,45.549,0 12.545,45.536,0 12.538,45.536,0 12.519,45.55,0 12.511,45.559,0 12.507,45.573,0 12.486,45.565,0 12.459,45.548,0 12.443,45.53,0 12.452,45.518,0 12.452,45.512,0 12.435,45.512,0 12.418,45.523,0 12.411,45.518,0 12.404,45.518,0 12.397,45.539,0 12.385,45.523,0 12.391,45.514,0 12.425,45.504,0 12.425,45.498,0 12.412,45.493,0 12.394,45.491,0 12.381,45.494,0 12.384,45.504,0 12.351,45.505,0 12.31,45.489,0 12.273,45.463,0 12.253,45.436,0 12.253,45.43,0 12.259,45.43,0 12.251,45.42,0 12.247,45.411,0 12.249,45.402,0 12.259,45.395,0 12.25,45.385,0 12.248,45.378,0 12.249,45.371,0 12.246,45.361,0 12.238,45.358,0 12.229,45.357,0 12.224,45.354,0 12.233,45.34,0 12.221,45.327,0 12.217,45.316,0 12.209,45.309,0 12.188,45.306,0 12.175,45.31,0 12.164,45.316,0 12.155,45.313,0 12.15,45.292,0 12.16,45.283,0 12.169,45.262,0 12.181,45.258,0 12.192,45.263,0 12.2,45.274,0 12.203,45.288,0 12.198,45.299,0 12.218,45.294,0 12.222,45.283,0 12.221,45.269,0 12.225,45.251,0 12.214,45.248,0 12.212,45.243,0 12.216,45.237,0 12.225,45.23,0 12.222,45.216,0 12.231,45.204,0 12.248,45.197,0 12.267,45.196,0 12.264,45.2,0 12.263,45.201,0 12.259,45.203,0 12.274,45.211,0 12.296,45.226,0 12.308,45.23,0 12.299,45.215,0 12.305,45.201,0 12.316,45.186,0 12.322,45.172,0 12.322,45.139,0 12.329,45.101,0 12.319,45.103,0 12.308,45.108,0 12.309,45.114,0 12.308,45.124,0 12.308,45.128,0 12.298,45.106,0 12.297,45.088,0 12.307,45.078,0 12.329,45.08,0 12.326,45.083,0 12.324,45.086,0 12.322,45.093,0 12.341,45.081,0 12.354,45.067,0 12.364,45.052,0 12.377,45.039,0 12.377,45.032,0 12.369,45.031,0 12.365,45.029,0 12.361,45.027,0 12.356,45.024,0 12.369,45.011,0 12.384,45.026,0 12.387,45.039,0 12.381,45.051,0 12.369,45.065,0 12.384,45.056,0 12.402,45.05,0 12.414,45.043,0 12.411,45.032,0 12.427,45.02,0 12.435,45.015,0 12.445,45.011,0 12.465,44.992,0 12.487,44.976,0 12.5,44.983,0 12.497,44.984,0 12.49,44.983,0 12.487,44.983,0 12.487,44.991,0 12.503,44.991,0 12.517,44.987,0 12.528,44.98,0 12.535,44.97,0 12.534,44.961,0 12.524,44.95,0 12.528,44.943,0 12.519,44.934,0 12.516,44.928,0 12.513,44.922,0 12.507,44.922,0 12.5,44.921,0 12.495,44.91,0 12.493,44.878,0 12.488,44.862,0 12.475,44.845,0 12.445,44.82,0 12.444,44.825,0 12.439,44.835,0 12.433,44.846,0 12.425,44.854,0 12.44,44.877,0 12.444,44.89,0 12.439,44.901,0 12.427,44.905,0 12.416,44.9,0 12.407,44.891,0 12.404,44.884,0 12.393,44.868,0 12.392,44.859,0 12.417,44.851,0 12.416,44.843,0 12.409,44.836,0 12.397,44.833,0 12.397,44.826,0 12.404,44.825,0 12.417,44.821,0 12.425,44.82,0 12.417,44.803,0 12.398,44.794,0 12.376,44.792,0 12.358,44.804,0 12.347,44.815,0 12.322,44.833,0 12.304,44.843,0 12.293,44.843,0 12.267,44.826,0 12.267,44.82,0 12.281,44.82,0 12.254,44.751,0 12.247,44.711,0 12.253,44.668,0 12.266,44.636,0 12.276,44.62,0 12.284,44.614,0 12.286,44.602,0 12.281,44.532,0 12.284,44.487,0 12.315,44.387,0 12.319,44.361,0 12.322,44.353,0 12.326,44.348,0 12.34,44.334,0 12.343,44.329,0 12.345,44.308,0 12.351,44.288,0 12.369,44.25,0 12.391,44.222,0 12.418,44.195,0 12.459,44.166,0 12.479,44.139,0 12.511,44.114,0 12.548,44.093,0 12.575,44.085,0 12.632,44.03,0 12.662,44.008,0 12.692,43.99,0 12.711,43.983,0 12.757,43.972,0 12.804,43.967,0 12.823,43.958,0 12.863,43.935,0 12.929,43.916,0 12.939,43.904,0 12.948,43.897,0 13.254,43.703,0 13.371,43.65,0 13.39,43.644,0 13.4,43.635,0 13.447,43.623,0 13.474,43.612,0 13.484,43.616,0 13.491,43.623,0 13.497,43.627,0 13.5,43.628,0 13.502,43.63,0 13.505,43.633,0 13.511,43.633,0 13.517,43.631,0 13.52,43.627,0 13.522,43.622,0 13.525,43.62,0 13.544,43.613,0 13.558,43.596,0 13.57,43.58,0 13.579,43.573,0 13.599,43.569,0 13.616,43.56,0 13.625,43.547,0 13.618,43.531,0 13.761,43.264,0 13.777,43.243,0 13.781,43.236,0 13.787,43.2,0 13.791,43.192,0 13.803,43.178,0 13.835,43.127,0 13.849,43.092,0 13.866,43.007,0 13.945,42.798,0 13.981,42.73,0 14.002,42.698,0 14.064,42.625,0 14.069,42.609,0 14.076,42.599,0 14.221,42.47,0 14.285,42.428,0 14.357,42.393,0 14.388,42.373,0 14.43,42.321,0 14.561,42.225,0 14.596,42.208,0 14.654,42.191,0 14.694,42.185,0 14.71,42.175,0 14.718,42.16,0 14.723,42.119,0 14.73,42.099,0 14.741,42.084,0 14.758,42.079,0 14.781,42.075,0 14.8,42.066,0 14.836,42.044,0 14.871,42.032,0 14.953,42.021,0 14.994,42.01,0 15.008,42.001,0 15.035,41.974,0 15.046,41.969,0 15.064,41.964,0 15.105,41.942,0 15.124,41.934,0 15.166,41.927,0 15.282,41.928,0 15.401,41.908,0 15.447,41.907,0 15.612,41.928,0 15.775,41.921,0 16.028,41.944,0 16.112,41.928,0 16.112,41.926,0 16.141,41.92,0 16.161,41.892,0 16.18,41.893,0 16.177,41.877,0 16.184,41.858,0 16.193,41.821,0 16.194,41.808,0 16.193,41.791,0 16.185,41.779,0 16.167,41.763,0 16.146,41.749,0 16.128,41.742,0 16.108,41.737,0 16.09,41.726,0 16.064,41.701,0 16.028,41.68,0 15.926,41.64,0 15.901,41.614,0 15.892,41.577,0 15.897,41.536,0 15.912,41.503,0 15.934,41.479,0 15.962,41.459,0 16.022,41.428,0 16.086,41.412,0 16.101,41.403,0 16.115,41.393,0 16.302,41.328,0 16.461,41.262,0 16.521,41.25,0 16.539,41.239,0 16.555,41.227,0 16.594,41.207,0 16.831,41.146,0 16.852,41.133,0 16.859,41.133,0 16.859,41.14,0 16.865,41.14,0 16.886,41.124,0 17.058,41.082,0 17.204,41.021,0 17.277,40.98,0 17.311,40.955,0 17.348,40.912,0 17.362,40.906,0 17.378,40.902,0 17.414,40.881,0 17.476,40.83,0 17.493,40.824,0 17.513,40.82,0 17.549,40.802,0 17.635,40.785,0 17.646,40.78,0 17.749,40.747,0 17.844,40.694,0 17.922,40.683,0 17.956,40.67,0 17.956,40.647,0 17.967,40.647,0 17.993,40.653,0 18.008,40.65,0 18.012,40.644,0 18.012,40.635,0 18.016,40.625,0 18.04,40.608,0 18.044,40.602,0 18.038,40.557,0 18.12,40.504,0 18.212,40.464,0 18.232,40.461,0 18.239,40.457,0 18.259,40.43,0 18.271,40.421,0 18.304,40.4,0 18.33,40.366,0 18.344,40.351,0 18.362,40.345,0 18.371,40.338,0 18.438,40.268,0 18.501,40.152,0 18.505,40.146,0 18.51,40.142,0 18.517,40.139,0 18.512,40.127,0 18.514,40.12,0 18.518,40.114,0 18.517,40.104,0 18.509,40.094,0 18.492,40.084,0 18.484,40.055,0 18.471,40.043,0 18.435,40.022,0 18.412,39.979,0 18.408,39.968,0 18.405,39.947,0 18.395,39.925,0 18.393,39.916,0 18.4,39.89,0 18.401,39.878,0 18.387,39.825,0 18.39,39.817,0 18.384,39.814,0 18.374,39.8,0 18.369,39.796,0 18.347,39.798,0 18.339,39.8,0 18.331,39.803,0 18.283,39.833,0 18.266,39.837,0 18.225,39.837,0 18.212,39.839,0 18.187,39.852,0 18.162,39.86,0 18.131,39.883,0 18.095,39.903,0 18.082,39.906,0 18.072,39.911,0 18.008,39.986,0 17.996,39.995,0 17.996,40.002,0 18.012,40.003,0 18.021,40.01,0 18.023,40.021,0 18.016,40.036,0 18.006,40.045,0 17.979,40.051,0 17.968,40.057,0 18.003,40.074,0 18.012,40.096,0 17.998,40.12,0 17.968,40.146,0 17.941,40.163,0 17.927,40.176,0 17.92,40.191,0 17.92,40.21,0 17.917,40.227,0 17.912,40.24,0 17.9,40.249,0 17.913,40.249,0 17.913,40.255,0 17.864,40.285,0 17.848,40.29,0 17.513,40.303,0 17.494,40.307,0 17.441,40.331,0 17.431,40.331,0 17.41,40.33,0 17.4,40.331,0 17.393,40.335,0 17.375,40.348,0 17.369,40.351,0 17.352,40.355,0 17.297,40.379,0 17.241,40.395,0 17.213,40.406,0 17.201,40.42,0 17.224,40.428,0 17.244,40.441,0 17.248,40.457,0 17.228,40.474,0 17.248,40.48,0 17.296,40.473,0 17.317,40.482,0 17.324,40.498,0 17.305,40.499,0 17.262,40.488,0 17.264,40.491,0 17.269,40.496,0 17.248,40.503,0 17.23,40.497,0 17.211,40.487,0 17.191,40.482,0 17.182,40.485,0 17.177,40.493,0 17.172,40.502,0 17.167,40.509,0 17.157,40.512,0 17.134,40.512,0 17.125,40.515,0 17.05,40.519,0 16.977,40.492,0 16.913,40.445,0 16.783,40.301,0 16.762,40.269,0 16.738,40.211,0 16.731,40.2,0 16.716,40.193,0 16.68,40.146,0 16.625,40.108,0 16.605,40.084,0 16.597,40.046,0 16.6,40.034,0 16.614,39.996,0 16.632,39.966,0 16.622,39.953,0 16.606,39.943,0 16.59,39.92,0 16.543,39.885,0 16.509,39.837,0 16.492,39.805,0 16.49,39.775,0 16.503,39.747,0 16.529,39.721,0 16.529,39.714,0 16.516,39.689,0 16.546,39.661,0 16.592,39.636,0 16.625,39.625,0 16.75,39.62,0 16.783,39.611,0 16.799,39.603,0 16.817,39.591,0 16.831,39.576,0 16.838,39.56,0 16.847,39.552,0 16.906,39.529,0 16.954,39.499,0 16.971,39.495,0 16.996,39.492,0 17.012,39.486,0 17.024,39.475,0 17.036,39.461,0 17.058,39.441,0 17.089,39.422,0 17.125,39.409,0 17.159,39.406,0 17.123,39.338,0 17.115,39.283,0 17.115,39.269,0 17.118,39.256,0 17.125,39.244,0 17.143,39.222,0 17.146,39.21,0 17.141,39.179,0 17.123,39.121,0 17.125,39.091,0 17.148,39.054,0 17.152,39.046,0 17.159,39.04,0 17.193,39.031,0 17.207,39.029,0 17.187,39.019,0 17.177,39.012,0 17.173,39.005,0 17.172,38.966,0 17.173,38.96,0 17.139,38.936,0 17.136,38.932,0 17.128,38.929,0 17.119,38.919,0 17.105,38.899,0 17.096,38.919,0 17.071,38.923,0 17.043,38.916,0 17.023,38.906,0 16.997,38.929,0 16.982,38.937,0 16.958,38.94,0 16.936,38.938,0 16.839,38.918,0 16.728,38.879,0 16.688,38.856,0 16.68,38.847,0 16.671,38.84,0 16.611,38.816,0 16.586,38.798,0 16.575,38.785,0 16.564,38.756,0 16.551,38.741,0 16.539,38.723,0 16.535,38.7,0 16.547,38.693,0 16.55,38.69,0 16.549,38.672,0 16.559,38.596,0 16.578,38.528,0 16.578,38.503,0 16.57,38.429,0 16.562,38.416,0 16.523,38.387,0 16.509,38.371,0 16.498,38.369,0 16.468,38.348,0 16.436,38.34,0 16.34,38.301,0 16.307,38.277,0 16.17,38.143,0 16.152,38.111,0 16.126,38.005,0 16.112,37.973,0 16.102,37.96,0 16.091,37.949,0 16.078,37.94,0 16.064,37.932,0 16.016,37.924,0 16.002,37.919,0 15.943,37.933,0 15.762,37.925,0 15.736,37.931,0 15.709,37.941,0 15.685,37.953,0 15.666,37.967,0 15.646,37.988,0 15.636,38.009,0 15.639,38.027,0 15.659,38.042,0 15.633,38.074,0 15.625,38.092,0 15.628,38.107,0 15.642,38.126,0 15.648,38.143,0 15.647,38.162,0 15.639,38.186,0 15.633,38.22,0 15.651,38.241,0 15.685,38.253,0 15.787,38.278,0 15.796,38.285,0 15.799,38.291,0 15.813,38.3,0 15.817,38.306,0 15.83,38.351,0 15.905,38.474,0 15.918,38.517,0 15.916,38.55,0 15.901,38.578,0 15.871,38.604,0 15.864,38.608,0 15.851,38.613,0 15.845,38.618,0 15.836,38.628,0 15.834,38.634,0 15.836,38.639,0 15.837,38.649,0 15.845,38.66,0 15.864,38.668,0 15.905,38.679,0 15.969,38.712,0 16.003,38.725,0 16.049,38.728,0 16.121,38.721,0 16.137,38.724,0 16.153,38.731,0 16.18,38.748,0 16.201,38.776,0 16.216,38.814,0 16.222,38.856,0 16.221,38.899,0 16.215,38.919,0 16.205,38.934,0 16.19,38.943,0 16.169,38.947,0 16.155,38.955,0 16.14,38.974,0 16.084,39.075,0 16.043,39.31,0 16.032,39.345,0 15.955,39.489,0 15.934,39.513,0 15.905,39.536,0 15.877,39.551,0 15.868,39.564,0 15.865,39.588,0 15.851,39.615,0 15.837,39.652,0 15.816,39.679,0 15.807,39.695,0 15.789,39.796,0 15.789,39.79,0 15.784,39.81,0 15.779,39.82,0 15.772,39.824,0 15.77,39.83,0 15.783,39.868,0 15.775,39.891,0 15.742,39.929,0 15.735,39.943,0 15.729,39.964,0 15.714,39.981,0 15.679,40.009,0 15.652,40.043,0 15.631,40.057,0 15.625,40.065,0 15.625,40.078,0 15.611,40.073,0 15.536,40.078,0 15.51,40.07,0 15.493,40.059,0 15.46,40.029,0 15.425,40.004,0 15.405,39.999,0 15.377,40.002,0 15.354,40.012,0 15.315,40.034,0 15.303,40.036,0 15.294,40.032,0 15.284,40.03,0 15.273,40.028,0 15.262,40.029,0 15.262,40.036,0 15.28,40.047,0 15.264,40.074,0 15.234,40.1,0 15.21,40.112,0 15.191,40.119,0 15.128,40.169,0 15.113,40.175,0 15.096,40.173,0 15.066,40.166,0 15.048,40.169,0 15.035,40.175,0 15.015,40.194,0 14.974,40.223,0 14.967,40.224,0 14.959,40.231,0 14.923,40.238,0 14.912,40.241,0 14.907,40.258,0 14.932,40.285,0 14.94,40.307,0 14.933,40.324,0 14.933,40.334,0 14.943,40.338,0 14.954,40.34,0 14.965,40.345,0 14.973,40.352,0 14.98,40.359,0 14.99,40.394,0 14.976,40.431,0 14.889,40.573,0 14.862,40.607,0 14.836,40.632,0 14.81,40.653,0 14.783,40.67,0 14.753,40.676,0 14.72,40.667,0 14.691,40.649,0 14.679,40.646,0 14.626,40.649,0 14.614,40.646,0 14.572,40.617,0 14.545,40.613,0 14.517,40.62,0 14.487,40.632,0 14.472,40.624,0 14.423,40.615,0 14.402,40.602,0 14.356,40.583,0 14.343,40.57,0 14.331,40.584,0 14.329,40.605,0 14.338,40.624,0 14.36,40.632,0 14.38,40.634,0 14.388,40.637,0 14.395,40.65,0 14.403,40.657,0 14.471,40.699,0 14.48,40.711,0 14.475,40.729,0 14.461,40.744,0 14.443,40.755,0 14.426,40.762,0 14.415,40.765,0 14.399,40.767,0 14.391,40.77,0 14.385,40.774,0 14.372,40.787,0 14.367,40.79,0 14.349,40.797,0 14.313,40.828,0 14.295,40.839,0 14.276,40.84,0 14.249,40.837,0 14.224,40.831,0 14.213,40.821,0 14.204,40.801,0 14.182,40.8,0 14.112,40.829,0 14.096,40.834,0 14.083,40.831,0 14.077,40.822,0 14.078,40.81,0 14.082,40.797,0 14.083,40.783,0 14.075,40.788,0 14.041,40.798,0 14.053,40.837,0 14.044,40.875,0 13.966,40.996,0 13.931,41.014,0 13.918,41.023,0 13.915,41.033,0 13.913,41.054,0 13.911,41.064,0 13.885,41.104,0 13.786,41.203,0 13.722,41.252,0 13.709,41.256,0 13.679,41.25,0 13.664,41.25,0 13.657,41.259,0 13.595,41.253,0 13.564,41.238,0 13.576,41.208,0 13.544,41.206,0 13.535,41.208,0 13.526,41.215,0 13.52,41.225,0 13.515,41.229,0 13.508,41.221,0 13.5,41.221,0 13.481,41.239,0 13.325,41.295,0 13.286,41.295,0 13.205,41.284,0 13.187,41.278,0 13.152,41.26,0 13.115,41.251,0 13.091,41.226,0 13.069,41.221,0 13.045,41.227,0 13.037,41.24,0 13.034,41.257,0 13.024,41.273,0 13.013,41.286,0 12.993,41.315,0 12.98,41.331,0 12.924,41.379,0 12.894,41.399,0 12.863,41.413,0 12.842,41.418,0 12.764,41.421,0 12.749,41.423,0 12.679,41.458,0 12.655,41.465,0 12.643,41.458,0 12.636,41.447,0 12.62,41.459,0 12.546,41.544,0 12.449,41.63,0 12.343,41.702,0 12.328,41.711,0 12.301,41.717,0 12.286,41.727,0 12.277,41.729,0 12.247,41.733,0 12.24,41.736,0 12.224,41.75,0 12.216,41.768,0 12.212,41.787,0 12.212,41.808,0 12.207,41.827,0 12.195,41.847,0 12.171,41.879,0 12.148,41.903,0 12.05,41.96,0 12.039,41.965,0 12.03,41.973,0 12.027,41.986,0 12.021,41.993,0 11.993,41.996,0 11.983,42,0 11.97,42.011,0 11.953,42.022,0 11.935,42.031,0 11.917,42.038,0 11.84,42.036,0 11.828,42.034,0 11.823,42.047,0 11.81,42.066,0 11.794,42.084,0 11.78,42.092,0 11.772,42.106,0 11.751,42.128,0 11.746,42.136,0 11.744,42.152,0 11.737,42.169,0 11.683,42.252,0 11.659,42.279,0 11.54,42.349,0 11.49,42.359,0 11.421,42.386,0 11.397,42.393,0 11.397,42.4,0 11.387,42.404,0 11.377,42.407,0 11.366,42.408,0 11.355,42.407,0 11.363,42.4,0 11.334,42.4,0 11.26,42.421,0 11.246,42.422,0 11.228,42.422,0 11.212,42.419,0 11.205,42.411,0 11.201,42.395,0 11.187,42.379,0 11.185,42.366,0 11.175,42.369,0 11.165,42.369,0 11.158,42.368,0 11.157,42.366,0 11.148,42.371,0 11.135,42.384,0 11.107,42.391,0 11.095,42.402,0 11.087,42.418,0 11.081,42.435,0 11.1,42.443,0 11.123,42.446,0 11.167,42.448,0 11.175,42.458,0 11.184,42.48,0 11.19,42.504,0 11.188,42.521,0 11.167,42.546,0 11.159,42.564,0 11.149,42.563,0 11.138,42.559,0 11.129,42.558,0 11.117,42.572,0 11.108,42.591,0 11.098,42.607,0 11.081,42.612,0 11.078,42.632,0 11.054,42.647,0 11.006,42.668,0 11.001,42.68,0 10.996,42.696,0 10.99,42.71,0 10.982,42.716,0 10.973,42.72,0 10.944,42.743,0 10.891,42.764,0 10.732,42.804,0 10.756,42.819,0 10.766,42.835,0 10.767,42.854,0 10.766,42.877,0 10.769,42.884,0 10.775,42.888,0 10.778,42.894,0 10.774,42.908,0 10.764,42.918,0 10.751,42.925,0 10.682,42.949,0 10.633,42.958,0 10.584,42.959,0 10.54,42.949,0 10.544,42.939,0 10.547,42.935,0 10.519,42.925,0 10.5,42.94,0 10.478,42.99,0 10.503,43.005,0 10.518,43.024,0 10.54,43.079,0 10.536,43.091,0 10.536,43.112,0 10.54,43.134,0 10.547,43.147,0 10.539,43.164,0 10.535,43.185,0 10.533,43.226,0 10.529,43.246,0 10.517,43.267,0 10.438,43.388,0 10.374,43.453,0 10.36,43.465,0 10.327,43.477,0 10.318,43.492,0 10.295,43.568,0 10.265,43.809,0 10.252,43.846,0 10.211,43.92,0 10.181,43.955,0 10.137,43.978,0 10.106,44.016,0 10.091,44.025,0 10.073,44.029,0 10.036,44.048,0 10.015,44.052,0 9.999,44.058,0 9.989,44.06,0 9.985,44.055,0 9.981,44.05,0 9.973,44.045,0 9.963,44.044,0 9.954,44.048,0 9.938,44.06,0 9.905,44.08,0 9.888,44.093,0 9.877,44.088,0 9.845,44.108,0 9.827,44.107,0 9.834,44.1,0 9.829,44.098,0 9.825,44.095,0 9.82,44.093,0 9.825,44.085,0 9.831,44.079,0 9.839,44.075,0 9.848,44.072,0 9.848,44.066,0 9.842,44.063,0 9.839,44.06,0 9.834,44.052,0 9.847,44.046,0 9.843,44.041,0 9.833,44.042,0 9.827,44.055,0 9.82,44.063,0 9.772,44.079,0 9.722,44.113,0 9.71,44.118,0 9.683,44.136,0 9.673,44.141,0 9.644,44.142,0 9.632,44.144,0 9.622,44.148,0 9.587,44.178,0 9.581,44.179,0 9.573,44.191,0 9.557,44.2,0 9.512,44.215,0 9.5,44.222,0 9.49,44.231,0 9.485,44.244,0 9.473,44.24,0 9.454,44.237,0 9.437,44.239,0 9.43,44.247,0 9.423,44.257,0 9.375,44.272,0 9.368,44.294,0 9.263,44.336,0 9.231,44.353,0 9.222,44.344,0 9.214,44.333,0 9.21,44.321,0 9.211,44.305,0 9.166,44.318,0 9.147,44.328,0 9.149,44.34,0 9.131,44.363,0 9.103,44.374,0 9.002,44.387,0 8.953,44.4,0 8.924,44.411,0 8.915,44.409,0 8.869,44.409,0 8.846,44.413,0 8.838,44.417,0 8.828,44.428,0 8.763,44.432,0 8.738,44.429,0 8.725,44.424,0 8.696,44.406,0 8.686,44.398,0 8.679,44.394,0 8.671,44.394,0 8.663,44.395,0 8.656,44.394,0 8.594,44.363,0 8.577,44.36,0 8.565,44.357,0 8.541,44.34,0 8.467,44.304,0 8.445,44.284,0 8.45,44.264,0 8.44,44.253,0 8.437,44.247,0 8.436,44.24,0 8.433,44.238,0 8.418,44.23,0 8.412,44.227,0 8.407,44.215,0 8.409,44.204,0 8.409,44.193,0 8.395,44.182,0 8.37,44.173,0 8.314,44.16,0 8.285,44.148,0 8.27,44.138,0 8.257,44.128,0 8.234,44.103,0 8.231,44.096,0 8.232,44.08,0 8.231,44.072,0 8.224,44.057,0 8.217,44.045,0 8.17,44.006,0 8.153,43.983,0 8.168,43.962,0 8.168,43.956,0 8.145,43.952,0 8.116,43.927,0 8.09,43.92,0 8.082,43.915,0 8.076,43.909,0 8.073,43.904,0 8.068,43.896,0 8.056,43.892,0 8.032,43.887,0 7.96,43.853,0 7.786,43.822,0 7.737,43.798,0 7.695,43.791,0 7.573,43.791,0 7.545,43.784,0 7.532,43.784,0 7.524,43.789,0 7.513,43.792,0 7.503,43.792,0 7.483,43.84,0 7.478,43.866,0 7.493,43.886,0 7.537,43.921,0 7.557,43.944,0 7.609,43.976,0 7.631,43.994,0 7.639,44.005,0 7.647,44.027,0 7.653,44.04,0 7.664,44.049,0 7.679,44.057,0 7.69,44.067,0 7.692,44.085,0 7.676,44.109,0 7.654,44.125,0 7.642,44.144,0 7.656,44.176,0 7.625,44.18,0 7.584,44.161,0 7.555,44.159,0 7.381,44.123,0 7.341,44.124,0 7.331,44.125,0 7.322,44.132,0 7.316,44.14,0 7.309,44.147,0 7.296,44.151,0 7.27,44.154,0 7.251,44.16,0 7.145,44.207,0 7.105,44.218,0 7.046,44.24,0 7.033,44.243,0 7.02,44.242,0 7.008,44.239,0 6.996,44.238,0 6.983,44.242,0 6.973,44.249,0 6.969,44.258,0 6.966,44.268,0 6.959,44.277,0 6.95,44.285,0 6.93,44.295,0 6.921,44.302,0 6.916,44.31,0 6.904,44.33,0 6.896,44.34,0 6.874,44.358,0 6.87,44.363,0 6.866,44.372,0 6.866,44.377,0 6.869,44.383,0 6.877,44.414,0 6.884,44.423,0 6.918,44.436,0 6.892,44.452,0 6.861,44.475,0 6.839,44.503,0 6.836,44.534,0 6.846,44.547,0 6.897,44.575,0 6.932,44.618,0 6.946,44.625,0 6.934,44.647,0 6.941,44.667,0 6.96,44.683,0 6.983,44.692,0 7.001,44.692,0 7.037,44.685,0 7.055,44.685,0 7.049,44.698,0 7.019,44.739,0 7.015,44.747,0 7.01,44.772,0 6.998,44.794,0 6.999,44.795,0 7.004,44.811,0 7.006,44.812,0 7.006,44.816,0 7.007,44.819,0 7.007,44.822,0 7.005,44.828,0 7.001,44.833,0 6.983,44.847,0 6.933,44.862,0 6.915,44.863,0 6.866,44.856,0 6.847,44.859,0 6.778,44.888,0 6.745,44.908,0 6.728,44.929,0 6.73,44.985,0 6.723,45.013,0 6.697,45.027,0 6.662,45.029,0 6.652,45.036,0 6.64,45.05,0 6.637,45.059,0 6.638,45.067,0 6.637,45.074,0 6.62,45.084,0 6.603,45.103,0 6.615,45.115,0 6.633,45.126,0 6.667,45.14,0 6.676,45.141,0 6.694,45.14,0 6.702,45.141,0 6.711,45.145,0 6.729,45.155,0 6.736,45.157,0 6.771,45.153,0 6.808,45.139,0 6.844,45.13,0 6.877,45.141,0 6.879,45.147,0 6.873,45.152,0 6.868,45.157,0 6.873,45.166,0 6.881,45.168,0 6.905,45.169,0 6.914,45.17,0 6.928,45.18,0 6.946,45.201,0 6.959,45.21,0 6.994,45.221,0 7.03,45.228,0 7.038,45.226,0 7.05,45.215,0 7.055,45.214,0 7.062,45.219,0 7.081,45.243,0 7.108,45.259,0 7.108,45.275,0 7.098,45.295,0 7.093,45.324,0 7.098,45.33,0 7.13,45.357,0 7.151,45.383,0 7.16,45.398,0 7.161,45.411,0 7.153,45.415,0 7.11,45.428,0 7.097,45.435,0 7.089,45.447,0 7.082,45.459,0 7.072,45.47,0 7.028,45.493,0 6.983,45.511,0 6.975,45.526,0 6.97,45.567,0 6.966,45.574,0 6.955,45.586,0 6.953,45.594,0 6.956,45.603,0 6.967,45.62,0 6.969,45.626,0 6.963,45.641,0 6.951,45.647,0 6.919,45.653,0 6.905,45.66,0 6.883,45.676,0 6.869,45.679,0 6.843,45.683,0 6.816,45.697,0 6.796,45.718,0 6.785,45.76,0 6.782,45.777,0 6.783,45.795,0 6.788,45.812,0 6.801,45.826,0 6.816,45.833,0 6.846,45.836,0 6.846,45.838,0 6.849,45.842,0 6.853,45.847,0 6.858,45.849,0 6.862,45.849,0 6.87,45.845,0 6.873,45.845,0 6.88,45.846,0 6.905,45.845,0 6.926,45.85,0 6.949,45.858,0 6.969,45.87,0 6.983,45.886,0 6.989,45.899,0 6.997,45.911,0 7.008,45.921,0 7.022,45.925,0 7.067,45.89,0 7.09,45.881,0 7.121,45.876,0 7.154,45.877,0 7.184,45.88,0 7.245,45.898,0 7.274,45.91,0 7.287,45.913,0 7.362,45.908,0 7.394,45.916,0 7.453,45.946,0 7.483,45.955,0 7.504,45.957,0 7.515,45.967,0 7.524,45.978,0 7.541,45.984,0 7.643,45.966,0 7.659,45.96,0 7.674,45.95,0 7.693,45.931,0 7.694,45.929,0 7.706,45.926,0 7.715,45.927,0 7.722,45.93,0 7.732,45.93,0 7.78,45.918,0 7.808,45.918,0 7.825,45.915,0 7.831,45.914,0 7.844,45.919,0 7.846,45.923,0 7.845,45.928,0 7.848,45.938,0 7.872,45.969,0 7.898,45.982,0 7.969,45.993,0 7.979,45.995,0 7.986,45.999,0 7.998,46.011,0 7.999,46.013,0 8.009,46.028,0 8.011,46.03,0 8.016,46.058,0 8.016,46.069,0 8.018,46.081,0 8.025,46.091,0 8.035,46.097,0 8.056,46.098,0 8.067,46.101,0 8.111,46.127,0 8.132,46.159,0 8.13,46.196,0 8.1,46.236,0 8.077,46.25,0 8.073,46.254,0 8.077,46.262,0 8.087,46.272,0 8.107,46.286,0 8.128,46.292,0 8.172,46.299,0 8.193,46.309,0 8.242,46.354,0 8.27,46.364,0 8.282,46.37,0 8.291,46.378,0 8.297,46.388,0 8.297,46.398,0 8.29,46.401,0 8.287,46.405,0 8.295,46.418,0 8.316,46.434,0 8.343,46.444,0 8.399,46.452,0 8.428,46.449,0 8.442,46.435,0 8.446,46.412,0 8.446,46.382,0 8.443,46.353,0 8.427,46.302,0 8.423,46.276,0 8.427,46.251,0 8.438,46.235,0 8.457,46.225,0 8.483,46.218,0 8.51,46.208,0 8.539,46.188,0 8.602,46.123,0 8.612,46.119,0 8.631,46.115,0 8.677,46.096,0 8.695,46.095,0 8.702,46.098,0 8.718,46.108,0 8.724,46.11,0 8.732,46.107,0 8.739,46.098,0 8.747,46.094,0 8.763,46.093,0 8.794,46.093,0 8.809,46.09,0 8.834,46.066,0 8.82,46.043,0 8.791,46.019,0 8.773,45.991,0 8.77,45.986,0 8.768,45.983,0 8.785,45.982,0 8.8,45.979,0 8.858,45.957,0 8.864,45.953,0 8.871,45.947,0 8.881,45.931,0 8.898,45.91,0 8.907,45.896,0 8.912,45.883,0 8.914,45.866,0 8.91,45.854,0 8.904,45.842,0 8.9,45.826,0 8.94,45.835,0 8.972,45.825,0 9.002,45.821,0 9.034,45.848,0 9.059,45.882,0 9.063,45.899,0 9.052,45.916,0 9.042,45.92,0 9.021,45.923,0 9.011,45.927,0 9.002,45.936,0 8.993,45.954,0 8.983,45.962,0 8.981,45.964,0 8.98,45.967,0 8.981,45.969,0 8.983,45.972,0 9.016,45.993,0 8.998,46.028,0 9.002,46.039,0 9.028,46.053,0 9.05,46.058,0 9.059,46.062,0 9.067,46.071,0 9.07,46.083,0 9.068,46.106,0 9.072,46.119,0 9.091,46.138,0 9.163,46.172,0 9.171,46.183,0 9.176,46.194,0 9.181,46.204,0 9.192,46.21,0 9.204,46.214,0 9.216,46.221,0 9.225,46.231,0 9.24,46.267,0 9.269,46.309,0 9.275,46.331,0 9.274,46.344,0 9.26,46.38,0 9.26,46.394,0 9.263,46.407,0 9.261,46.417,0 9.248,46.423,0 9.238,46.437,0 9.246,46.461,0 9.263,46.485,0 9.282,46.497,0 9.331,46.502,0 9.351,46.498,0 9.352,46.485,0 9.377,46.469,0 9.385,46.466,0 9.395,46.469,0 9.4,46.475,0 9.404,46.483,0 9.411,46.489,0 9.427,46.497,0 9.435,46.498,0 9.438,46.492,0 9.444,46.396,0 9.442,46.381,0 9.444,46.375,0 9.452,46.37,0 9.474,46.362,0 9.483,46.357,0 9.503,46.321,0 9.515,46.309,0 9.536,46.299,0 9.56,46.293,0 9.674,46.292,0 9.693,46.297,0 9.708,46.312,0 9.709,46.32,0 9.707,46.331,0 9.709,46.342,0 9.72,46.351,0 9.731,46.351,0 9.755,46.341,0 9.768,46.339,0 9.789,46.343,0 9.855,46.367,0 9.899,46.372,0 9.918,46.371,0 9.939,46.367,0 9.964,46.356,0 9.971,46.34,0 9.971,46.32,0 9.978,46.298,0 9.992,46.284,0 10.032,46.26,0 10.042,46.243,0 10.043,46.22,0 10.076,46.22,0 10.118,46.231,0 10.146,46.243,0 10.159,46.262,0 10.146,46.28,0 10.105,46.309,0 10.096,46.321,0 10.092,46.329,0 10.092,46.338,0 10.097,46.352,0 10.105,46.361,0 10.126,46.374,0 10.133,46.381,0 10.141,46.403,0 10.133,46.414,0 10.116,46.419,0 10.071,46.425,0 10.042,46.433,0 10.026,46.446,0 10.044,46.467,0 10.035,46.471,0 10.03,46.477,0 10.028,46.484,0 10.027,46.493,0 10.031,46.504,0 10.031,46.526,0 10.033,46.533,0 10.041,46.542,0 10.063,46.557,0 10.071,46.564,0 10.083,46.597,0 10.088,46.604,0 10.097,46.608,0 10.192,46.627,0 10.218,46.627,0 10.234,46.618,0 10.236,46.607,0 10.23,46.586,0 10.235,46.575,0 10.276,46.566,0 10.284,46.561,0 10.289,46.556,0 10.295,46.551,0 10.307,46.547,0 10.319,46.546,0 10.354,46.548,0 10.426,46.535,0 10.444,46.538,0 10.458,46.554,0 10.466,46.578,0 10.467,46.604,0 10.459,46.624,0 10.438,46.636,0 10.396,46.639,0 10.378,46.653,0 10.369,46.672,0 10.374,46.682,0 10.385,46.689,0 10.394,46.701,0 10.397,46.715,0 10.396,46.726,0 10.4,46.736,0 10.417,46.743,0 10.429,46.756,0 10.426,46.769,0 10.419,46.784,0 10.417,46.799,0 10.439,46.817,0 10.445,46.823,0 10.449,46.832,0 10.454,46.864,0 10.486,46.846,0 10.528,46.843,0 10.629,46.862,0 10.647,46.864,0 10.662,46.861,0 10.739,46.83,0 10.749,46.819,0 10.744,46.813,0 10.722,46.8,0 10.717,46.795,0 10.723,46.786,0 10.734,46.786,0 10.755,46.791,0 10.766,46.788,0 10.795,46.777,0 10.805,46.777,0 10.824,46.78,0 10.834,46.78,0 10.843,46.777,0 10.86,46.767,0 10.87,46.764,0 10.88,46.765,0 10.914,46.772,0 10.931,46.774,0 10.966,46.772,0 10.983,46.768,0 10.997,46.769,0 11.011,46.779,0 11.033,46.806,0 11.037,46.808,0 11.049,46.812,0 11.053,46.815,0 11.055,46.82,0 11.053,46.83,0 11.054,46.834,0 11.073,46.865,0 11.084,46.9,0 11.092,46.912,0 11.157,46.957,0 11.174,46.964,0 11.244,46.979,0 11.314,46.987,0 11.349,46.982,0 11.381,46.972,0 11.411,46.97,0 11.445,46.993,0 11.445,46.993,0 11.453,47.001,0 11.462,47.006,0 11.472,47.007,0 11.489,47.004,0 11.496,47.002,0 11.502,46.998,0 11.507,46.993,0 11.515,46.989,0 11.524,46.988,0 11.534,46.99,0 11.543,46.993,0 11.543,46.993,0 11.544,46.993,0 11.544,46.993,0 11.573,46.999,0 11.596,47,0 11.648,46.993,0 11.648,46.993,0 11.65,46.993,0 11.657,46.993,0 11.665,46.993,0 11.684,46.992,0 11.716,46.975,0 11.735,46.971,0 11.746,46.972,0 11.766,46.983,0 11.777,46.988,0 11.823,46.993,0 11.857,47.012,0 11.9,47.028,0 11.944,47.038,0 12.015,47.04,0 12.116,47.077,0 12.181,47.085,0 12.204,47.08,0 12.204,47.053,0 12.182,47.034,0 12.122,47.011,0 12.111,46.993,0 12.118,46.983,0 12.122,46.972,0 </coordinates></LinearRing></outerBoundaryIs><innerBoundaryIs><LinearRing><coordinates>12.4,43.903,0 12.429,43.892,0 12.461,43.895,0 12.479,43.917,0 12.478,43.92,0 12.478,43.923,0 12.48,43.926,0 12.483,43.929,0 12.49,43.939,0 12.492,43.956,0 12.489,43.973,0 12.482,43.983,0 12.453,43.979,0 12.421,43.967,0 12.396,43.948,0 12.386,43.925,0 12.4,43.903,0 </coordinates></LinearRing></innerBoundaryIs><innerBoundaryIs><LinearRing><coordinates>12.444,41.902,0 12.449,41.9,0 12.455,41.9,0 12.458,41.902,0 12.455,41.908,0 12.447,41.907,0 12.444,41.902,0 </coordinates></LinearRing></innerBoundaryIs></Polygon></MultiGeometry>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(k.features())[0].geometry, MultiPolygon))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_atom(self):
pass
def test_schema(self):
doc = """<Schema name="TrailHeadType" id="TrailHeadTypeId">
<SimpleField type="string" name="TrailHeadName">
<displayName><![CDATA[<b>Trail Head Name</b>]]></displayName>
</SimpleField>
<SimpleField type="double" name="TrailLength">
<displayName><![CDATA[<i>The length in miles</i>]]></displayName>
</SimpleField>
<SimpleField type="int" name="ElevationGain">
<displayName><![CDATA[<i>change in altitude</i>]]></displayName>
</SimpleField>
</Schema> """
s = kml.Schema(ns='', id='default')
s.from_string(doc)
self.assertEqual(len(list(s.simple_fields)), 3)
self.assertEqual(list(s.simple_fields)[0]['type'], 'string')
self.assertEqual(list(s.simple_fields)[1]['type'], 'double')
self.assertEqual(list(s.simple_fields)[2]['type'], 'int')
self.assertEqual(list(s.simple_fields)[0]['name'], 'TrailHeadName')
self.assertEqual(list(s.simple_fields)[1]['name'], 'TrailLength')
self.assertEqual(list(s.simple_fields)[2]['name'], 'ElevationGain')
self.assertEqual(list(s.simple_fields)[0][
'displayName'
], '<b>Trail Head Name</b>')
self.assertEqual(list(s.simple_fields)[1][
'displayName'
], '<i>The length in miles</i>')
self.assertEqual(list(s.simple_fields)[2][
'displayName'
], '<i>change in altitude</i>')
s1 = kml.Schema(ns='', id='default')
s1.from_string(s.to_string())
self.assertEqual(len(list(s1.simple_fields)), 3)
self.assertEqual(list(s1.simple_fields)[0]['type'], 'string')
self.assertEqual(list(s1.simple_fields)[1]['name'], 'TrailLength')
self.assertEqual(list(s1.simple_fields)[2][
'displayName'
], '<i>change in altitude</i>')
self.assertEqual(s.to_string(), s1.to_string())
doc1 = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
%s
</Document>
</kml>""" % doc
k = kml.KML()
k.from_string(doc1)
d = list(k.features())[0]
s2 = list(d.schemata())[0]
s.ns = config.NS
self.assertEqual(s.to_string(), s2.to_string())
k1 = kml.KML()
k1.from_string(k.to_string())
self.assertTrue('Schema' in k1.to_string())
self.assertTrue('SimpleField' in k1.to_string())
self.assertEqual(k1.to_string(), k.to_string())
def test_schema_data(self):
doc = """<SchemaData schemaUrl="#TrailHeadTypeId">
<SimpleData name="TrailHeadName">Pi in the sky</SimpleData>
<SimpleData name="TrailLength">3.14159</SimpleData>
<SimpleData name="ElevationGain">10</SimpleData>
</SchemaData>"""
sd = kml.SchemaData(ns='', schema_url='#default')
sd.from_string(doc)
self.assertEqual(sd.schema_url, '#TrailHeadTypeId')
self.assertEqual(
sd.data[0], {'name': 'TrailHeadName',
'value': 'Pi in the sky'})
self.assertEqual(
sd.data[1], {'name': 'TrailLength',
'value': '3.14159'})
self.assertEqual(sd.data[2], {'name': 'ElevationGain', 'value': '10'})
sd1 = kml.SchemaData(ns='', schema_url='#default')
sd1.from_string(sd.to_string())
self.assertEqual(sd1.schema_url, '#TrailHeadTypeId')
self.assertEqual(sd.to_string(), sd1.to_string())
def test_snippet(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<Snippet maxLines="2" >Short Desc</Snippet>
</Placemark> </kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(list(k.features())[0].snippet['text'], 'Short Desc')
self.assertEqual(list(k.features())[0].snippet['maxLines'], 2)
list(k.features())[0]._snippet['maxLines'] = 3
self.assertEqual(list(k.features())[0].snippet['maxLines'], 3)
self.assertTrue('maxLines="3"' in k.to_string())
list(k.features())[0].snippet = {'text': 'Annother Snippet'}
self.assertFalse('maxLines' in k.to_string())
self.assertTrue('Annother Snippet' in k.to_string())
list(k.features())[0].snippet = 'Diffrent Snippet'
self.assertFalse('maxLines' in k.to_string())
self.assertTrue('Diffrent Snippet' in k.to_string())
def test_from_wrong_string(self):
doc = kml.KML()
self.assertRaises(TypeError, doc.from_string, '<xml></xml>')
def test_address(self):
doc = kml.Document()
doc.from_string("""
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2" id="pm-id">
<kml:name>pm-name</kml:name>
<kml:description>pm-description</kml:description>
<kml:visibility>1</kml:visibility>
<kml:address>1600 Amphitheatre Parkway, Mountain View, CA 94043, USA</kml:address>
</kml:Document>
""")
doc2 = kml.Document()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_phone_number(self):
doc = kml.Document()
doc.from_string("""
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2" id="pm-id">
<kml:name>pm-name</kml:name>
<kml:description>pm-description</kml:description>
<kml:visibility>1</kml:visibility>
<kml:phoneNumber>+1 234 567 8901</kml:phoneNumber>
</kml:Document>
""")
doc2 = kml.Document()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_groundoverlay(self):
doc = kml.KML()
doc.from_string(
"""
<kml xmlns="http://www.opengis.net/kml/2.2">
<Folder>
<name>Ground Overlays</name>
<description>Examples of ground overlays</description>
<GroundOverlay>
<name>Large-scale overlay on terrain</name>
<description>Overlay shows Mount Etna erupting
on July 13th, 2001.</description>
<Icon>
<href>http://developers.google.com/kml/documentation/images/etna.jpg</href>
</Icon>
<LatLonBox>
<north>37.91904192681665</north>
<south>37.46543388598137</south>
<east>15.35832653742206</east>
<west>14.60128369746704</west>
<rotation>-0.1556640799496235</rotation>
</LatLonBox>
</GroundOverlay>
</Folder>
</kml>
""")
doc2 = kml.KML()
doc2.from_string(doc.to_string())
self.assertEqual(doc.to_string(), doc2.to_string())
def test_linarring_placemark(self):
doc = kml.KML()
doc.from_string( """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<LinearRing>
<coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,0.0</coordinates>
</LinearRing>
</Placemark> </kml>""")
doc2 = kml.KML()
doc2.from_string(doc.to_string())
self.assertTrue(
isinstance(list(doc.features())[0].geometry, LinearRing))
self.assertEqual(doc.to_string(), doc2.to_string())
class StyleTestCase(unittest.TestCase):
def test_styleurl(self):
f = kml.Document()
f.styleUrl = '#somestyle'
self.assertEqual(f.styleUrl, '#somestyle')
self.assertTrue(isinstance(f._styleUrl, styles.StyleUrl))
s = styles.StyleUrl(config.NS, url='#otherstyle')
f.styleUrl = s
self.assertTrue(isinstance(f._styleUrl, styles.StyleUrl))
self.assertEqual(f.styleUrl, '#otherstyle')
f2 = kml.Document()
f2.from_string(f.to_string())
self.assertEqual(f.to_string(), f2.to_string())
def test_style(self):
lstyle = styles.LineStyle(color='red', width=2.0)
style = styles.Style(styles=[lstyle])
f = kml.Document(styles=[style])
f2 = kml.Document()
f2.from_string(f.to_string(prettyprint=True))
self.assertEqual(f.to_string(), f2.to_string())
def test_polystyle_fill(self):
style = styles.PolyStyle()
def test_polystyle_outline(self):
style = styles.PolyStyle()
class StyleUsageTestCase(unittest.TestCase):
def test_create_document_style(self):
style = styles.Style(styles=[styles.PolyStyle(color='7f000000')])
doc = kml.Document(styles=[style])
doc2 = kml.Document()
doc2.append_style(style)
expected = """
<kml:Document xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:visibility>1</kml:visibility>
<kml:Style>
<kml:PolyStyle>
<kml:color>7f000000</kml:color>
<kml:fill>1</kml:fill>
<kml:outline>1</kml:outline>
</kml:PolyStyle>
</kml:Style>
</kml:Document>
"""
doc3 = kml.Document()
doc3.from_string(expected)
self.assertEqual(doc.to_string(), doc2.to_string())
self.assertEqual(doc2.to_string(), doc3.to_string())
self.assertEqual(doc.to_string(), doc3.to_string())
def test_create_placemark_style(self):
style = styles.Style(styles=[styles.PolyStyle(color='7f000000')])
place = kml.Placemark(styles=[style])
place2 = kml.Placemark()
place2.append_style(style)
expected = """
<kml:Placemark xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:visibility>1</kml:visibility>
<kml:Style>
<kml:PolyStyle>
<kml:color>7f000000</kml:color>
<kml:fill>1</kml:fill>
<kml:outline>1</kml:outline>
</kml:PolyStyle>
</kml:Style>
</kml:Placemark>
"""
place3 = kml.Placemark()
place3.from_string(expected)
self.assertEqual(place.to_string(), place2.to_string())
self.assertEqual(place2.to_string(), place3.to_string())
self.assertEqual(place.to_string(), place3.to_string())
class StyleFromStringTestCase(unittest.TestCase):
def test_styleurl(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<styleUrl>#default</styleUrl>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertEqual(list(k.features())[0].styleUrl, '#default')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_balloonstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<Style id="exampleBalloonStyle">
<BalloonStyle>
<!-- a background color for the balloon -->
<bgColor>ffffffbb</bgColor>
<!-- styling of the balloon text -->
<textColor>ff000000</textColor>
<text><![CDATA[
<b><font color="#CC0000" size="+3">$[name]</font></b>
<br/><br/>
<font face="Courier">$[description]</font>
<br/><br/>
Extra text that will appear in the description balloon
<br/><br/>
<!-- insert the to/from hyperlinks -->
$[geDirections]
]]></text>
<!-- kml:displayModeEnum -->
<displayMode>default</displayMode>
</BalloonStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.BalloonStyle))
self.assertEqual(style.bgColor, 'ffffffbb')
self.assertEqual(style.textColor, 'ff000000')
self.assertEqual(style.displayMode, 'default')
self.assertTrue('$[geDirections]' in style.text)
self.assertTrue('$[description]' in style.text)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k2.to_string(), k.to_string())
def test_balloonstyle_old_color(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<Style id="exampleBalloonStyle">
<BalloonStyle>
<!-- a background color for the balloon -->
<color>ffffffbb</color>
</BalloonStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.BalloonStyle))
self.assertEqual(style.bgColor, 'ffffffbb')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k2.to_string(), k.to_string())
def test_labelstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.LabelStyle))
self.assertEqual(style.color, 'ff0000cc')
self.assertEqual(style.colorMode, None)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_iconstyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Style id="randomColorIcon">
<IconStyle>
<color>ff00ff00</color>
<colorMode>random</colorMode>
<scale>1.1</scale>
<heading>0</heading>
<Icon>
<href>http://maps.google.com/icon21.png</href>
</Icon>
</IconStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list((k.features()))), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.IconStyle))
self.assertEqual(style.color, 'ff00ff00')
self.assertEqual(style.scale, 1.1)
self.assertEqual(style.colorMode, 'random')
self.assertEqual(style.heading, 0.0)
self.assertEqual(style.icon_href, 'http://maps.google.com/icon21.png')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_linestyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>LineStyle.kml</name>
<open>1</open>
<Style id="linestyleExample">
<LineStyle>
<color>7f0000ff</color>
<width>4</width>
</LineStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.LineStyle))
self.assertEqual(style.color, '7f0000ff')
self.assertEqual(style.width, 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<color>ff0000cc</color>
<colorMode>random</colorMode>
</PolyStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.color, 'ff0000cc')
self.assertEqual(style.colorMode, 'random')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle_float_fill(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<fill>0.0</fill>
</PolyStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.fill, 0)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_polystyle_float_outline(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>PolygonStyle.kml</name>
<open>1</open>
<Style id="examplePolyStyle">
<PolyStyle>
<outline>0.0</outline>
</PolyStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
style = list(list(list(k.features())[0].styles())[0].styles())[0]
self.assertTrue(isinstance(style, styles.PolyStyle))
self.assertEqual(style.outline, 0)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_styles(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<!-- Begin Style Definitions -->
<Style id="myDefaultStyles">
<IconStyle>
<color>a1ff00ff</color>
<scale>1.399999976158142</scale>
<Icon>
<href>http://myserver.com/icon.jpg</href>
</Icon>
</IconStyle>
<LabelStyle>
<color>7fffaaff</color>
<scale>1.5</scale>
</LabelStyle>
<LineStyle>
<color>ff0000ff</color>
<width>15</width>
</LineStyle>
<PolyStyle>
<color>7f7faaaa</color>
<colorMode>random</colorMode>
</PolyStyle>
</Style>
<!-- End Style Definitions -->
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(list(list(k.features())[0].styles())[0], styles.Style))
style = list(list(list(k.features())[0].styles())[0].styles())
self.assertEqual(len(style), 4)
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_stylemapurl(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<styleUrl>#normalState</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#highlightState</styleUrl>
</Pair>
</StyleMap>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(
list(list(k.features())[0].styles())[0], styles.StyleMap))
sm = list(list(list(k.features())[0].styles()))[0]
self.assertTrue(isinstance(sm.normal, styles.StyleUrl))
self.assertEqual(sm.normal.url, '#normalState')
self.assertTrue(isinstance(sm.highlight, styles.StyleUrl))
self.assertEqual(sm.highlight.url, '#highlightState')
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_stylemapstyles(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
</Pair>
<Pair>
<key>highlight</key>
<Style id="examplePolyStyle">
<PolyStyle>
<color>ff0000cc</color>
<colorMode>random</colorMode>
</PolyStyle>
<LineStyle>
<color>ff0000ff</color>
<width>15</width>
</LineStyle>
</Style>
</Pair>
</StyleMap>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
self.assertTrue(
isinstance(
list(list(k.features())[0].styles())[0], styles.StyleMap))
sm = list(list(list(k.features())[0].styles()))[0]
self.assertTrue(isinstance(sm.normal, styles.Style))
self.assertEqual(len(list(sm.normal.styles())), 1)
self.assertTrue(
isinstance(list(sm.normal.styles())[0], styles.LabelStyle))
self.assertTrue(isinstance(sm.highlight, styles.Style))
self.assertTrue(isinstance(sm.highlight, styles.Style))
self.assertEqual(len(list(sm.highlight.styles())), 2)
self.assertTrue(
isinstance(list(sm.highlight.styles())[0], styles.LineStyle))
self.assertTrue(
isinstance(list(sm.highlight.styles())[1], styles.PolyStyle))
k2 = kml.KML()
k2.from_string(k.to_string())
self.assertEqual(k.to_string(), k2.to_string())
def test_get_style_by_url(self):
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Document.kml</name>
<open>1</open>
<Style id="exampleStyleDocument">
<LabelStyle>
<color>ff0000cc</color>
</LabelStyle>
</Style>
<StyleMap id="styleMapExample">
<Pair>
<key>normal</key>
<styleUrl>#normalState</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#highlightState</styleUrl>
</Pair>
</StyleMap>
<Style id="linestyleExample">
<LineStyle>
<color>7f0000ff</color>
<width>4</width>
</LineStyle>
</Style>
</Document>
</kml>"""
k = kml.KML()
k.from_string(doc)
self.assertEqual(len(list(k.features())), 1)
document = list(k.features())[0]
style = document.get_style_by_url(
'http://localhost:8080/somepath#exampleStyleDocument')
self.assertTrue(isinstance(list(style.styles())[0], styles.LabelStyle))
style = document.get_style_by_url('somepath#linestyleExample')
self.assertTrue(isinstance(list(style.styles())[0], styles.LineStyle))
style = document.get_style_by_url('#styleMapExample')
self.assertTrue(isinstance(style, styles.StyleMap))
class DateTimeTestCase(unittest.TestCase):
def test_timestamp(self):
now = datetime.datetime.now()
ts = kml.TimeStamp(timestamp=now)
self.assertEqual(ts.timestamp, [now, 'dateTime'])
self.assertTrue('TimeStamp>' in str(ts.to_string()))
self.assertTrue('when>' in str(ts.to_string()))
self.assertTrue(now.isoformat() in str(ts.to_string()))
y2k = datetime.date(2000, 1, 1)
ts = kml.TimeStamp(timestamp=y2k)
self.assertEqual(ts.timestamp, [y2k, 'date'])
self.assertTrue('2000-01-01' in str(ts.to_string()))
def test_timestamp_resolution(self):
now = datetime.datetime.now()
ts = kml.TimeStamp(timestamp=now)
self.assertTrue(now.isoformat() in str(ts.to_string()))
ts.timestamp[1] = 'date'
self.assertTrue(now.date().isoformat() in str(ts.to_string()))
self.assertFalse(now.isoformat() in str(ts.to_string()))
year = str(now.year)
ym = now.strftime('%Y-%m')
ts.timestamp[1] = 'gYearMonth'
self.assertTrue(ym in str(ts.to_string()))
self.assertFalse(now.date().isoformat() in str(ts.to_string()))
ts.timestamp[1] = 'gYear'
self.assertTrue(year in str(ts.to_string()))
self.assertFalse(ym in str(ts.to_string()))
ts.timestamp = None
self.assertRaises(TypeError, ts.to_string)
def test_timespan(self):
now = datetime.datetime.now()
y2k = datetime.datetime(2000, 1, 1)
ts = kml.TimeSpan(end=now, begin=y2k)
self.assertEqual(ts.end, [now, 'dateTime'])
self.assertEqual(ts.begin, [y2k, 'dateTime'])
self.assertTrue('TimeSpan>' in str(ts.to_string()))
self.assertTrue('begin>' in str(ts.to_string()))
self.assertTrue('end>' in str(ts.to_string()))
self.assertTrue(now.isoformat() in str(ts.to_string()))
self.assertTrue(y2k.isoformat() in str(ts.to_string()))
ts.end = None
self.assertFalse(now.isoformat() in str(ts.to_string()))
self.assertTrue(y2k.isoformat() in str(ts.to_string()))
ts.begin = None
self.assertRaises(ValueError, ts.to_string)
def test_feature_timestamp(self):
now = datetime.datetime.now()
f = kml.Document()
f.timeStamp = now
self.assertEqual(f.timeStamp, now)
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('TimeStamp>' in str(f.to_string()))
self.assertTrue('when>' in str(f.to_string()))
f.timeStamp = now.date()
self.assertTrue(now.date().isoformat() in str(f.to_string()))
self.assertFalse(now.isoformat() in str(f.to_string()))
f.timeStamp = None
self.assertFalse('TimeStamp>' in str(f.to_string()))
def test_feature_timespan(self):
now = datetime.datetime.now()
y2k = datetime.date(2000, 1, 1)
f = kml.Document()
f.begin = y2k
f.end = now
self.assertEqual(f.begin, y2k)
self.assertEqual(f.end, now)
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
f.end = None
self.assertFalse(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertFalse('end>' in str(f.to_string()))
f.begin = None
self.assertFalse('TimeSpan>' in str(f.to_string()))
def test_feature_timespan_stamp(self):
now = datetime.datetime.now()
y2k = datetime.date(2000, 1, 1)
f = kml.Document()
f.begin = y2k
f.end = now
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertTrue('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
self.assertFalse('TimeStamp>' in str(f.to_string()))
self.assertFalse('when>' in str(f.to_string()))
f.timeStamp = now
self.assertTrue(now.isoformat() in str(f.to_string()))
self.assertTrue('TimeStamp>' in str(f.to_string()))
self.assertTrue('when>' in str(f.to_string()))
self.assertFalse('2000-01-01' in str(f.to_string()))
self.assertFalse('TimeSpan>' in str(f.to_string()))
self.assertFalse('begin>' in str(f.to_string()))
self.assertFalse('end>' in str(f.to_string()))
f.end = y2k
self.assertFalse(now.isoformat() in str(f.to_string()))
self.assertTrue('2000-01-01' in str(f.to_string()))
self.assertTrue('TimeSpan>' in str(f.to_string()))
self.assertFalse('begin>' in str(f.to_string()))
self.assertTrue('end>' in str(f.to_string()))
self.assertFalse('TimeStamp>' in str(f.to_string()))
self.assertFalse('when>' in str(f.to_string()))
ts = kml.TimeStamp(timestamp=now)
f._time_stamp = ts
self.assertRaises(ValueError, f.to_string)
def test_read_timestamp(self):
ts = kml.TimeStamp(ns='')
doc = """
<TimeStamp>
<when>1997</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYear')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 1, 1, 0, 0))
doc = """
<TimeStamp>
<when>1997-07</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYearMonth')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 7, 1, 0, 0))
doc = """
<TimeStamp>
<when>199808</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'gYearMonth')
self.assertEqual(ts.timestamp[0], datetime.datetime(1998, 8, 1, 0, 0))
doc = """
<TimeStamp>
<when>1997-07-16</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'date')
self.assertEqual(ts.timestamp[0], datetime.datetime(1997, 7, 16, 0, 0))
doc = """
<TimeStamp>
<when>1997-07-16T07:30:15Z</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'dateTime')
self.assertEqual(ts.timestamp[0], datetime.datetime(
1997, 7, 16, 7, 30, 15,
tzinfo=tzutc()))
doc = """
<TimeStamp>
<when>1997-07-16T10:30:15+03:00</when>
</TimeStamp>
"""
ts.from_string(doc)
self.assertEqual(ts.timestamp[1], 'dateTime')
self.assertEqual(ts.timestamp[0], datetime.datetime(
1997, 7, 16, 10, 30, 15,
tzinfo=tzoffset(None, 10800)))
def test_read_timespan(self):
ts = kml.TimeSpan(ns='')
doc = """
<TimeSpan>
<begin>1876-08-01</begin>
<end>1997-07-16T07:30:15Z</end>
</TimeSpan>
"""
ts.from_string(doc)
self.assertEqual(ts.begin[1], 'date')
self.assertEqual(ts.begin[0], datetime.datetime(1876, 8, 1, 0, 0))
self.assertEqual(ts.end[1], 'dateTime')
self.assertEqual(ts.end[0], datetime.datetime(
1997, 7, 16, 7, 30, 15,
tzinfo=tzutc()))
def test_featurefromstring(self):
d = kml.Document(ns='')
doc = """<Document>
<name>Document.kml</name>
<open>1</open>
<TimeStamp>
<when>1997-07-16T10:30:15+03:00</when>
</TimeStamp>
<TimeSpan>
<begin>1876-08-01</begin>
<end>1997-07-16T07:30:15Z</end>
</TimeSpan>
</Document>"""
d.from_string(doc)
class AtomTestCase(unittest.TestCase):
def test_author(self):
a = atom.Author(name="Christian Ledermann")
self.assertEqual(a.name, "Christian Ledermann")
a.uri = 'http://iwlearn.net'
a.email = 'christian@gmail.com'
self.assertTrue("Christian Ledermann" in str(a.to_string()))
self.assertTrue('http://iwlearn.net' in str(a.to_string()))
self.assertTrue('christian@gmail.com' in str(a.to_string()))
self.assertTrue('name>' in str(a.to_string()))
self.assertTrue('uri>' in str(a.to_string()))
self.assertTrue('email>' in str(a.to_string()))
a.email = 'christian'
self.assertFalse('email>' in str(a.to_string()))
a2 = atom.Author()
a2.from_string(a.to_string())
self.assertEqual(a.to_string(), a2.to_string())
def test_link(self):
l = atom.Link(href="http://localhost/", rel="alternate")
self.assertEqual(l.href, "http://localhost/")
self.assertEqual(l.rel, "alternate")
l.title = "Title"
l.type = "text/html"
l.hreflang = 'en'
l.length = "4096"
self.assertTrue('href="http://localhost/"' in str(l.to_string()))
self.assertTrue('rel="alternate"' in str(l.to_string()))
self.assertTrue('title="Title"' in str(l.to_string()))
self.assertTrue('hreflang="en"' in str(l.to_string()))
self.assertTrue('type="text/html"' in str(l.to_string()))
self.assertTrue('length="4096"' in str(l.to_string()))
self.assertTrue('link' in str(l.to_string()))
self.assertTrue('="http://www.w3.org/2005/Atom"' in str(l.to_string()))
l2 = atom.Link()
l2.from_string(l.to_string())
self.assertEqual(l.to_string(), l2.to_string())
l.href = None
self.assertRaises(ValueError, l.to_string)
class SetGeometryTestCase(unittest.TestCase):
def test_altitude_mode(self):
geom = Geometry()
geom.geometry = Point(0, 1)
self.assertEqual(geom.altitude_mode, None)
self.assertFalse('altitudeMode' in str(geom.to_string()))
geom.altitude_mode = 'unknown'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'clampToSeaFloor'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'relativeToSeaFloor'
self.assertRaises(AssertionError, geom.to_string)
geom.altitude_mode = 'clampToGround'
self.assertFalse('altitudeMode' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertTrue(
'altitudeMode>relativeToGround</' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertTrue('altitudeMode>absolute</' in str(geom.to_string()))
def test_extrude(self):
geom = Geometry()
self.assertEqual(geom.extrude, False)
geom.geometry = Point(0, 1)
geom.extrude = False
self.assertFalse('extrude' in str(geom.to_string()))
geom.extrude = True
geom.altitude_mode = 'clampToGround'
self.assertFalse('extrude' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertTrue('extrude>1</' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertTrue('extrude>1</' in str(geom.to_string()))
def test_tesselate(self):
geom = Geometry()
self.assertEqual(geom.tessellate, False)
geom.geometry = LineString([(0, 0), (1, 1)])
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'clampToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.tessellate = True
geom.altitude_mode = None
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'relativeToGround'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'absolute'
self.assertFalse('tessellate' in str(geom.to_string()))
geom.altitude_mode = 'clampToGround'
self.assertTrue('tessellate>1</' in str(geom.to_string()))
geom.geometry = Point(0, 1)
self.assertFalse('tessellate' in str(geom.to_string()))
geom.geometry = Polygon([(0, 0), (1, 0), (1, 1), (0, 0)])
self.assertFalse('tessellate' in str(geom.to_string()))
def test_point(self):
p = Point(0, 1)
g = Geometry(geometry=p)
self.assertEqual(g.geometry, p)
g = Geometry(geometry=p.__geo_interface__)
self.assertEqual(g.geometry.__geo_interface__, p.__geo_interface__)
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
def test_linestring(self):
l = LineString([(0, 0), (1, 1)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,1.000000</' in
str(g.to_string()))
g2 = Geometry()
g2.from_string(g.to_string())
self.assertEqual(g.to_string(), g2.to_string())
def test_linearring(self):
l = LinearRing([(0, 0), (1, 0), (1, 1), (0, 0)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
def test_polygon(self):
l = Polygon([(0, 0), (1, 0), (1, 1), (0, 0)])
g = Geometry(geometry=l)
self.assertEqual(g.geometry, l)
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertFalse('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
p = Polygon(
[(-1, -1), (2, -1), (2, 2), (-1, -1)], [[(0, 0), (1, 0), (1, 1),
(0, 0)]], )
g = Geometry(geometry=p)
self.assertEqual(g.geometry, p)
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertTrue('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</'
in str(g.to_string()))
def test_multipoint(self):
p0 = Point(0, 1)
p1 = Point(1, 1)
g = Geometry(geometry=MultiPoint([p0, p1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
self.assertTrue(
'coordinates>1.000000,1.000000</' in str(g.to_string()))
def test_multilinestring(self):
l0 = LineString([(0, 0), (1, 0)])
l1 = LineString([(0, 1), (1, 1)])
g = Geometry(geometry=MultiLineString([l0, l1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000</' in
str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000 1.000000,1.000000</' in
str(g.to_string()))
def test_multipolygon(self):
p0 = Polygon(
[(-1, -1), (2, -1), (2, 2), (-1, -1)], [[(0, 0), (1, 0), (1, 1),
(0, 0)]])
p1 = Polygon([(3, 0), (4, 0), (4, 1), (3, 0)])
g = Geometry(geometry=MultiPolygon([p0, p1]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertTrue('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</'
in str(g.to_string()))
self.assertTrue(
'coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</'
in str(g.to_string()))
def test_geometrycollection(self):
po = Polygon([(3, 0), (4, 0), (4, 1), (3, 0)])
lr = LinearRing([(0, -1), (1, -1), (1, 1), (0, -1)])
ls = LineString([(0, 0), (1, 1)])
p = Point(0, 1)
g = Geometry(geometry=GeometryCollection([po, p, ls, lr]))
self.assertTrue('MultiGeometry' in str(g.to_string()))
self.assertTrue('Polygon' in str(g.to_string()))
self.assertTrue('outerBoundaryIs' in str(g.to_string()))
self.assertFalse('innerBoundaryIs' in str(g.to_string()))
self.assertTrue('LinearRing' in str(g.to_string()))
self.assertTrue(
'coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</'
in str(g.to_string()))
self.assertTrue('LineString' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,0.000000 1.000000,1.000000</' in
str(g.to_string()))
self.assertTrue('Point' in str(g.to_string()))
self.assertTrue(
'coordinates>0.000000,1.000000</' in str(g.to_string()))
class GetGeometryTestCase(unittest.TestCase):
def test_altitude_mode(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:altitudeMode>clampToGround</kml:altitudeMode>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.altitude_mode, None)
g.from_string(doc)
self.assertEqual(g.altitude_mode, 'clampToGround')
def test_extrude(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:extrude>1</kml:extrude>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.extrude, False)
g.from_string(doc)
self.assertEqual(g.extrude, True)
def test_tesselate(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
<kml:tessellate>1</kml:tessellate>
</kml:Point>"""
g = Geometry()
self.assertEqual(g.tessellate, False)
g.from_string(doc)
self.assertEqual(g.tessellate, True)
def test_point(self):
doc = """<kml:Point xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__,
{'type': 'Point',
'coordinates': (0.0, 1.0)})
def test_linestring(self):
doc = """<kml:LineString xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,0.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__,
{'type': 'LineString',
'coordinates': ((0.0, 0.0), (1.0, 1.0))})
def test_linearring(self):
doc = """<kml:LinearRing xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'LinearRing',
'coordinates': ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0))
})
def test_polygon(self):
doc = """<kml:Polygon xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'Polygon',
'coordinates': ((
(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)
), )
})
doc = """<kml:Polygon xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
<kml:innerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:innerBoundaryIs>
</kml:Polygon>
"""
g.from_string(doc)
self.assertEqual(
g.geometry.__geo_interface__, {
'type': 'Polygon',
'coordinates': (
((-1.0, -1.0), (2.0, -1.0), (2.0, 2.0),
(-1.0, -1.0)), ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0),
(0.0, 0.0)),
)
})
def test_multipoint(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Point>
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>
<kml:Point>
<kml:coordinates>1.000000,1.000000</kml:coordinates>
</kml:Point>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_multilinestring(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:LineString>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000</kml:coordinates>
</kml:LineString>
<kml:LineString>
<kml:coordinates>0.000000,1.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_multipolygon(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>-1.000000,-1.000000 2.000000,-1.000000 2.000000,2.000000 -1.000000,-1.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
<kml:innerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>0.000000,0.000000 1.000000,0.000000 1.000000,1.000000 0.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:innerBoundaryIs>
</kml:Polygon>
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>3.000000,0.000000 4.000000,0.000000 4.000000,1.000000 3.000000,0.000000</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
def test_geometrycollection(self):
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:Polygon>
<kml:outerBoundaryIs>
<kml:LinearRing>
<kml:coordinates>3,0 4,0 4,1 3,0</kml:coordinates>
</kml:LinearRing>
</kml:outerBoundaryIs>
</kml:Polygon>
<kml:Point>
<kml:coordinates>0.000000,1.000000</kml:coordinates>
</kml:Point>
<kml:LineString>
<kml:coordinates>0.000000,0.000000 1.000000,1.000000</kml:coordinates>
</kml:LineString>
<kml:LinearRing>
<kml:coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,1.0 0.0,0.0</kml:coordinates>
</kml:LinearRing>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 4)
doc = """
<kml:MultiGeometry xmlns:kml="http://www.opengis.net/kml/2.2">
<kml:LinearRing>
<kml:coordinates>3.0,0.0 4.0,0.0 4.0,1.0 3.0,0.0</kml:coordinates>
</kml:LinearRing>
<kml:LinearRing>
<kml:coordinates>0.0,0.0 1.0,0.0 1.0,1.0 0.0,0.0</kml:coordinates>
</kml:LinearRing>
</kml:MultiGeometry>
"""
g = Geometry()
g.from_string(doc)
self.assertEqual(len(g.geometry), 2)
self.assertEqual(g.geometry.geom_type, 'GeometryCollection')
class Force3DTestCase(unittest.TestCase):
def setUp(self):
config.FORCE3D = False
def tearDown(self):
config.FORCE3D = False
def test3d(self):
config.FORCE3D = True
ns = ''
p2 = kml.Placemark(ns, 'id', 'name', 'description')
p2.geometry = Polygon([(0, 0), (1, 1), (1, 0)])
p3 = kml.Placemark(ns, 'id', 'name', 'description')
p3.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 0)])
self.assertEqual(p2.to_string(), p3.to_string())
def testno3d(self):
config.FORCE3D = False
ns = ''
p2 = kml.Placemark(ns, 'id', 'name', 'description')
p2.geometry = Polygon([(0, 0), (1, 1), (1, 0)])
p3 = kml.Placemark(ns, 'id', 'name', 'description')
p3.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 0)])
self.assertNotEqual(p2.to_string(), p3.to_string())
class BaseFeatureTestCase(unittest.TestCase):
def test_address_string(self):
f = kml._Feature()
address = '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
f.address = address
self.assertEqual(f.address, address)
def test_address_none(self):
f = kml._Feature()
f.address = None
self.assertEqual(f.address, None)
def test_address_value_error(self):
f = kml._Feature()
with self.assertRaises(ValueError):
f.address = 123
def test_phone_number_string(self):
f = kml._Feature()
f.phoneNumber = '+1-234-567-8901'
self.assertEqual(f.phoneNumber, '+1-234-567-8901')
def test_phone_number_none(self):
f = kml._Feature()
f.phoneNumber = None
self.assertEqual(f.phoneNumber, None)
def test_phone_number_value_error(self):
f = kml._Feature()
with self.assertRaises(ValueError):
f.phoneNumber = 123
class BaseOverlayTestCase(unittest.TestCase):
def test_color_string(self):
o = kml._Overlay(name='An Overlay')
o.color = '00010203'
self.assertEqual(o.color, '00010203')
def test_color_none(self):
o = kml._Overlay(name='An Overlay')
o.color = '00010203'
self.assertEqual(o.color, '00010203')
o.color = None
self.assertEqual(o.color, None)
def test_color_value_error(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.color = object()
def test_draw_order_string(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = '1'
self.assertEqual(o.drawOrder, '1')
def test_draw_order_int(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = 1
self.assertEqual(o.drawOrder, '1')
def test_draw_order_none(self):
o = kml._Overlay(name='An Overlay')
o.drawOrder = '1'
self.assertEqual(o.drawOrder, '1')
o.drawOrder = None
self.assertEqual(o.drawOrder, None)
def test_draw_order_value_error(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.drawOrder = object()
def test_icon_without_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = 'http://example.com/'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_open_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_close_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = 'http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_with_tag(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
def test_icon_to_none(self):
o = kml._Overlay(name='An Overlay')
o.icon = '<href>http://example.com/</href>'
self.assertEqual(o.icon, '<href>http://example.com/</href>')
o.icon = None
self.assertEqual(o.icon, None)
def test_icon_raise_exception(self):
o = kml._Overlay(name='An Overlay')
with self.assertRaises(ValueError):
o.icon = 12345
class GroundOverlayTestCase(unittest.TestCase):
def setUp(self):
self.g = kml.GroundOverlay()
def test_altitude_int(self):
self.g.altitude = 123
self.assertEqual(self.g.altitude, '123')
def test_altitude_float(self):
self.g.altitude = 123.4
self.assertEqual(self.g.altitude, '123.4')
def test_altitude_string(self):
self.g.altitude = '123'
self.assertEqual(self.g.altitude, '123')
def test_altitude_value_error(self):
with self.assertRaises(ValueError):
self.g.altitude = object()
def test_altitude_none(self):
self.g.altitude = '123'
self.assertEqual(self.g.altitude, '123')
self.g.altitude = None
self.assertEqual(self.g.altitude, None)
def test_altitude_mode_default(self):
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_error(self):
self.g.altitudeMode = ''
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_clamp(self):
self.g.altitudeMode = 'clampToGround'
self.assertEqual(self.g.altitudeMode, 'clampToGround')
def test_altitude_mode_absolute(self):
self.g.altitudeMode = 'absolute'
self.assertEqual(self.g.altitudeMode, 'absolute')
def test_latlonbox_function(self):
self.g.latLonBox(10, 20, 30, 40, 50)
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_string(self):
self.g.north = '10'
self.g.south = '20'
self.g.east = '30'
self.g.west = '40'
self.g.rotation = '50'
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_int(self):
self.g.north = 10
self.g.south = 20
self.g.east = 30
self.g.west = 40
self.g.rotation = 50
self.assertEqual(self.g.north, '10')
self.assertEqual(self.g.south, '20')
self.assertEqual(self.g.east, '30')
self.assertEqual(self.g.west, '40')
self.assertEqual(self.g.rotation, '50')
def test_latlonbox_float(self):
self.g.north = 10.0
self.g.south = 20.0
self.g.east = 30.0
self.g.west = 40.0
self.g.rotation = 50.0
self.assertEqual(self.g.north, '10.0')
self.assertEqual(self.g.south, '20.0')
self.assertEqual(self.g.east, '30.0')
self.assertEqual(self.g.west, '40.0')
self.assertEqual(self.g.rotation, '50.0')
def test_latlonbox_value_error(self):
with self.assertRaises(ValueError):
self.g.north = object()
with self.assertRaises(ValueError):
self.g.south = object()
with self.assertRaises(ValueError):
self.g.east = object()
with self.assertRaises(ValueError):
self.g.west = object()
with self.assertRaises(ValueError):
self.g.rotation = object()
self.assertEqual(self.g.north, None)
self.assertEqual(self.g.south, None)
self.assertEqual(self.g.east, None)
self.assertEqual(self.g.west, None)
self.assertEqual(self.g.rotation, None)
def test_latlonbox_empty_string(self):
self.g.north = ''
self.g.south = ''
self.g.east = ''
self.g.west = ''
self.g.rotation = ''
self.assertEqual(self.g.north, '')
self.assertEqual(self.g.south, '')
self.assertEqual(self.g.east, '')
self.assertEqual(self.g.west, '')
self.assertEqual(self.g.rotation, '')
def test_latlonbox_none(self):
self.g.north = None
self.g.south = None
self.g.east = None
self.g.west = None
self.g.rotation = None
self.assertEqual(self.g.north, None)
self.assertEqual(self.g.south, None)
self.assertEqual(self.g.east, None)
self.assertEqual(self.g.west, None)
self.assertEqual(self.g.rotation, None)
class GroundOverlayStringTestCase(unittest.TestCase):
def test_default_to_string(self):
g = kml.GroundOverlay()
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_to_string(self):
g = kml.GroundOverlay()
g.icon = 'http://example.com'
g.drawOrder = 1
g.color = '00010203'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:color>00010203</kml:color>'
'<kml:drawOrder>1</kml:drawOrder>'
'<kml:icon><href>http://example.com</href></kml:icon>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_int(self):
g = kml.GroundOverlay()
g.altitude = 123
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_float(self):
g = kml.GroundOverlay()
g.altitude = 123.4
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_from_string(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_absolute(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 'absolute'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>absolute</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_unknown_string(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 'unknown string'
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_altitude_mode_value(self):
g = kml.GroundOverlay()
g.altitude = '123.4'
g.altitudeMode = 1234
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:altitude>123.4</kml:altitude>'
'<kml:altitudeMode>clampToGround</kml:altitudeMode>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_no_rotation(self):
g = kml.GroundOverlay()
g.latLonBox(10, 20, 30, 40)
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>0</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_rotation(self):
g = kml.GroundOverlay()
g.latLonBox(10, 20, 30, 40, 50)
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>50</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_latlonbox_nswer(self):
g = kml.GroundOverlay()
g.north = 10
g.south = 20
g.east = 30
g.west = 40
g.rotation = 50
expected = kml.GroundOverlay()
expected.from_string(
'<kml:GroundOverlay xmlns:kml="http://www.opengis.net/kml/2.2">'
'<kml:visibility>1</kml:visibility>'
'<kml:latLonBox>'
'<kml:north>10</kml:north>'
'<kml:south>20</kml:south>'
'<kml:east>30</kml:east>'
'<kml:west>40</kml:west>'
'<kml:rotation>50</kml:rotation>'
'</kml:latLonBox>'
'</kml:GroundOverlay>')
self.assertEqual(g.to_string(), expected.to_string())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(BaseClassesTestCase))
suite.addTest(unittest.makeSuite(BuildKmlTestCase))
suite.addTest(unittest.makeSuite(KmlFromStringTestCase))
suite.addTest(unittest.makeSuite(StyleTestCase))
suite.addTest(unittest.makeSuite(StyleFromStringTestCase))
suite.addTest(unittest.makeSuite(DateTimeTestCase))
suite.addTest(unittest.makeSuite(AtomTestCase))
suite.addTest(unittest.makeSuite(SetGeometryTestCase))
suite.addTest(unittest.makeSuite(GetGeometryTestCase))
suite.addTest(unittest.makeSuite(Force3DTestCase))
suite.addTest(unittest.makeSuite(BaseOverlayTestCase))
suite.addTest(unittest.makeSuite(GroundOverlayTestCase))
return suite
if __name__ == '__main__':
unittest.main()
| true | true |
f71b8c248dafde29a7c3bf37462e5c2f5296a920 | 461 | py | Python | pyapi/utils/db.py | dockerian/py-api | 777db7d5dacf3ecf29a991f50d2ac78bb5bef66a | [
"Apache-2.0"
] | null | null | null | pyapi/utils/db.py | dockerian/py-api | 777db7d5dacf3ecf29a991f50d2ac78bb5bef66a | [
"Apache-2.0"
] | 6 | 2019-12-26T16:51:55.000Z | 2022-03-21T22:16:45.000Z | pyapi/utils/db.py | dockerian/pyapi | 777db7d5dacf3ecf29a991f50d2ac78bb5bef66a | [
"Apache-2.0"
] | null | null | null | """
# db module - database adapter functions
"""
from sqlalchemy import DateTime, TypeDecorator
# pylint: disable=abstract-method
class DateTimeUtc(TypeDecorator):
'''
Results returned as offset-aware datetimes.
'''
impl = DateTime
# pylint: disable=unused-argument
def process_result_value(self, value, dialect):
"""
set UTC time zone with processing value
"""
return value.replace(tzinfo=pytz.utc)
| 20.954545 | 51 | 0.668113 |
from sqlalchemy import DateTime, TypeDecorator
class DateTimeUtc(TypeDecorator):
impl = DateTime
def process_result_value(self, value, dialect):
return value.replace(tzinfo=pytz.utc)
| true | true |
f71b8c325f2c4b1fda3cadbcc6909025b1010728 | 2,157 | py | Python | flask_rebar/swagger_generation/swagger_words.py | jsonau/flask-rebar | 22b82596e60bcb537c69dba03ed7155176a9aca1 | [
"MIT"
] | null | null | null | flask_rebar/swagger_generation/swagger_words.py | jsonau/flask-rebar | 22b82596e60bcb537c69dba03ed7155176a9aca1 | [
"MIT"
] | null | null | null | flask_rebar/swagger_generation/swagger_words.py | jsonau/flask-rebar | 22b82596e60bcb537c69dba03ed7155176a9aca1 | [
"MIT"
] | null | null | null | """
Swagger Words
~~~~~~~~~~~~~
Python friendly aliases to reserved Swagger words.
:copyright: Copyright 2018 PlanGrid, Inc., see AUTHORS.
:license: MIT, see LICENSE for details.
"""
from __future__ import unicode_literals
additional_properties = "additionalProperties"
all_of = "allOf"
allow_empty_value = "allowEmptyValue"
any_of = "anyOf"
api_key = "apiKey"
array = "array"
basic = "basic"
binary = "binary"
body = "body"
boolean = "boolean"
byte = "byte"
collection_format = "collectionFormat"
components = "components"
consumes = "consumes"
content = "content"
csv = "csv"
date = "date"
date_time = "date-time"
default = "default"
definitions = "definitions"
description = "description"
double = "double"
enum = "enum"
example = "example"
external_docs = "externalDocs"
exclusive_maximum = "exclusiveMaximum"
exclusive_minimum = "exclusiveMinimum"
explode = "explode"
float_ = "float"
form = "form"
format_ = "format"
header = "header"
host = "host"
in_ = "in"
info = "info"
integer = "integer"
int32 = "int32"
int64 = "int64"
items = "items"
max_items = "maxItems"
max_length = "maxLength"
max_properties = "maxProperties"
maximum = "maximum"
min_items = "minItems"
min_length = "minLength"
min_properties = "minProperties"
minimum = "minimum"
multi = "multi"
multiple_of = "multipleOf"
name = "name"
null = "null"
nullable = "x-nullable"
number = "number"
oauth2 = "oauth2"
object_ = "object"
one_of = "oneOf"
openapi = "openapi"
operation_id = "operationId"
parameters = "parameters"
password = "password"
path = "path"
paths = "paths"
pattern = "pattern"
produces = "produces"
properties = "properties"
query = "query"
ref = "$ref"
request_body = "requestBody"
required = "required"
responses = "responses"
schema = "schema"
schemas = "schemas"
schemes = "schemes"
security = "security"
security_definitions = "securityDefinitions"
security_schemes = "securitySchemes"
servers = "servers"
simple = "simple"
string = "string"
style = "style"
summary = "summary"
swagger = "swagger"
tags = "tags"
title = "title"
type_ = "type"
unique_items = "uniqueItems"
url = "url"
uuid = "uuid"
variables = "variables"
version = "version"
| 21.147059 | 59 | 0.710246 | from __future__ import unicode_literals
additional_properties = "additionalProperties"
all_of = "allOf"
allow_empty_value = "allowEmptyValue"
any_of = "anyOf"
api_key = "apiKey"
array = "array"
basic = "basic"
binary = "binary"
body = "body"
boolean = "boolean"
byte = "byte"
collection_format = "collectionFormat"
components = "components"
consumes = "consumes"
content = "content"
csv = "csv"
date = "date"
date_time = "date-time"
default = "default"
definitions = "definitions"
description = "description"
double = "double"
enum = "enum"
example = "example"
external_docs = "externalDocs"
exclusive_maximum = "exclusiveMaximum"
exclusive_minimum = "exclusiveMinimum"
explode = "explode"
float_ = "float"
form = "form"
format_ = "format"
header = "header"
host = "host"
in_ = "in"
info = "info"
integer = "integer"
int32 = "int32"
int64 = "int64"
items = "items"
max_items = "maxItems"
max_length = "maxLength"
max_properties = "maxProperties"
maximum = "maximum"
min_items = "minItems"
min_length = "minLength"
min_properties = "minProperties"
minimum = "minimum"
multi = "multi"
multiple_of = "multipleOf"
name = "name"
null = "null"
nullable = "x-nullable"
number = "number"
oauth2 = "oauth2"
object_ = "object"
one_of = "oneOf"
openapi = "openapi"
operation_id = "operationId"
parameters = "parameters"
password = "password"
path = "path"
paths = "paths"
pattern = "pattern"
produces = "produces"
properties = "properties"
query = "query"
ref = "$ref"
request_body = "requestBody"
required = "required"
responses = "responses"
schema = "schema"
schemas = "schemas"
schemes = "schemes"
security = "security"
security_definitions = "securityDefinitions"
security_schemes = "securitySchemes"
servers = "servers"
simple = "simple"
string = "string"
style = "style"
summary = "summary"
swagger = "swagger"
tags = "tags"
title = "title"
type_ = "type"
unique_items = "uniqueItems"
url = "url"
uuid = "uuid"
variables = "variables"
version = "version"
| true | true |
f71b8c4522567898a2c8dbed743a740b05b28ad7 | 1,035 | py | Python | oslo_ovsdb_frontend/impl/native/helpers.py | salv-orlando/oslo_ovsdb_frontend | 07845187467a9e8ad00f02f597e0e1277f28c637 | [
"Apache-2.0"
] | null | null | null | oslo_ovsdb_frontend/impl/native/helpers.py | salv-orlando/oslo_ovsdb_frontend | 07845187467a9e8ad00f02f597e0e1277f28c637 | [
"Apache-2.0"
] | null | null | null | oslo_ovsdb_frontend/impl/native/helpers.py | salv-orlando/oslo_ovsdb_frontend | 07845187467a9e8ad00f02f597e0e1277f28c637 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2015 Red Hat, 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.
def _connection_to_manager_uri(conn_uri):
proto, addr = conn_uri.split(':', 1)
if ':' in addr:
ip, port = addr.split(':', 1)
return 'p%s:%s:%s' % (proto, port, ip)
else:
return 'p%s:%s' % (proto, addr)
def enable_connection_uri(conn_uri, execute_func):
manager_uri = _connection_to_manager_uri(conn_uri)
execute_func(['ovs-vsctl', 'set-manager', manager_uri], run_as_root=True)
| 36.964286 | 78 | 0.686957 |
def _connection_to_manager_uri(conn_uri):
proto, addr = conn_uri.split(':', 1)
if ':' in addr:
ip, port = addr.split(':', 1)
return 'p%s:%s:%s' % (proto, port, ip)
else:
return 'p%s:%s' % (proto, addr)
def enable_connection_uri(conn_uri, execute_func):
manager_uri = _connection_to_manager_uri(conn_uri)
execute_func(['ovs-vsctl', 'set-manager', manager_uri], run_as_root=True)
| true | true |
f71b8d9b0f6513f05ab15b6e9fc0dbe880661dcb | 940 | py | Python | rapidenv/misc/set_activate_alias.py | innoviz-sw-infra/rapid-env | acc5e1e461af42b5fbb7024c0b79d4315c206fe2 | [
"MIT"
] | 1 | 2021-02-15T20:55:49.000Z | 2021-02-15T20:55:49.000Z | rapidenv/misc/set_activate_alias.py | innoviz-sw-infra/rapid-env | acc5e1e461af42b5fbb7024c0b79d4315c206fe2 | [
"MIT"
] | null | null | null | rapidenv/misc/set_activate_alias.py | innoviz-sw-infra/rapid-env | acc5e1e461af42b5fbb7024c0b79d4315c206fe2 | [
"MIT"
] | null | null | null | import sys
from pathlib import Path
def mainwin32():
if len(sys.argv) < 2:
print(f'to use run: python set_activate_alias.py $profile')
return
profile = sys.argv[1]
profile = Path(profile)
# makr parent directory if not exist
if not profile.parent.exists():
profile.parent.mkdir(parents=True)
# make file if not exist
if not profile.exists():
with open(profile, "a") as f:
f.write("")
with open(profile, 'r') as f:
txt = f.read()
insert = r"Set-Alias -Name activate -Value .\venv\Scripts\activate"
if txt.find(insert) != -1:
print(f'alias already set in "{profile}".')
return
# write to file
with open(profile, "a") as f:
f.write(insert + "\n")
def main():
if sys.platform == "win32":
mainwin32()
else:
print("plafrom not supported")
if __name__ == "__main__":
main() | 22.926829 | 71 | 0.575532 | import sys
from pathlib import Path
def mainwin32():
if len(sys.argv) < 2:
print(f'to use run: python set_activate_alias.py $profile')
return
profile = sys.argv[1]
profile = Path(profile)
if not profile.parent.exists():
profile.parent.mkdir(parents=True)
if not profile.exists():
with open(profile, "a") as f:
f.write("")
with open(profile, 'r') as f:
txt = f.read()
insert = r"Set-Alias -Name activate -Value .\venv\Scripts\activate"
if txt.find(insert) != -1:
print(f'alias already set in "{profile}".')
return
with open(profile, "a") as f:
f.write(insert + "\n")
def main():
if sys.platform == "win32":
mainwin32()
else:
print("plafrom not supported")
if __name__ == "__main__":
main() | true | true |
f71b8dec12d6719d1ccd4adbb31f7a450c33383c | 1,268 | py | Python | apps/accounts/forms.py | cloudartisan/dojomaster | 9d5efa0345c659636f8d8b556302d0d7bb2055a8 | [
"MIT"
] | 1 | 2019-02-21T14:47:31.000Z | 2019-02-21T14:47:31.000Z | apps/accounts/forms.py | cloudartisan/dojomaster | 9d5efa0345c659636f8d8b556302d0d7bb2055a8 | [
"MIT"
] | null | null | null | apps/accounts/forms.py | cloudartisan/dojomaster | 9d5efa0345c659636f8d8b556302d0d7bb2055a8 | [
"MIT"
] | null | null | null | from django import forms
from .models import UserAccount
class UserCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = UserAccount
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on the user.
"""
class Meta:
model = UserAccount
fields = ()
| 29.488372 | 90 | 0.662461 | from django import forms
from .models import UserAccount
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = UserAccount
fields = ('email',)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
class Meta:
model = UserAccount
fields = ()
| true | true |
f71b8eacdcd41ec7c42144254a210d3c2c2d6f9a | 568 | py | Python | ahrs/filters/__init__.py | ethan-jiang-1/ahrs | e1725267b0009a8a573f99dbf8d06e8481407ab6 | [
"MIT"
] | 184 | 2019-09-06T07:58:52.000Z | 2022-03-31T04:27:09.000Z | ahrs/filters/__init__.py | geoKinga/ahrs | 87f9210cfcf6c545d86ae8588a93f012020164ee | [
"MIT"
] | 48 | 2019-11-13T15:42:46.000Z | 2022-03-31T23:53:53.000Z | ahrs/filters/__init__.py | geoKinga/ahrs | 87f9210cfcf6c545d86ae8588a93f012020164ee | [
"MIT"
] | 34 | 2019-12-19T16:22:00.000Z | 2022-03-14T09:51:50.000Z | # -*- coding: utf-8 -*-
"""
Attitude Estimators
===================
These are the most common attitude filters.
"""
from .angular import AngularRate
from .aqua import AQUA
from .complementary import Complementary
from .davenport import Davenport
from .ekf import EKF
from .famc import FAMC
from .flae import FLAE
from .fourati import Fourati
from .fqa import FQA
from .tilt import Tilt
from .madgwick import Madgwick
from .mahony import Mahony
from .oleq import OLEQ
from .quest import QUEST
from .roleq import ROLEQ
from .saam import SAAM
from .triad import TRIAD
| 21.037037 | 43 | 0.753521 |
from .angular import AngularRate
from .aqua import AQUA
from .complementary import Complementary
from .davenport import Davenport
from .ekf import EKF
from .famc import FAMC
from .flae import FLAE
from .fourati import Fourati
from .fqa import FQA
from .tilt import Tilt
from .madgwick import Madgwick
from .mahony import Mahony
from .oleq import OLEQ
from .quest import QUEST
from .roleq import ROLEQ
from .saam import SAAM
from .triad import TRIAD
| true | true |
f71b8eb018fd43deeb30f1cc3852fc3278cb539b | 1,196 | py | Python | Exercicios/ex059.py | MateusBarboza99/Python-03- | 9c6df88aaa8ba83d385b92722ed1df5873df3a77 | [
"MIT"
] | null | null | null | Exercicios/ex059.py | MateusBarboza99/Python-03- | 9c6df88aaa8ba83d385b92722ed1df5873df3a77 | [
"MIT"
] | null | null | null | Exercicios/ex059.py | MateusBarboza99/Python-03- | 9c6df88aaa8ba83d385b92722ed1df5873df3a77 | [
"MIT"
] | null | null | null | from time import sleep
valor1 = int(input('Digite Primeiro valor: '))
valor2 = int(input('Digite segundo valor: '))
opção = 0
while opção != 5:
print(''' [ 1 ] SOMAR
[ 2 ] MULTIPLICAR
[ 3 ] MAIOR
[ 4 ] NOVOS NÚMEROS
[ 5 ] SAIR DO PROGRAMA''')
opção = int(input('Qual opção você deseja ? '))
if opção == 1:
total = valor1 + valor2
print('A soma entre {} + {} é igual a {}'.format(valor1, valor2, total))
elif opção == 2:
produto = valor1 * valor2
print('Multiplicando {} x {} é igual a {}'.format(valor1, valor2, produto))
elif opção == 3:
if valor1 > valor2:
maior = valor1
else:
maior = valor2
print('O Maior número entre {} e {} foi o {}'.format(valor1, valor2, maior))
elif opção == 4:
print('Por favor Informe os número novamente: ')
valor1 = int(input('Digite Primeiro valor: '))
valor2 = int(input('Digite segundo valor: '))
elif opção == 5:
print('Finalizando.......')
sleep(4)
else:
print('Opção Invalida! Tente Novamente!! ')
print('=-=' * 10)
sleep(2)
print('Fim do Programa! Volte sempre!!!')
| 32.324324 | 88 | 0.553512 | from time import sleep
valor1 = int(input('Digite Primeiro valor: '))
valor2 = int(input('Digite segundo valor: '))
opção = 0
while opção != 5:
print(''' [ 1 ] SOMAR
[ 2 ] MULTIPLICAR
[ 3 ] MAIOR
[ 4 ] NOVOS NÚMEROS
[ 5 ] SAIR DO PROGRAMA''')
opção = int(input('Qual opção você deseja ? '))
if opção == 1:
total = valor1 + valor2
print('A soma entre {} + {} é igual a {}'.format(valor1, valor2, total))
elif opção == 2:
produto = valor1 * valor2
print('Multiplicando {} x {} é igual a {}'.format(valor1, valor2, produto))
elif opção == 3:
if valor1 > valor2:
maior = valor1
else:
maior = valor2
print('O Maior número entre {} e {} foi o {}'.format(valor1, valor2, maior))
elif opção == 4:
print('Por favor Informe os número novamente: ')
valor1 = int(input('Digite Primeiro valor: '))
valor2 = int(input('Digite segundo valor: '))
elif opção == 5:
print('Finalizando.......')
sleep(4)
else:
print('Opção Invalida! Tente Novamente!! ')
print('=-=' * 10)
sleep(2)
print('Fim do Programa! Volte sempre!!!')
| true | true |
f71b8f02bb638c288dc1d7f5c04c314106795526 | 2,828 | py | Python | tests/providers/amazon/aws/operators/test_step_function_start_execution.py | ChaseKnowlden/airflow | 6b71eac1997a7c0db3b8e3aed6b4e65d01871440 | [
"Apache-2.0"
] | 15,947 | 2019-01-05T13:51:02.000Z | 2022-03-31T23:33:16.000Z | tests/providers/amazon/aws/operators/test_step_function_start_execution.py | ChaseKnowlden/airflow | 6b71eac1997a7c0db3b8e3aed6b4e65d01871440 | [
"Apache-2.0"
] | 14,603 | 2019-01-05T09:43:19.000Z | 2022-03-31T23:11:59.000Z | tests/providers/amazon/aws/operators/test_step_function_start_execution.py | ChaseKnowlden/airflow | 6b71eac1997a7c0db3b8e3aed6b4e65d01871440 | [
"Apache-2.0"
] | 8,429 | 2019-01-05T19:45:47.000Z | 2022-03-31T22:13:01.000Z | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
from unittest import mock
from unittest.mock import MagicMock
from airflow.providers.amazon.aws.operators.step_function_start_execution import (
StepFunctionStartExecutionOperator,
)
TASK_ID = 'step_function_start_execution_task'
STATE_MACHINE_ARN = 'arn:aws:states:us-east-1:000000000000:stateMachine:pseudo-state-machine'
NAME = 'NAME'
INPUT = '{}'
AWS_CONN_ID = 'aws_non_default'
REGION_NAME = 'us-west-2'
class TestStepFunctionStartExecutionOperator(unittest.TestCase):
def setUp(self):
self.mock_context = MagicMock()
def test_init(self):
# Given / When
operator = StepFunctionStartExecutionOperator(
task_id=TASK_ID,
state_machine_arn=STATE_MACHINE_ARN,
name=NAME,
state_machine_input=INPUT,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
)
# Then
assert TASK_ID == operator.task_id
assert STATE_MACHINE_ARN == operator.state_machine_arn
assert NAME == operator.name
assert INPUT == operator.input
assert AWS_CONN_ID == operator.aws_conn_id
assert REGION_NAME == operator.region_name
@mock.patch('airflow.providers.amazon.aws.operators.step_function_start_execution.StepFunctionHook')
def test_execute(self, mock_hook):
# Given
hook_response = (
'arn:aws:states:us-east-1:123456789012:execution:'
'pseudo-state-machine:020f5b16-b1a1-4149-946f-92dd32d97934'
)
hook_instance = mock_hook.return_value
hook_instance.start_execution.return_value = hook_response
operator = StepFunctionStartExecutionOperator(
task_id=TASK_ID,
state_machine_arn=STATE_MACHINE_ARN,
name=NAME,
state_machine_input=INPUT,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
)
# When
result = operator.execute(self.mock_context)
# Then
assert hook_response == result
| 33.666667 | 104 | 0.703324 |
import unittest
from unittest import mock
from unittest.mock import MagicMock
from airflow.providers.amazon.aws.operators.step_function_start_execution import (
StepFunctionStartExecutionOperator,
)
TASK_ID = 'step_function_start_execution_task'
STATE_MACHINE_ARN = 'arn:aws:states:us-east-1:000000000000:stateMachine:pseudo-state-machine'
NAME = 'NAME'
INPUT = '{}'
AWS_CONN_ID = 'aws_non_default'
REGION_NAME = 'us-west-2'
class TestStepFunctionStartExecutionOperator(unittest.TestCase):
def setUp(self):
self.mock_context = MagicMock()
def test_init(self):
operator = StepFunctionStartExecutionOperator(
task_id=TASK_ID,
state_machine_arn=STATE_MACHINE_ARN,
name=NAME,
state_machine_input=INPUT,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
)
assert TASK_ID == operator.task_id
assert STATE_MACHINE_ARN == operator.state_machine_arn
assert NAME == operator.name
assert INPUT == operator.input
assert AWS_CONN_ID == operator.aws_conn_id
assert REGION_NAME == operator.region_name
@mock.patch('airflow.providers.amazon.aws.operators.step_function_start_execution.StepFunctionHook')
def test_execute(self, mock_hook):
hook_response = (
'arn:aws:states:us-east-1:123456789012:execution:'
'pseudo-state-machine:020f5b16-b1a1-4149-946f-92dd32d97934'
)
hook_instance = mock_hook.return_value
hook_instance.start_execution.return_value = hook_response
operator = StepFunctionStartExecutionOperator(
task_id=TASK_ID,
state_machine_arn=STATE_MACHINE_ARN,
name=NAME,
state_machine_input=INPUT,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
)
result = operator.execute(self.mock_context)
assert hook_response == result
| true | true |
f71b8fffbe1ae2ccf4e9b4742ebf89d95ffbb7f6 | 39 | py | Python | tfcv/modeling/modules/attention/__init__.py | xingzhaolee/tfcv | 27b6a4e8e93cf9b5fecedd6c259118f64b74e263 | [
"MIT"
] | null | null | null | tfcv/modeling/modules/attention/__init__.py | xingzhaolee/tfcv | 27b6a4e8e93cf9b5fecedd6c259118f64b74e263 | [
"MIT"
] | null | null | null | tfcv/modeling/modules/attention/__init__.py | xingzhaolee/tfcv | 27b6a4e8e93cf9b5fecedd6c259118f64b74e263 | [
"MIT"
] | null | null | null | from .bam import *
from .cbam import *
| 13 | 19 | 0.692308 | from .bam import *
from .cbam import *
| true | true |
f71b90fd99c79c76b18913c0621289947d10b94f | 2,923 | py | Python | pkg/distro/packaging_test.py | psigen/rules_pkg | b20c45f292be6c74d2f0d829ba02c83dbe271195 | [
"Apache-2.0"
] | null | null | null | pkg/distro/packaging_test.py | psigen/rules_pkg | b20c45f292be6c74d2f0d829ba02c83dbe271195 | [
"Apache-2.0"
] | null | null | null | pkg/distro/packaging_test.py | psigen/rules_pkg | b20c45f292be6c74d2f0d829ba02c83dbe271195 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test that the rules_pkg distribution is usable."""
import os
import subprocess
import unittest
from bazel_tools.tools.python.runfiles import runfiles
from releasing import release_tools
from distro import release_version
_VERBOSE = True
class PackagingTest(unittest.TestCase):
"""Test the distribution packaging."""
def setUp(self):
self.data_files = runfiles.Create()
self.repo = 'rules_pkg'
self.version = release_version.RELEASE_VERSION
def testBuild(self):
# Set up a fresh Bazel workspace using the currently build repo.
tempdir = os.path.join(os.environ['TEST_TMPDIR'], 'build')
if not os.path.exists(tempdir):
os.makedirs(tempdir)
with open(os.path.join(tempdir, 'WORKSPACE'), 'w') as workspace:
file_name = release_tools.package_basename(self.repo, self.version)
local_path = runfiles.Create().Rlocation(
os.path.join('rules_pkg', 'distro', file_name))
sha256 = release_tools.get_package_sha256(local_path)
workspace_content = '\n'.join((
'workspace(name = "test_rules_pkg_packaging")',
release_tools.workspace_content(
'file://%s' % local_path, self.repo, sha256,
deps_method='rules_pkg_dependencies'
)
))
workspace.write(workspace_content)
if _VERBOSE:
print('=== WORKSPACE ===')
print(workspace_content)
# We do a little dance of renaming *.tmpl to *, mostly so that we do not
# have a BUILD file in testdata, which would create a package boundary.
def CopyTestFile(source_name, dest_name):
source_path = self.data_files.Rlocation(
os.path.join('rules_pkg', 'distro', 'testdata', source_name))
with open(source_path) as inp:
with open(os.path.join(tempdir, dest_name), 'w') as out:
content = inp.read()
out.write(content)
CopyTestFile('BUILD.tmpl', 'BUILD')
os.chdir(tempdir)
build_result = subprocess.check_output(['bazel', 'build', ':dummy_tar'])
if _VERBOSE:
print('=== Build Result ===')
print(build_result)
# TODO(aiuto): Find tar in a disciplined way
content = subprocess.check_output(
['tar', 'tzf', 'bazel-bin/dummy_tar.tar.gz'])
self.assertEqual(b'./\n./BUILD\n', content)
if __name__ == '__main__':
unittest.main()
| 34.797619 | 76 | 0.689702 |
import os
import subprocess
import unittest
from bazel_tools.tools.python.runfiles import runfiles
from releasing import release_tools
from distro import release_version
_VERBOSE = True
class PackagingTest(unittest.TestCase):
def setUp(self):
self.data_files = runfiles.Create()
self.repo = 'rules_pkg'
self.version = release_version.RELEASE_VERSION
def testBuild(self):
tempdir = os.path.join(os.environ['TEST_TMPDIR'], 'build')
if not os.path.exists(tempdir):
os.makedirs(tempdir)
with open(os.path.join(tempdir, 'WORKSPACE'), 'w') as workspace:
file_name = release_tools.package_basename(self.repo, self.version)
local_path = runfiles.Create().Rlocation(
os.path.join('rules_pkg', 'distro', file_name))
sha256 = release_tools.get_package_sha256(local_path)
workspace_content = '\n'.join((
'workspace(name = "test_rules_pkg_packaging")',
release_tools.workspace_content(
'file://%s' % local_path, self.repo, sha256,
deps_method='rules_pkg_dependencies'
)
))
workspace.write(workspace_content)
if _VERBOSE:
print('=== WORKSPACE ===')
print(workspace_content)
def CopyTestFile(source_name, dest_name):
source_path = self.data_files.Rlocation(
os.path.join('rules_pkg', 'distro', 'testdata', source_name))
with open(source_path) as inp:
with open(os.path.join(tempdir, dest_name), 'w') as out:
content = inp.read()
out.write(content)
CopyTestFile('BUILD.tmpl', 'BUILD')
os.chdir(tempdir)
build_result = subprocess.check_output(['bazel', 'build', ':dummy_tar'])
if _VERBOSE:
print('=== Build Result ===')
print(build_result)
content = subprocess.check_output(
['tar', 'tzf', 'bazel-bin/dummy_tar.tar.gz'])
self.assertEqual(b'./\n./BUILD\n', content)
if __name__ == '__main__':
unittest.main()
| true | true |
f71b9174bdbad3aa8de9187fea7cf060e68be521 | 277,501 | py | Python | sdk/eventgrid/azure-eventgrid/azure/eventgrid/_generated/models/_models.py | mtin/azure-sdk-for-python | 08d7f8f76d1c9eca230cbcecb3c42eb92817bcb8 | [
"MIT"
] | null | null | null | sdk/eventgrid/azure-eventgrid/azure/eventgrid/_generated/models/_models.py | mtin/azure-sdk-for-python | 08d7f8f76d1c9eca230cbcecb3c42eb92817bcb8 | [
"MIT"
] | null | null | null | sdk/eventgrid/azure-eventgrid/azure/eventgrid/_generated/models/_models.py | mtin/azure-sdk-for-python | 08d7f8f76d1c9eca230cbcecb3c42eb92817bcb8 | [
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import msrest.serialization
class AcsChatEventBaseProperties(msrest.serialization.Model):
"""Schema of common properties of all chat events.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatEventBaseProperties, self).__init__(**kwargs)
self.recipient_communication_identifier = kwargs.get('recipient_communication_identifier', None)
self.transaction_id = kwargs.get('transaction_id', None)
self.thread_id = kwargs.get('thread_id', None)
class AcsChatEventInThreadBaseProperties(msrest.serialization.Model):
"""Schema of common properties of all thread-level chat events.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatEventInThreadBaseProperties, self).__init__(**kwargs)
self.transaction_id = kwargs.get('transaction_id', None)
self.thread_id = kwargs.get('thread_id', None)
class AcsChatMessageEventBaseProperties(AcsChatEventBaseProperties):
"""Schema of common properties of all chat message events.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEventBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.sender_communication_identifier = kwargs.get('sender_communication_identifier', None)
self.sender_display_name = kwargs.get('sender_display_name', None)
self.compose_time = kwargs.get('compose_time', None)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', None)
class AcsChatMessageDeletedEventData(AcsChatMessageEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeleted event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param delete_time: The time at which the message was deleted.
:type delete_time: ~datetime.datetime
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageDeletedEventData, self).__init__(**kwargs)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatMessageEventInThreadBaseProperties(AcsChatEventInThreadBaseProperties):
"""Schema of common properties of all thread-level chat message events.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEventInThreadBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.sender_communication_identifier = kwargs.get('sender_communication_identifier', None)
self.sender_display_name = kwargs.get('sender_display_name', None)
self.compose_time = kwargs.get('compose_time', None)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', None)
class AcsChatMessageDeletedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeletedInThread event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param delete_time: The time at which the message was deleted.
:type delete_time: ~datetime.datetime
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageDeletedInThreadEventData, self).__init__(**kwargs)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatMessageEditedEventData(AcsChatMessageEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEdited event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param message_body: The body of the chat message.
:type message_body: str
:param edit_time: The time at which the message was edited.
:type edit_time: ~datetime.datetime
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEditedEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
self.edit_time = kwargs.get('edit_time', None)
class AcsChatMessageEditedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEditedInThread event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param message_body: The body of the chat message.
:type message_body: str
:param edit_time: The time at which the message was edited.
:type edit_time: ~datetime.datetime
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEditedInThreadEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
self.edit_time = kwargs.get('edit_time', None)
class AcsChatMessageReceivedEventData(AcsChatMessageEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceived event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param message_body: The body of the chat message.
:type message_body: str
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageReceivedEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
class AcsChatMessageReceivedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceivedInThread event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param message_id: The chat message id.
:type message_id: str
:param sender_communication_identifier: The communication identifier of the sender.
:type sender_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param sender_display_name: The display name of the sender.
:type sender_display_name: str
:param compose_time: The original compose time of the message.
:type compose_time: ~datetime.datetime
:param type: The type of the message.
:type type: str
:param version: The version of the message.
:type version: long
:param message_body: The body of the chat message.
:type message_body: str
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageReceivedInThreadEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
class AcsChatParticipantAddedToThreadEventData(AcsChatEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantAdded event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param time: The time at which the user was added to the thread.
:type time: ~datetime.datetime
:param added_by_communication_identifier: The communication identifier of the user who added
the user.
:type added_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param participant_added: The details of the user who was added.
:type participant_added: ~event_grid_publisher_client.models.AcsChatThreadParticipantProperties
:param version: The version of the thread.
:type version: long
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'added_by_communication_identifier': {'key': 'addedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_added': {'key': 'participantAdded', 'type': 'AcsChatThreadParticipantProperties'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantAddedToThreadEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.added_by_communication_identifier = kwargs.get('added_by_communication_identifier', None)
self.participant_added = kwargs.get('participant_added', None)
self.version = kwargs.get('version', None)
class AcsChatThreadEventBaseProperties(AcsChatEventBaseProperties):
"""Schema of common properties of all chat thread events.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadEventBaseProperties, self).__init__(**kwargs)
self.create_time = kwargs.get('create_time', None)
self.version = kwargs.get('version', None)
class AcsChatParticipantAddedToThreadWithUserEventData(AcsChatThreadEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatParticipantAddedToThreadWithUser event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param time: The time at which the user was added to the thread.
:type time: ~datetime.datetime
:param added_by_communication_identifier: The communication identifier of the user who added
the user.
:type added_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param participant_added: The details of the user who was added.
:type participant_added: ~event_grid_publisher_client.models.AcsChatThreadParticipantProperties
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'time': {'key': 'time', 'type': 'iso-8601'},
'added_by_communication_identifier': {'key': 'addedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_added': {'key': 'participantAdded', 'type': 'AcsChatThreadParticipantProperties'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantAddedToThreadWithUserEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.added_by_communication_identifier = kwargs.get('added_by_communication_identifier', None)
self.participant_added = kwargs.get('participant_added', None)
class AcsChatParticipantRemovedFromThreadEventData(AcsChatEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantRemoved event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param time: The time at which the user was removed to the thread.
:type time: ~datetime.datetime
:param removed_by_communication_identifier: The communication identifier of the user who
removed the user.
:type removed_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param participant_removed: The details of the user who was removed.
:type participant_removed:
~event_grid_publisher_client.models.AcsChatThreadParticipantProperties
:param version: The version of the thread.
:type version: long
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'removed_by_communication_identifier': {'key': 'removedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_removed': {'key': 'participantRemoved', 'type': 'AcsChatThreadParticipantProperties'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantRemovedFromThreadEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.removed_by_communication_identifier = kwargs.get('removed_by_communication_identifier', None)
self.participant_removed = kwargs.get('participant_removed', None)
self.version = kwargs.get('version', None)
class AcsChatParticipantRemovedFromThreadWithUserEventData(AcsChatThreadEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param time: The time at which the user was removed to the thread.
:type time: ~datetime.datetime
:param removed_by_communication_identifier: The communication identifier of the user who
removed the user.
:type removed_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param participant_removed: The details of the user who was removed.
:type participant_removed:
~event_grid_publisher_client.models.AcsChatThreadParticipantProperties
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'time': {'key': 'time', 'type': 'iso-8601'},
'removed_by_communication_identifier': {'key': 'removedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_removed': {'key': 'participantRemoved', 'type': 'AcsChatThreadParticipantProperties'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantRemovedFromThreadWithUserEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.removed_by_communication_identifier = kwargs.get('removed_by_communication_identifier', None)
self.participant_removed = kwargs.get('participant_removed', None)
class AcsChatThreadEventInThreadBaseProperties(AcsChatEventInThreadBaseProperties):
"""Schema of common properties of all chat thread events.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadEventInThreadBaseProperties, self).__init__(**kwargs)
self.create_time = kwargs.get('create_time', None)
self.version = kwargs.get('version', None)
class AcsChatThreadCreatedEventData(AcsChatThreadEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreated event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param created_by_communication_identifier: The communication identifier of the user who
created the thread.
:type created_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param properties: The thread properties.
:type properties: dict[str, object]
:param participants: The list of properties of participants who are part of the thread.
:type participants:
list[~event_grid_publisher_client.models.AcsChatThreadParticipantProperties]
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'created_by_communication_identifier': {'key': 'createdByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'properties': {'key': 'properties', 'type': '{object}'},
'participants': {'key': 'participants', 'type': '[AcsChatThreadParticipantProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadCreatedEventData, self).__init__(**kwargs)
self.created_by_communication_identifier = kwargs.get('created_by_communication_identifier', None)
self.properties = kwargs.get('properties', None)
self.participants = kwargs.get('participants', None)
class AcsChatThreadCreatedWithUserEventData(AcsChatThreadEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreatedWithUser event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param created_by_communication_identifier: The communication identifier of the user who
created the thread.
:type created_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param properties: The thread properties.
:type properties: dict[str, object]
:param participants: The list of properties of participants who are part of the thread.
:type participants:
list[~event_grid_publisher_client.models.AcsChatThreadParticipantProperties]
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'created_by_communication_identifier': {'key': 'createdByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'properties': {'key': 'properties', 'type': '{object}'},
'participants': {'key': 'participants', 'type': '[AcsChatThreadParticipantProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadCreatedWithUserEventData, self).__init__(**kwargs)
self.created_by_communication_identifier = kwargs.get('created_by_communication_identifier', None)
self.properties = kwargs.get('properties', None)
self.participants = kwargs.get('participants', None)
class AcsChatThreadDeletedEventData(AcsChatThreadEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadDeleted event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param deleted_by_communication_identifier: The communication identifier of the user who
deleted the thread.
:type deleted_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param delete_time: The deletion time of the thread.
:type delete_time: ~datetime.datetime
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'deleted_by_communication_identifier': {'key': 'deletedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadDeletedEventData, self).__init__(**kwargs)
self.deleted_by_communication_identifier = kwargs.get('deleted_by_communication_identifier', None)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatThreadParticipantProperties(msrest.serialization.Model):
"""Schema of the chat thread participant.
:param display_name: The name of the user.
:type display_name: str
:param participant_communication_identifier: The communication identifier of the user.
:type participant_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'participant_communication_identifier': {'key': 'participantCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadParticipantProperties, self).__init__(**kwargs)
self.display_name = kwargs.get('display_name', None)
self.participant_communication_identifier = kwargs.get('participant_communication_identifier', None)
class AcsChatThreadPropertiesUpdatedEventData(AcsChatThreadEventInThreadBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdated event.
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param edited_by_communication_identifier: The communication identifier of the user who updated
the thread properties.
:type edited_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param edit_time: The time at which the properties of the thread were updated.
:type edit_time: ~datetime.datetime
:param properties: The updated thread properties.
:type properties: dict[str, object]
"""
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'edited_by_communication_identifier': {'key': 'editedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
'properties': {'key': 'properties', 'type': '{object}'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadPropertiesUpdatedEventData, self).__init__(**kwargs)
self.edited_by_communication_identifier = kwargs.get('edited_by_communication_identifier', None)
self.edit_time = kwargs.get('edit_time', None)
self.properties = kwargs.get('properties', None)
class AcsChatThreadPropertiesUpdatedPerUserEventData(AcsChatThreadEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param edited_by_communication_identifier: The communication identifier of the user who updated
the thread properties.
:type edited_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param edit_time: The time at which the properties of the thread were updated.
:type edit_time: ~datetime.datetime
:param properties: The updated thread properties.
:type properties: dict[str, object]
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'edited_by_communication_identifier': {'key': 'editedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
'properties': {'key': 'properties', 'type': '{object}'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadPropertiesUpdatedPerUserEventData, self).__init__(**kwargs)
self.edited_by_communication_identifier = kwargs.get('edited_by_communication_identifier', None)
self.edit_time = kwargs.get('edit_time', None)
self.properties = kwargs.get('properties', None)
class AcsChatThreadWithUserDeletedEventData(AcsChatThreadEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadWithUserDeleted event.
:param recipient_communication_identifier: The communication identifier of the target user.
:type recipient_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param transaction_id: The transaction id will be used as co-relation vector.
:type transaction_id: str
:param thread_id: The chat thread id.
:type thread_id: str
:param create_time: The original creation time of the thread.
:type create_time: ~datetime.datetime
:param version: The version of the thread.
:type version: long
:param deleted_by_communication_identifier: The communication identifier of the user who
deleted the thread.
:type deleted_by_communication_identifier:
~event_grid_publisher_client.models.CommunicationIdentifierModel
:param delete_time: The deletion time of the thread.
:type delete_time: ~datetime.datetime
"""
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'deleted_by_communication_identifier': {'key': 'deletedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadWithUserDeletedEventData, self).__init__(**kwargs)
self.deleted_by_communication_identifier = kwargs.get('deleted_by_communication_identifier', None)
self.delete_time = kwargs.get('delete_time', None)
class AcsRecordingChunkInfoProperties(msrest.serialization.Model):
"""Schema for all properties of Recording Chunk Information.
:param document_id: The documentId of the recording chunk.
:type document_id: str
:param index: The index of the recording chunk.
:type index: long
:param end_reason: The reason for ending the recording chunk.
:type end_reason: str
"""
_attribute_map = {
'document_id': {'key': 'documentId', 'type': 'str'},
'index': {'key': 'index', 'type': 'long'},
'end_reason': {'key': 'endReason', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingChunkInfoProperties, self).__init__(**kwargs)
self.document_id = kwargs.get('document_id', None)
self.index = kwargs.get('index', None)
self.end_reason = kwargs.get('end_reason', None)
class AcsRecordingFileStatusUpdatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RecordingFileStatusUpdated event.
:param recording_storage_info: The details of recording storage information.
:type recording_storage_info:
~event_grid_publisher_client.models.AcsRecordingStorageInfoProperties
:param recording_start_time: The time at which the recording started.
:type recording_start_time: ~datetime.datetime
:param recording_duration_ms: The recording duration in milliseconds.
:type recording_duration_ms: long
:param session_end_reason: The reason for ending recording session.
:type session_end_reason: str
"""
_attribute_map = {
'recording_storage_info': {'key': 'recordingStorageInfo', 'type': 'AcsRecordingStorageInfoProperties'},
'recording_start_time': {'key': 'recordingStartTime', 'type': 'iso-8601'},
'recording_duration_ms': {'key': 'recordingDurationMs', 'type': 'long'},
'session_end_reason': {'key': 'sessionEndReason', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingFileStatusUpdatedEventData, self).__init__(**kwargs)
self.recording_storage_info = kwargs.get('recording_storage_info', None)
self.recording_start_time = kwargs.get('recording_start_time', None)
self.recording_duration_ms = kwargs.get('recording_duration_ms', None)
self.session_end_reason = kwargs.get('session_end_reason', None)
class AcsRecordingStorageInfoProperties(msrest.serialization.Model):
"""Schema for all properties of Recording Storage Information.
:param recording_chunks: List of details of recording chunks information.
:type recording_chunks:
list[~event_grid_publisher_client.models.AcsRecordingChunkInfoProperties]
"""
_attribute_map = {
'recording_chunks': {'key': 'recordingChunks', 'type': '[AcsRecordingChunkInfoProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingStorageInfoProperties, self).__init__(**kwargs)
self.recording_chunks = kwargs.get('recording_chunks', None)
class AcsSmsDeliveryAttemptProperties(msrest.serialization.Model):
"""Schema for details of a delivery attempt.
:param timestamp: TimeStamp when delivery was attempted.
:type timestamp: ~datetime.datetime
:param segments_succeeded: Number of segments that were successfully delivered.
:type segments_succeeded: int
:param segments_failed: Number of segments whose delivery failed.
:type segments_failed: int
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'segments_succeeded': {'key': 'segmentsSucceeded', 'type': 'int'},
'segments_failed': {'key': 'segmentsFailed', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsDeliveryAttemptProperties, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.segments_succeeded = kwargs.get('segments_succeeded', None)
self.segments_failed = kwargs.get('segments_failed', None)
class AcsSmsEventBaseProperties(msrest.serialization.Model):
"""Schema of common properties of all SMS events.
:param message_id: The identity of the SMS message.
:type message_id: str
:param from_property: The identity of SMS message sender.
:type from_property: str
:param to: The identity of SMS message receiver.
:type to: str
"""
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsEventBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.from_property = kwargs.get('from_property', None)
self.to = kwargs.get('to', None)
class AcsSmsDeliveryReportReceivedEventData(AcsSmsEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSDeliveryReportReceived event.
:param message_id: The identity of the SMS message.
:type message_id: str
:param from_property: The identity of SMS message sender.
:type from_property: str
:param to: The identity of SMS message receiver.
:type to: str
:param delivery_status: Status of Delivery.
:type delivery_status: str
:param delivery_status_details: Details about Delivery Status.
:type delivery_status_details: str
:param delivery_attempts: List of details of delivery attempts made.
:type delivery_attempts:
list[~event_grid_publisher_client.models.AcsSmsDeliveryAttemptProperties]
:param received_timestamp: The time at which the SMS delivery report was received.
:type received_timestamp: ~datetime.datetime
:param tag: Customer Content.
:type tag: str
"""
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
'delivery_status': {'key': 'deliveryStatus', 'type': 'str'},
'delivery_status_details': {'key': 'deliveryStatusDetails', 'type': 'str'},
'delivery_attempts': {'key': 'deliveryAttempts', 'type': '[AcsSmsDeliveryAttemptProperties]'},
'received_timestamp': {'key': 'receivedTimestamp', 'type': 'iso-8601'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsDeliveryReportReceivedEventData, self).__init__(**kwargs)
self.delivery_status = kwargs.get('delivery_status', None)
self.delivery_status_details = kwargs.get('delivery_status_details', None)
self.delivery_attempts = kwargs.get('delivery_attempts', None)
self.received_timestamp = kwargs.get('received_timestamp', None)
self.tag = kwargs.get('tag', None)
class AcsSmsReceivedEventData(AcsSmsEventBaseProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSReceived event.
:param message_id: The identity of the SMS message.
:type message_id: str
:param from_property: The identity of SMS message sender.
:type from_property: str
:param to: The identity of SMS message receiver.
:type to: str
:param message: The SMS content.
:type message: str
:param received_timestamp: The time at which the SMS was received.
:type received_timestamp: ~datetime.datetime
"""
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'received_timestamp': {'key': 'receivedTimestamp', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsReceivedEventData, self).__init__(**kwargs)
self.message = kwargs.get('message', None)
self.received_timestamp = kwargs.get('received_timestamp', None)
class AppConfigurationKeyValueDeletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueDeleted event.
:param key: The key used to identify the key-value that was deleted.
:type key: str
:param label: The label, if any, used to identify the key-value that was deleted.
:type label: str
:param etag: The etag representing the key-value that was deleted.
:type etag: str
:param sync_token: The sync token representing the server state after the event.
:type sync_token: str
"""
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'label': {'key': 'label', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'sync_token': {'key': 'syncToken', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppConfigurationKeyValueDeletedEventData, self).__init__(**kwargs)
self.key = kwargs.get('key', None)
self.label = kwargs.get('label', None)
self.etag = kwargs.get('etag', None)
self.sync_token = kwargs.get('sync_token', None)
class AppConfigurationKeyValueModifiedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueModified event.
:param key: The key used to identify the key-value that was modified.
:type key: str
:param label: The label, if any, used to identify the key-value that was modified.
:type label: str
:param etag: The etag representing the new state of the key-value.
:type etag: str
:param sync_token: The sync token representing the server state after the event.
:type sync_token: str
"""
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'label': {'key': 'label', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'sync_token': {'key': 'syncToken', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppConfigurationKeyValueModifiedEventData, self).__init__(**kwargs)
self.key = kwargs.get('key', None)
self.label = kwargs.get('label', None)
self.etag = kwargs.get('etag', None)
self.sync_token = kwargs.get('sync_token', None)
class AppEventTypeDetail(msrest.serialization.Model):
"""Detail of action on the app.
:param action: Type of action of the operation. Possible values include: "Restarted",
"Stopped", "ChangedAppSettings", "Started", "Completed", "Failed".
:type action: str or ~event_grid_publisher_client.models.AppAction
"""
_attribute_map = {
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppEventTypeDetail, self).__init__(**kwargs)
self.action = kwargs.get('action', None)
class AppServicePlanEventTypeDetail(msrest.serialization.Model):
"""Detail of action on the app service plan.
:param stamp_kind: Kind of environment where app service plan is. Possible values include:
"Public", "AseV1", "AseV2".
:type stamp_kind: str or ~event_grid_publisher_client.models.StampKind
:param action: Type of action on the app service plan. Possible values include: "Updated".
:type action: str or ~event_grid_publisher_client.models.AppServicePlanAction
:param status: Asynchronous operation status of the operation on the app service plan. Possible
values include: "Started", "Completed", "Failed".
:type status: str or ~event_grid_publisher_client.models.AsyncStatus
"""
_attribute_map = {
'stamp_kind': {'key': 'stampKind', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppServicePlanEventTypeDetail, self).__init__(**kwargs)
self.stamp_kind = kwargs.get('stamp_kind', None)
self.action = kwargs.get('action', None)
self.status = kwargs.get('status', None)
class CloudEvent(msrest.serialization.Model):
"""Properties of an event published to an Event Grid topic using the CloudEvent 1.0 Schema.
All required parameters must be populated in order to send to Azure.
:param additional_properties: Unmatched properties from the message are deserialized to this
collection.
:type additional_properties: dict[str, object]
:param id: Required. An identifier for the event. The combination of id and source must be
unique for each distinct event.
:type id: str
:param source: Required. Identifies the context in which an event happened. The combination of
id and source must be unique for each distinct event.
:type source: str
:param data: Event data specific to the event type.
:type data: object
:param data_base64: Event data specific to the event type, encoded as a base64 string.
:type data_base64: bytearray
:param type: Required. Type of event related to the originating occurrence.
:type type: str
:param time: The time (in UTC) the event was generated, in RFC3339 format.
:type time: ~datetime.datetime
:param specversion: Required. The version of the CloudEvents specification which the event
uses.
:type specversion: str
:param dataschema: Identifies the schema that data adheres to.
:type dataschema: str
:param datacontenttype: Content type of data value.
:type datacontenttype: str
:param subject: This describes the subject of the event in the context of the event producer
(identified by source).
:type subject: str
"""
_validation = {
'id': {'required': True},
'source': {'required': True},
'type': {'required': True},
'specversion': {'required': True},
}
_attribute_map = {
'additional_properties': {'key': '', 'type': '{object}'},
'id': {'key': 'id', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'},
'data': {'key': 'data', 'type': 'object'},
'data_base64': {'key': 'data_base64', 'type': 'bytearray'},
'type': {'key': 'type', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'specversion': {'key': 'specversion', 'type': 'str'},
'dataschema': {'key': 'dataschema', 'type': 'str'},
'datacontenttype': {'key': 'datacontenttype', 'type': 'str'},
'subject': {'key': 'subject', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CloudEvent, self).__init__(**kwargs)
self.additional_properties = kwargs.get('additional_properties', None)
self.id = kwargs['id']
self.source = kwargs['source']
self.data = kwargs.get('data', None)
self.data_base64 = kwargs.get('data_base64', None)
self.type = kwargs['type']
self.time = kwargs.get('time', None)
self.specversion = kwargs['specversion']
self.dataschema = kwargs.get('dataschema', None)
self.datacontenttype = kwargs.get('datacontenttype', None)
self.subject = kwargs.get('subject', None)
class CommunicationIdentifierModel(msrest.serialization.Model):
"""Identifies a participant in Azure Communication services. A participant is, for example, a phone number or an Azure communication user. This model must be interpreted as a union: Apart from rawId, at most one further property may be set.
:param raw_id: Raw Id of the identifier. Optional in requests, required in responses.
:type raw_id: str
:param communication_user: The communication user.
:type communication_user: ~event_grid_publisher_client.models.CommunicationUserIdentifierModel
:param phone_number: The phone number.
:type phone_number: ~event_grid_publisher_client.models.PhoneNumberIdentifierModel
:param microsoft_teams_user: The Microsoft Teams user.
:type microsoft_teams_user:
~event_grid_publisher_client.models.MicrosoftTeamsUserIdentifierModel
"""
_attribute_map = {
'raw_id': {'key': 'rawId', 'type': 'str'},
'communication_user': {'key': 'communicationUser', 'type': 'CommunicationUserIdentifierModel'},
'phone_number': {'key': 'phoneNumber', 'type': 'PhoneNumberIdentifierModel'},
'microsoft_teams_user': {'key': 'microsoftTeamsUser', 'type': 'MicrosoftTeamsUserIdentifierModel'},
}
def __init__(
self,
**kwargs
):
super(CommunicationIdentifierModel, self).__init__(**kwargs)
self.raw_id = kwargs.get('raw_id', None)
self.communication_user = kwargs.get('communication_user', None)
self.phone_number = kwargs.get('phone_number', None)
self.microsoft_teams_user = kwargs.get('microsoft_teams_user', None)
class CommunicationUserIdentifierModel(msrest.serialization.Model):
"""A user that got created with an Azure Communication Services resource.
All required parameters must be populated in order to send to Azure.
:param id: Required. The Id of the communication user.
:type id: str
"""
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CommunicationUserIdentifierModel, self).__init__(**kwargs)
self.id = kwargs['id']
class ContainerRegistryArtifactEventData(msrest.serialization.Model):
"""The content of the event request message.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryArtifactEventTarget
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryArtifactEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.timestamp = kwargs.get('timestamp', None)
self.action = kwargs.get('action', None)
self.target = kwargs.get('target', None)
class ContainerRegistryArtifactEventTarget(msrest.serialization.Model):
"""The target of the event.
:param media_type: The MIME type of the artifact.
:type media_type: str
:param size: The size in bytes of the artifact.
:type size: long
:param digest: The digest of the artifact.
:type digest: str
:param repository: The repository name of the artifact.
:type repository: str
:param tag: The tag of the artifact.
:type tag: str
:param name: The name of the artifact.
:type name: str
:param version: The version of the artifact.
:type version: str
"""
_attribute_map = {
'media_type': {'key': 'mediaType', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'digest': {'key': 'digest', 'type': 'str'},
'repository': {'key': 'repository', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryArtifactEventTarget, self).__init__(**kwargs)
self.media_type = kwargs.get('media_type', None)
self.size = kwargs.get('size', None)
self.digest = kwargs.get('digest', None)
self.repository = kwargs.get('repository', None)
self.tag = kwargs.get('tag', None)
self.name = kwargs.get('name', None)
self.version = kwargs.get('version', None)
class ContainerRegistryChartDeletedEventData(ContainerRegistryArtifactEventData):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartDeleted event.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryArtifactEventTarget
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryChartDeletedEventData, self).__init__(**kwargs)
class ContainerRegistryChartPushedEventData(ContainerRegistryArtifactEventData):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartPushed event.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryArtifactEventTarget
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryChartPushedEventData, self).__init__(**kwargs)
class ContainerRegistryEventActor(msrest.serialization.Model):
"""The agent that initiated the event. For most situations, this could be from the authorization context of the request.
:param name: The subject or username associated with the request context that generated the
event.
:type name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventActor, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class ContainerRegistryEventData(msrest.serialization.Model):
"""The content of the event request message.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryEventTarget
:param request: The request that generated the event.
:type request: ~event_grid_publisher_client.models.ContainerRegistryEventRequest
:param actor: The agent that initiated the event. For most situations, this could be from the
authorization context of the request.
:type actor: ~event_grid_publisher_client.models.ContainerRegistryEventActor
:param source: The registry node that generated the event. Put differently, while the actor
initiates the event, the source generates it.
:type source: ~event_grid_publisher_client.models.ContainerRegistryEventSource
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.timestamp = kwargs.get('timestamp', None)
self.action = kwargs.get('action', None)
self.target = kwargs.get('target', None)
self.request = kwargs.get('request', None)
self.actor = kwargs.get('actor', None)
self.source = kwargs.get('source', None)
class ContainerRegistryEventRequest(msrest.serialization.Model):
"""The request that generated the event.
:param id: The ID of the request that initiated the event.
:type id: str
:param addr: The IP or hostname and possibly port of the client connection that initiated the
event. This is the RemoteAddr from the standard http request.
:type addr: str
:param host: The externally accessible hostname of the registry instance, as specified by the
http host header on incoming requests.
:type host: str
:param method: The request method that generated the event.
:type method: str
:param useragent: The user agent header of the request.
:type useragent: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'addr': {'key': 'addr', 'type': 'str'},
'host': {'key': 'host', 'type': 'str'},
'method': {'key': 'method', 'type': 'str'},
'useragent': {'key': 'useragent', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventRequest, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.addr = kwargs.get('addr', None)
self.host = kwargs.get('host', None)
self.method = kwargs.get('method', None)
self.useragent = kwargs.get('useragent', None)
class ContainerRegistryEventSource(msrest.serialization.Model):
"""The registry node that generated the event. Put differently, while the actor initiates the event, the source generates it.
:param addr: The IP or hostname and the port of the registry node that generated the event.
Generally, this will be resolved by os.Hostname() along with the running port.
:type addr: str
:param instance_id: The running instance of an application. Changes after each restart.
:type instance_id: str
"""
_attribute_map = {
'addr': {'key': 'addr', 'type': 'str'},
'instance_id': {'key': 'instanceID', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventSource, self).__init__(**kwargs)
self.addr = kwargs.get('addr', None)
self.instance_id = kwargs.get('instance_id', None)
class ContainerRegistryEventTarget(msrest.serialization.Model):
"""The target of the event.
:param media_type: The MIME type of the referenced object.
:type media_type: str
:param size: The number of bytes of the content. Same as Length field.
:type size: long
:param digest: The digest of the content, as defined by the Registry V2 HTTP API Specification.
:type digest: str
:param length: The number of bytes of the content. Same as Size field.
:type length: long
:param repository: The repository name.
:type repository: str
:param url: The direct URL to the content.
:type url: str
:param tag: The tag name.
:type tag: str
"""
_attribute_map = {
'media_type': {'key': 'mediaType', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'digest': {'key': 'digest', 'type': 'str'},
'length': {'key': 'length', 'type': 'long'},
'repository': {'key': 'repository', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventTarget, self).__init__(**kwargs)
self.media_type = kwargs.get('media_type', None)
self.size = kwargs.get('size', None)
self.digest = kwargs.get('digest', None)
self.length = kwargs.get('length', None)
self.repository = kwargs.get('repository', None)
self.url = kwargs.get('url', None)
self.tag = kwargs.get('tag', None)
class ContainerRegistryImageDeletedEventData(ContainerRegistryEventData):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImageDeleted event.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryEventTarget
:param request: The request that generated the event.
:type request: ~event_grid_publisher_client.models.ContainerRegistryEventRequest
:param actor: The agent that initiated the event. For most situations, this could be from the
authorization context of the request.
:type actor: ~event_grid_publisher_client.models.ContainerRegistryEventActor
:param source: The registry node that generated the event. Put differently, while the actor
initiates the event, the source generates it.
:type source: ~event_grid_publisher_client.models.ContainerRegistryEventSource
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryImageDeletedEventData, self).__init__(**kwargs)
class ContainerRegistryImagePushedEventData(ContainerRegistryEventData):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImagePushed event.
:param id: The event ID.
:type id: str
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param action: The action that encompasses the provided event.
:type action: str
:param target: The target of the event.
:type target: ~event_grid_publisher_client.models.ContainerRegistryEventTarget
:param request: The request that generated the event.
:type request: ~event_grid_publisher_client.models.ContainerRegistryEventRequest
:param actor: The agent that initiated the event. For most situations, this could be from the
authorization context of the request.
:type actor: ~event_grid_publisher_client.models.ContainerRegistryEventActor
:param source: The registry node that generated the event. Put differently, while the actor
initiates the event, the source generates it.
:type source: ~event_grid_publisher_client.models.ContainerRegistryEventSource
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryImagePushedEventData, self).__init__(**kwargs)
class DeviceConnectionStateEventInfo(msrest.serialization.Model):
"""Information about the device connection state event.
:param sequence_number: Sequence number is string representation of a hexadecimal number.
string compare can be used to identify the larger number because both in ASCII and HEX numbers
come after alphabets. If you are converting the string to hex, then the number is a 256 bit
number.
:type sequence_number: str
"""
_attribute_map = {
'sequence_number': {'key': 'sequenceNumber', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceConnectionStateEventInfo, self).__init__(**kwargs)
self.sequence_number = kwargs.get('sequence_number', None)
class DeviceConnectionStateEventProperties(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a device connection state event (DeviceConnected, DeviceDisconnected).
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param module_id: The unique identifier of the module. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type module_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param device_connection_state_event_info: Information about the device connection state event.
:type device_connection_state_event_info:
~event_grid_publisher_client.models.DeviceConnectionStateEventInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(DeviceConnectionStateEventProperties, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.module_id = kwargs.get('module_id', None)
self.hub_name = kwargs.get('hub_name', None)
self.device_connection_state_event_info = kwargs.get('device_connection_state_event_info', None)
class DeviceLifeCycleEventProperties(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a device life cycle event (DeviceCreated, DeviceDeleted).
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param twin: Information about the device twin, which is the cloud representation of
application device metadata.
:type twin: ~event_grid_publisher_client.models.DeviceTwinInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(DeviceLifeCycleEventProperties, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.hub_name = kwargs.get('hub_name', None)
self.twin = kwargs.get('twin', None)
class DeviceTelemetryEventProperties(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a device telemetry event (DeviceTelemetry).
:param body: The content of the message from the device.
:type body: object
:param properties: Application properties are user-defined strings that can be added to the
message. These fields are optional.
:type properties: dict[str, str]
:param system_properties: System properties help identify contents and source of the messages.
:type system_properties: dict[str, str]
"""
_attribute_map = {
'body': {'key': 'body', 'type': 'object'},
'properties': {'key': 'properties', 'type': '{str}'},
'system_properties': {'key': 'systemProperties', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(DeviceTelemetryEventProperties, self).__init__(**kwargs)
self.body = kwargs.get('body', None)
self.properties = kwargs.get('properties', None)
self.system_properties = kwargs.get('system_properties', None)
class DeviceTwinInfo(msrest.serialization.Model):
"""Information about the device twin, which is the cloud representation of application device metadata.
:param authentication_type: Authentication type used for this device: either SAS, SelfSigned,
or CertificateAuthority.
:type authentication_type: str
:param cloud_to_device_message_count: Count of cloud to device messages sent to this device.
:type cloud_to_device_message_count: float
:param connection_state: Whether the device is connected or disconnected.
:type connection_state: str
:param device_id: The unique identifier of the device twin.
:type device_id: str
:param etag: A piece of information that describes the content of the device twin. Each etag is
guaranteed to be unique per device twin.
:type etag: str
:param last_activity_time: The ISO8601 timestamp of the last activity.
:type last_activity_time: str
:param properties: Properties JSON element.
:type properties: ~event_grid_publisher_client.models.DeviceTwinInfoProperties
:param status: Whether the device twin is enabled or disabled.
:type status: str
:param status_update_time: The ISO8601 timestamp of the last device twin status update.
:type status_update_time: str
:param version: An integer that is incremented by one each time the device twin is updated.
:type version: float
:param x509_thumbprint: The thumbprint is a unique value for the x509 certificate, commonly
used to find a particular certificate in a certificate store. The thumbprint is dynamically
generated using the SHA1 algorithm, and does not physically exist in the certificate.
:type x509_thumbprint: ~event_grid_publisher_client.models.DeviceTwinInfoX509Thumbprint
"""
_attribute_map = {
'authentication_type': {'key': 'authenticationType', 'type': 'str'},
'cloud_to_device_message_count': {'key': 'cloudToDeviceMessageCount', 'type': 'float'},
'connection_state': {'key': 'connectionState', 'type': 'str'},
'device_id': {'key': 'deviceId', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'last_activity_time': {'key': 'lastActivityTime', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DeviceTwinInfoProperties'},
'status': {'key': 'status', 'type': 'str'},
'status_update_time': {'key': 'statusUpdateTime', 'type': 'str'},
'version': {'key': 'version', 'type': 'float'},
'x509_thumbprint': {'key': 'x509Thumbprint', 'type': 'DeviceTwinInfoX509Thumbprint'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfo, self).__init__(**kwargs)
self.authentication_type = kwargs.get('authentication_type', None)
self.cloud_to_device_message_count = kwargs.get('cloud_to_device_message_count', None)
self.connection_state = kwargs.get('connection_state', None)
self.device_id = kwargs.get('device_id', None)
self.etag = kwargs.get('etag', None)
self.last_activity_time = kwargs.get('last_activity_time', None)
self.properties = kwargs.get('properties', None)
self.status = kwargs.get('status', None)
self.status_update_time = kwargs.get('status_update_time', None)
self.version = kwargs.get('version', None)
self.x509_thumbprint = kwargs.get('x509_thumbprint', None)
class DeviceTwinInfoProperties(msrest.serialization.Model):
"""Properties JSON element.
:param desired: A portion of the properties that can be written only by the application back-
end, and read by the device.
:type desired: ~event_grid_publisher_client.models.DeviceTwinProperties
:param reported: A portion of the properties that can be written only by the device, and read
by the application back-end.
:type reported: ~event_grid_publisher_client.models.DeviceTwinProperties
"""
_attribute_map = {
'desired': {'key': 'desired', 'type': 'DeviceTwinProperties'},
'reported': {'key': 'reported', 'type': 'DeviceTwinProperties'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfoProperties, self).__init__(**kwargs)
self.desired = kwargs.get('desired', None)
self.reported = kwargs.get('reported', None)
class DeviceTwinInfoX509Thumbprint(msrest.serialization.Model):
"""The thumbprint is a unique value for the x509 certificate, commonly used to find a particular certificate in a certificate store. The thumbprint is dynamically generated using the SHA1 algorithm, and does not physically exist in the certificate.
:param primary_thumbprint: Primary thumbprint for the x509 certificate.
:type primary_thumbprint: str
:param secondary_thumbprint: Secondary thumbprint for the x509 certificate.
:type secondary_thumbprint: str
"""
_attribute_map = {
'primary_thumbprint': {'key': 'primaryThumbprint', 'type': 'str'},
'secondary_thumbprint': {'key': 'secondaryThumbprint', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfoX509Thumbprint, self).__init__(**kwargs)
self.primary_thumbprint = kwargs.get('primary_thumbprint', None)
self.secondary_thumbprint = kwargs.get('secondary_thumbprint', None)
class DeviceTwinMetadata(msrest.serialization.Model):
"""Metadata information for the properties JSON document.
:param last_updated: The ISO8601 timestamp of the last time the properties were updated.
:type last_updated: str
"""
_attribute_map = {
'last_updated': {'key': 'lastUpdated', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinMetadata, self).__init__(**kwargs)
self.last_updated = kwargs.get('last_updated', None)
class DeviceTwinProperties(msrest.serialization.Model):
"""A portion of the properties that can be written only by the application back-end, and read by the device.
:param metadata: Metadata information for the properties JSON document.
:type metadata: ~event_grid_publisher_client.models.DeviceTwinMetadata
:param version: Version of device twin properties.
:type version: float
"""
_attribute_map = {
'metadata': {'key': 'metadata', 'type': 'DeviceTwinMetadata'},
'version': {'key': 'version', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinProperties, self).__init__(**kwargs)
self.metadata = kwargs.get('metadata', None)
self.version = kwargs.get('version', None)
class EventGridEvent(msrest.serialization.Model):
"""Properties of an event published to an Event Grid topic using the EventGrid Schema.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Required. An unique identifier for the event.
:type id: str
:param topic: The resource path of the event source.
:type topic: str
:param subject: Required. A resource path relative to the topic path.
:type subject: str
:param data: Required. Event data specific to the event type.
:type data: object
:param event_type: Required. The type of the event that occurred.
:type event_type: str
:param event_time: Required. The time (in UTC) the event was generated.
:type event_time: ~datetime.datetime
:ivar metadata_version: The schema version of the event metadata.
:vartype metadata_version: str
:param data_version: Required. The schema version of the data object.
:type data_version: str
"""
_validation = {
'id': {'required': True},
'subject': {'required': True},
'data': {'required': True},
'event_type': {'required': True},
'event_time': {'required': True},
'metadata_version': {'readonly': True},
'data_version': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'topic': {'key': 'topic', 'type': 'str'},
'subject': {'key': 'subject', 'type': 'str'},
'data': {'key': 'data', 'type': 'object'},
'event_type': {'key': 'eventType', 'type': 'str'},
'event_time': {'key': 'eventTime', 'type': 'iso-8601'},
'metadata_version': {'key': 'metadataVersion', 'type': 'str'},
'data_version': {'key': 'dataVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EventGridEvent, self).__init__(**kwargs)
self.id = kwargs['id']
self.topic = kwargs.get('topic', None)
self.subject = kwargs['subject']
self.data = kwargs['data']
self.event_type = kwargs['event_type']
self.event_time = kwargs['event_time']
self.metadata_version = None
self.data_version = kwargs['data_version']
class EventHubCaptureFileCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.EventHub.CaptureFileCreated event.
:param fileurl: The path to the capture file.
:type fileurl: str
:param file_type: The file type of the capture file.
:type file_type: str
:param partition_id: The shard ID.
:type partition_id: str
:param size_in_bytes: The file size.
:type size_in_bytes: int
:param event_count: The number of events in the file.
:type event_count: int
:param first_sequence_number: The smallest sequence number from the queue.
:type first_sequence_number: int
:param last_sequence_number: The last sequence number from the queue.
:type last_sequence_number: int
:param first_enqueue_time: The first time from the queue.
:type first_enqueue_time: ~datetime.datetime
:param last_enqueue_time: The last time from the queue.
:type last_enqueue_time: ~datetime.datetime
"""
_attribute_map = {
'fileurl': {'key': 'fileurl', 'type': 'str'},
'file_type': {'key': 'fileType', 'type': 'str'},
'partition_id': {'key': 'partitionId', 'type': 'str'},
'size_in_bytes': {'key': 'sizeInBytes', 'type': 'int'},
'event_count': {'key': 'eventCount', 'type': 'int'},
'first_sequence_number': {'key': 'firstSequenceNumber', 'type': 'int'},
'last_sequence_number': {'key': 'lastSequenceNumber', 'type': 'int'},
'first_enqueue_time': {'key': 'firstEnqueueTime', 'type': 'iso-8601'},
'last_enqueue_time': {'key': 'lastEnqueueTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(EventHubCaptureFileCreatedEventData, self).__init__(**kwargs)
self.fileurl = kwargs.get('fileurl', None)
self.file_type = kwargs.get('file_type', None)
self.partition_id = kwargs.get('partition_id', None)
self.size_in_bytes = kwargs.get('size_in_bytes', None)
self.event_count = kwargs.get('event_count', None)
self.first_sequence_number = kwargs.get('first_sequence_number', None)
self.last_sequence_number = kwargs.get('last_sequence_number', None)
self.first_enqueue_time = kwargs.get('first_enqueue_time', None)
self.last_enqueue_time = kwargs.get('last_enqueue_time', None)
class IotHubDeviceConnectedEventData(DeviceConnectionStateEventProperties):
"""Event data for Microsoft.Devices.DeviceConnected event.
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param module_id: The unique identifier of the module. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type module_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param device_connection_state_event_info: Information about the device connection state event.
:type device_connection_state_event_info:
~event_grid_publisher_client.models.DeviceConnectionStateEventInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceConnectedEventData, self).__init__(**kwargs)
class IotHubDeviceCreatedEventData(DeviceLifeCycleEventProperties):
"""Event data for Microsoft.Devices.DeviceCreated event.
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param twin: Information about the device twin, which is the cloud representation of
application device metadata.
:type twin: ~event_grid_publisher_client.models.DeviceTwinInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceCreatedEventData, self).__init__(**kwargs)
class IotHubDeviceDeletedEventData(DeviceLifeCycleEventProperties):
"""Event data for Microsoft.Devices.DeviceDeleted event.
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param twin: Information about the device twin, which is the cloud representation of
application device metadata.
:type twin: ~event_grid_publisher_client.models.DeviceTwinInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceDeletedEventData, self).__init__(**kwargs)
class IotHubDeviceDisconnectedEventData(DeviceConnectionStateEventProperties):
"""Event data for Microsoft.Devices.DeviceDisconnected event.
:param device_id: The unique identifier of the device. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type device_id: str
:param module_id: The unique identifier of the module. This case-sensitive string can be up to
128 characters long, and supports ASCII 7-bit alphanumeric characters plus the following
special characters: - : . + % _ # * ? ! ( ) , = @ ; $ '.
:type module_id: str
:param hub_name: Name of the IoT Hub where the device was created or deleted.
:type hub_name: str
:param device_connection_state_event_info: Information about the device connection state event.
:type device_connection_state_event_info:
~event_grid_publisher_client.models.DeviceConnectionStateEventInfo
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceDisconnectedEventData, self).__init__(**kwargs)
class IotHubDeviceTelemetryEventData(DeviceTelemetryEventProperties):
"""Event data for Microsoft.Devices.DeviceTelemetry event.
:param body: The content of the message from the device.
:type body: object
:param properties: Application properties are user-defined strings that can be added to the
message. These fields are optional.
:type properties: dict[str, str]
:param system_properties: System properties help identify contents and source of the messages.
:type system_properties: dict[str, str]
"""
_attribute_map = {
'body': {'key': 'body', 'type': 'object'},
'properties': {'key': 'properties', 'type': '{str}'},
'system_properties': {'key': 'systemProperties', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceTelemetryEventData, self).__init__(**kwargs)
class KeyVaultAccessPolicyChangedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.VaultAccessPolicyChanged event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultAccessPolicyChangedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateExpiredEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateExpired event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateNearExpiryEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNearExpiry event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateNewVersionCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNewVersionCreated event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyExpiredEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyExpired event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyNearExpiryEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNearExpiry event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyNewVersionCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNewVersionCreated event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretExpiredEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretExpired event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretNearExpiryEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNearExpiry event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretNewVersionCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNewVersionCreated event.
:param id: The id of the object that triggered this event.
:type id: str
:param vault_name: Key vault name of the object that triggered this event.
:type vault_name: str
:param object_type: The type of the object that triggered this event.
:type object_type: str
:param object_name: The name of the object that triggered this event.
:type object_name: str
:param version: The version of the object that triggered this event.
:type version: str
:param nbf: Not before date of the object that triggered this event.
:type nbf: float
:param exp: The expiration date of the object that triggered this event.
:type exp: float
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class MachineLearningServicesDatasetDriftDetectedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.DatasetDriftDetected event.
:param data_drift_id: The ID of the data drift monitor that triggered the event.
:type data_drift_id: str
:param data_drift_name: The name of the data drift monitor that triggered the event.
:type data_drift_name: str
:param run_id: The ID of the Run that detected data drift.
:type run_id: str
:param base_dataset_id: The ID of the base Dataset used to detect drift.
:type base_dataset_id: str
:param target_dataset_id: The ID of the target Dataset used to detect drift.
:type target_dataset_id: str
:param drift_coefficient: The coefficient result that triggered the event.
:type drift_coefficient: float
:param start_time: The start time of the target dataset time series that resulted in drift
detection.
:type start_time: ~datetime.datetime
:param end_time: The end time of the target dataset time series that resulted in drift
detection.
:type end_time: ~datetime.datetime
"""
_attribute_map = {
'data_drift_id': {'key': 'dataDriftId', 'type': 'str'},
'data_drift_name': {'key': 'dataDriftName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'base_dataset_id': {'key': 'baseDatasetId', 'type': 'str'},
'target_dataset_id': {'key': 'targetDatasetId', 'type': 'str'},
'drift_coefficient': {'key': 'driftCoefficient', 'type': 'float'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesDatasetDriftDetectedEventData, self).__init__(**kwargs)
self.data_drift_id = kwargs.get('data_drift_id', None)
self.data_drift_name = kwargs.get('data_drift_name', None)
self.run_id = kwargs.get('run_id', None)
self.base_dataset_id = kwargs.get('base_dataset_id', None)
self.target_dataset_id = kwargs.get('target_dataset_id', None)
self.drift_coefficient = kwargs.get('drift_coefficient', None)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
class MachineLearningServicesModelDeployedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelDeployed event.
:param service_name: The name of the deployed service.
:type service_name: str
:param service_compute_type: The compute type (e.g. ACI, AKS) of the deployed service.
:type service_compute_type: str
:param model_ids: A common separated list of model IDs. The IDs of the models deployed in the
service.
:type model_ids: str
:param service_tags: The tags of the deployed service.
:type service_tags: object
:param service_properties: The properties of the deployed service.
:type service_properties: object
"""
_attribute_map = {
'service_name': {'key': 'serviceName', 'type': 'str'},
'service_compute_type': {'key': 'serviceComputeType', 'type': 'str'},
'model_ids': {'key': 'modelIds', 'type': 'str'},
'service_tags': {'key': 'serviceTags', 'type': 'object'},
'service_properties': {'key': 'serviceProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesModelDeployedEventData, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.service_compute_type = kwargs.get('service_compute_type', None)
self.model_ids = kwargs.get('model_ids', None)
self.service_tags = kwargs.get('service_tags', None)
self.service_properties = kwargs.get('service_properties', None)
class MachineLearningServicesModelRegisteredEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelRegistered event.
:param model_name: The name of the model that was registered.
:type model_name: str
:param model_version: The version of the model that was registered.
:type model_version: str
:param model_tags: The tags of the model that was registered.
:type model_tags: object
:param model_properties: The properties of the model that was registered.
:type model_properties: object
"""
_attribute_map = {
'model_name': {'key': 'modelName', 'type': 'str'},
'model_version': {'key': 'modelVersion', 'type': 'str'},
'model_tags': {'key': 'modelTags', 'type': 'object'},
'model_properties': {'key': 'modelProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesModelRegisteredEventData, self).__init__(**kwargs)
self.model_name = kwargs.get('model_name', None)
self.model_version = kwargs.get('model_version', None)
self.model_tags = kwargs.get('model_tags', None)
self.model_properties = kwargs.get('model_properties', None)
class MachineLearningServicesRunCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunCompleted event.
:param experiment_id: The ID of the experiment that the run belongs to.
:type experiment_id: str
:param experiment_name: The name of the experiment that the run belongs to.
:type experiment_name: str
:param run_id: The ID of the Run that was completed.
:type run_id: str
:param run_type: The Run Type of the completed Run.
:type run_type: str
:param run_tags: The tags of the completed Run.
:type run_tags: object
:param run_properties: The properties of the completed Run.
:type run_properties: object
"""
_attribute_map = {
'experiment_id': {'key': 'experimentId', 'type': 'str'},
'experiment_name': {'key': 'experimentName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'run_type': {'key': 'runType', 'type': 'str'},
'run_tags': {'key': 'runTags', 'type': 'object'},
'run_properties': {'key': 'runProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesRunCompletedEventData, self).__init__(**kwargs)
self.experiment_id = kwargs.get('experiment_id', None)
self.experiment_name = kwargs.get('experiment_name', None)
self.run_id = kwargs.get('run_id', None)
self.run_type = kwargs.get('run_type', None)
self.run_tags = kwargs.get('run_tags', None)
self.run_properties = kwargs.get('run_properties', None)
class MachineLearningServicesRunStatusChangedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunStatusChanged event.
:param experiment_id: The ID of the experiment that the Machine Learning Run belongs to.
:type experiment_id: str
:param experiment_name: The name of the experiment that the Machine Learning Run belongs to.
:type experiment_name: str
:param run_id: The ID of the Machine Learning Run.
:type run_id: str
:param run_type: The Run Type of the Machine Learning Run.
:type run_type: str
:param run_tags: The tags of the Machine Learning Run.
:type run_tags: object
:param run_properties: The properties of the Machine Learning Run.
:type run_properties: object
:param run_status: The status of the Machine Learning Run.
:type run_status: str
"""
_attribute_map = {
'experiment_id': {'key': 'experimentId', 'type': 'str'},
'experiment_name': {'key': 'experimentName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'run_type': {'key': 'runType', 'type': 'str'},
'run_tags': {'key': 'runTags', 'type': 'object'},
'run_properties': {'key': 'runProperties', 'type': 'object'},
'run_status': {'key': 'runStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesRunStatusChangedEventData, self).__init__(**kwargs)
self.experiment_id = kwargs.get('experiment_id', None)
self.experiment_name = kwargs.get('experiment_name', None)
self.run_id = kwargs.get('run_id', None)
self.run_type = kwargs.get('run_type', None)
self.run_tags = kwargs.get('run_tags', None)
self.run_properties = kwargs.get('run_properties', None)
self.run_status = kwargs.get('run_status', None)
class MapsGeofenceEventProperties(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Geofence event (GeofenceEntered, GeofenceExited, GeofenceResult).
:param expired_geofence_geometry_id: Lists of the geometry ID of the geofence which is expired
relative to the user time in the request.
:type expired_geofence_geometry_id: list[str]
:param geometries: Lists the fence geometries that either fully contain the coordinate position
or have an overlap with the searchBuffer around the fence.
:type geometries: list[~event_grid_publisher_client.models.MapsGeofenceGeometry]
:param invalid_period_geofence_geometry_id: Lists of the geometry ID of the geofence which is
in invalid period relative to the user time in the request.
:type invalid_period_geofence_geometry_id: list[str]
:param is_event_published: True if at least one event is published to the Azure Maps event
subscriber, false if no event is published to the Azure Maps event subscriber.
:type is_event_published: bool
"""
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceEventProperties, self).__init__(**kwargs)
self.expired_geofence_geometry_id = kwargs.get('expired_geofence_geometry_id', None)
self.geometries = kwargs.get('geometries', None)
self.invalid_period_geofence_geometry_id = kwargs.get('invalid_period_geofence_geometry_id', None)
self.is_event_published = kwargs.get('is_event_published', None)
class MapsGeofenceEnteredEventData(MapsGeofenceEventProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceEntered event.
:param expired_geofence_geometry_id: Lists of the geometry ID of the geofence which is expired
relative to the user time in the request.
:type expired_geofence_geometry_id: list[str]
:param geometries: Lists the fence geometries that either fully contain the coordinate position
or have an overlap with the searchBuffer around the fence.
:type geometries: list[~event_grid_publisher_client.models.MapsGeofenceGeometry]
:param invalid_period_geofence_geometry_id: Lists of the geometry ID of the geofence which is
in invalid period relative to the user time in the request.
:type invalid_period_geofence_geometry_id: list[str]
:param is_event_published: True if at least one event is published to the Azure Maps event
subscriber, false if no event is published to the Azure Maps event subscriber.
:type is_event_published: bool
"""
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceEnteredEventData, self).__init__(**kwargs)
class MapsGeofenceExitedEventData(MapsGeofenceEventProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceExited event.
:param expired_geofence_geometry_id: Lists of the geometry ID of the geofence which is expired
relative to the user time in the request.
:type expired_geofence_geometry_id: list[str]
:param geometries: Lists the fence geometries that either fully contain the coordinate position
or have an overlap with the searchBuffer around the fence.
:type geometries: list[~event_grid_publisher_client.models.MapsGeofenceGeometry]
:param invalid_period_geofence_geometry_id: Lists of the geometry ID of the geofence which is
in invalid period relative to the user time in the request.
:type invalid_period_geofence_geometry_id: list[str]
:param is_event_published: True if at least one event is published to the Azure Maps event
subscriber, false if no event is published to the Azure Maps event subscriber.
:type is_event_published: bool
"""
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceExitedEventData, self).__init__(**kwargs)
class MapsGeofenceGeometry(msrest.serialization.Model):
"""The geofence geometry.
:param device_id: ID of the device.
:type device_id: str
:param distance: Distance from the coordinate to the closest border of the geofence. Positive
means the coordinate is outside of the geofence. If the coordinate is outside of the geofence,
but more than the value of searchBuffer away from the closest geofence border, then the value
is 999. Negative means the coordinate is inside of the geofence. If the coordinate is inside
the polygon, but more than the value of searchBuffer away from the closest geofencing
border,then the value is -999. A value of 999 means that there is great confidence the
coordinate is well outside the geofence. A value of -999 means that there is great confidence
the coordinate is well within the geofence.
:type distance: float
:param geometry_id: The unique ID for the geofence geometry.
:type geometry_id: str
:param nearest_lat: Latitude of the nearest point of the geometry.
:type nearest_lat: float
:param nearest_lon: Longitude of the nearest point of the geometry.
:type nearest_lon: float
:param ud_id: The unique id returned from user upload service when uploading a geofence. Will
not be included in geofencing post API.
:type ud_id: str
"""
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'distance': {'key': 'distance', 'type': 'float'},
'geometry_id': {'key': 'geometryId', 'type': 'str'},
'nearest_lat': {'key': 'nearestLat', 'type': 'float'},
'nearest_lon': {'key': 'nearestLon', 'type': 'float'},
'ud_id': {'key': 'udId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceGeometry, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.distance = kwargs.get('distance', None)
self.geometry_id = kwargs.get('geometry_id', None)
self.nearest_lat = kwargs.get('nearest_lat', None)
self.nearest_lon = kwargs.get('nearest_lon', None)
self.ud_id = kwargs.get('ud_id', None)
class MapsGeofenceResultEventData(MapsGeofenceEventProperties):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceResult event.
:param expired_geofence_geometry_id: Lists of the geometry ID of the geofence which is expired
relative to the user time in the request.
:type expired_geofence_geometry_id: list[str]
:param geometries: Lists the fence geometries that either fully contain the coordinate position
or have an overlap with the searchBuffer around the fence.
:type geometries: list[~event_grid_publisher_client.models.MapsGeofenceGeometry]
:param invalid_period_geofence_geometry_id: Lists of the geometry ID of the geofence which is
in invalid period relative to the user time in the request.
:type invalid_period_geofence_geometry_id: list[str]
:param is_event_published: True if at least one event is published to the Azure Maps event
subscriber, false if no event is published to the Azure Maps event subscriber.
:type is_event_published: bool
"""
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceResultEventData, self).__init__(**kwargs)
class MediaJobStateChangeEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Media.JobStateChange event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobStateChangeEventData, self).__init__(**kwargs)
self.previous_state = None
self.state = None
self.correlation_data = kwargs.get('correlation_data', None)
class MediaJobCanceledEventData(MediaJobStateChangeEventData):
"""Job canceled event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobCanceled event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
:param outputs: Gets the Job outputs.
:type outputs: list[~event_grid_publisher_client.models.MediaJobOutput]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobCanceledEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobCancelingEventData(MediaJobStateChangeEventData):
"""Job canceling event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobCanceling event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobCancelingEventData, self).__init__(**kwargs)
class MediaJobError(msrest.serialization.Model):
"""Details of JobOutput errors.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: Error code describing the error. Possible values include: "ServiceError",
"ServiceTransientError", "DownloadNotAccessible", "DownloadTransientError",
"UploadNotAccessible", "UploadTransientError", "ConfigurationUnsupported", "ContentMalformed",
"ContentUnsupported".
:vartype code: str or ~event_grid_publisher_client.models.MediaJobErrorCode
:ivar message: A human-readable language-dependent representation of the error.
:vartype message: str
:ivar category: Helps with categorization of errors. Possible values include: "Service",
"Download", "Upload", "Configuration", "Content".
:vartype category: str or ~event_grid_publisher_client.models.MediaJobErrorCategory
:ivar retry: Indicates that it may be possible to retry the Job. If retry is unsuccessful,
please contact Azure support via Azure Portal. Possible values include: "DoNotRetry",
"MayRetry".
:vartype retry: str or ~event_grid_publisher_client.models.MediaJobRetry
:ivar details: An array of details about specific errors that led to this reported error.
:vartype details: list[~event_grid_publisher_client.models.MediaJobErrorDetail]
"""
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
'category': {'readonly': True},
'retry': {'readonly': True},
'details': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'category': {'key': 'category', 'type': 'str'},
'retry': {'key': 'retry', 'type': 'str'},
'details': {'key': 'details', 'type': '[MediaJobErrorDetail]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobError, self).__init__(**kwargs)
self.code = None
self.message = None
self.category = None
self.retry = None
self.details = None
class MediaJobErrorDetail(msrest.serialization.Model):
"""Details of JobOutput errors.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: Code describing the error detail.
:vartype code: str
:ivar message: A human-readable representation of the error.
:vartype message: str
"""
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaJobErrorDetail, self).__init__(**kwargs)
self.code = None
self.message = None
class MediaJobErroredEventData(MediaJobStateChangeEventData):
"""Job error state event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobErrored event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
:param outputs: Gets the Job outputs.
:type outputs: list[~event_grid_publisher_client.models.MediaJobOutput]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobErroredEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobFinishedEventData(MediaJobStateChangeEventData):
"""Job finished event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobFinished event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
:param outputs: Gets the Job outputs.
:type outputs: list[~event_grid_publisher_client.models.MediaJobOutput]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobFinishedEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobOutput(msrest.serialization.Model):
"""The event data for a Job output.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: MediaJobOutputAsset.
All required parameters must be populated in order to send to Azure.
:param odata_type: The discriminator for derived types.Constant filled by server.
:type odata_type: str
:param error: Gets the Job output error.
:type error: ~event_grid_publisher_client.models.MediaJobError
:param label: Gets the Job output label.
:type label: str
:param progress: Required. Gets the Job output progress.
:type progress: long
:param state: Required. Gets the Job output state. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:type state: str or ~event_grid_publisher_client.models.MediaJobState
"""
_validation = {
'progress': {'required': True},
'state': {'required': True},
}
_attribute_map = {
'odata_type': {'key': '@odata\\.type', 'type': 'str'},
'error': {'key': 'error', 'type': 'MediaJobError'},
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'state': {'key': 'state', 'type': 'str'},
}
_subtype_map = {
'odata_type': {'#Microsoft.Media.JobOutputAsset': 'MediaJobOutputAsset'}
}
def __init__(
self,
**kwargs
):
super(MediaJobOutput, self).__init__(**kwargs)
self.odata_type = None # type: Optional[str]
self.error = kwargs.get('error', None)
self.label = kwargs.get('label', None)
self.progress = kwargs['progress']
self.state = kwargs['state']
class MediaJobOutputAsset(MediaJobOutput):
"""The event data for a Job output asset.
All required parameters must be populated in order to send to Azure.
:param odata_type: The discriminator for derived types.Constant filled by server.
:type odata_type: str
:param error: Gets the Job output error.
:type error: ~event_grid_publisher_client.models.MediaJobError
:param label: Gets the Job output label.
:type label: str
:param progress: Required. Gets the Job output progress.
:type progress: long
:param state: Required. Gets the Job output state. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:type state: str or ~event_grid_publisher_client.models.MediaJobState
:param asset_name: Gets the Job output asset name.
:type asset_name: str
"""
_validation = {
'progress': {'required': True},
'state': {'required': True},
}
_attribute_map = {
'odata_type': {'key': '@odata\\.type', 'type': 'str'},
'error': {'key': 'error', 'type': 'MediaJobError'},
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'state': {'key': 'state', 'type': 'str'},
'asset_name': {'key': 'assetName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputAsset, self).__init__(**kwargs)
self.odata_type = '#Microsoft.Media.JobOutputAsset' # type: str
self.asset_name = kwargs.get('asset_name', None)
class MediaJobOutputStateChangeEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Media.JobOutputStateChange event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputStateChangeEventData, self).__init__(**kwargs)
self.previous_state = None
self.output = kwargs.get('output', None)
self.job_correlation_data = kwargs.get('job_correlation_data', None)
class MediaJobOutputCanceledEventData(MediaJobOutputStateChangeEventData):
"""Job output canceled event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputCanceled event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputCanceledEventData, self).__init__(**kwargs)
class MediaJobOutputCancelingEventData(MediaJobOutputStateChangeEventData):
"""Job output canceling event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputCanceling event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputCancelingEventData, self).__init__(**kwargs)
class MediaJobOutputErroredEventData(MediaJobOutputStateChangeEventData):
"""Job output error event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputErrored event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputErroredEventData, self).__init__(**kwargs)
class MediaJobOutputFinishedEventData(MediaJobOutputStateChangeEventData):
"""Job output finished event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputFinished event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputFinishedEventData, self).__init__(**kwargs)
class MediaJobOutputProcessingEventData(MediaJobOutputStateChangeEventData):
"""Job output processing event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputProcessing event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputProcessingEventData, self).__init__(**kwargs)
class MediaJobOutputProgressEventData(msrest.serialization.Model):
"""Job Output Progress Event Data. Schema of the Data property of an EventGridEvent for a Microsoft.Media.JobOutputProgress event.
:param label: Gets the Job output label.
:type label: str
:param progress: Gets the Job output progress.
:type progress: long
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_attribute_map = {
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputProgressEventData, self).__init__(**kwargs)
self.label = kwargs.get('label', None)
self.progress = kwargs.get('progress', None)
self.job_correlation_data = kwargs.get('job_correlation_data', None)
class MediaJobOutputScheduledEventData(MediaJobOutputStateChangeEventData):
"""Job output scheduled event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobOutputScheduled event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:param output: Gets the output.
:type output: ~event_grid_publisher_client.models.MediaJobOutput
:param job_correlation_data: Gets the Job correlation data.
:type job_correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputScheduledEventData, self).__init__(**kwargs)
class MediaJobProcessingEventData(MediaJobStateChangeEventData):
"""Job processing event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobProcessing event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobProcessingEventData, self).__init__(**kwargs)
class MediaJobScheduledEventData(MediaJobStateChangeEventData):
"""Job scheduled event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.JobScheduled event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar previous_state: The previous state of the Job. Possible values include: "Canceled",
"Canceling", "Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype previous_state: str or ~event_grid_publisher_client.models.MediaJobState
:ivar state: The new state of the Job. Possible values include: "Canceled", "Canceling",
"Error", "Finished", "Processing", "Queued", "Scheduled".
:vartype state: str or ~event_grid_publisher_client.models.MediaJobState
:param correlation_data: Gets the Job correlation data.
:type correlation_data: dict[str, str]
"""
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobScheduledEventData, self).__init__(**kwargs)
class MediaLiveEventConnectionRejectedEventData(msrest.serialization.Model):
"""Encoder connection rejected event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventConnectionRejected event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar ingest_url: Gets the ingest URL provided by the live event.
:vartype ingest_url: str
:ivar stream_id: Gets the stream Id.
:vartype stream_id: str
:ivar encoder_ip: Gets the remote IP.
:vartype encoder_ip: str
:ivar encoder_port: Gets the remote port.
:vartype encoder_port: str
:ivar result_code: Gets the result code.
:vartype result_code: str
"""
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'result_code': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventConnectionRejectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
self.result_code = None
class MediaLiveEventEncoderConnectedEventData(msrest.serialization.Model):
"""Encoder connect event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventEncoderConnected event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar ingest_url: Gets the ingest URL provided by the live event.
:vartype ingest_url: str
:ivar stream_id: Gets the stream Id.
:vartype stream_id: str
:ivar encoder_ip: Gets the remote IP.
:vartype encoder_ip: str
:ivar encoder_port: Gets the remote port.
:vartype encoder_port: str
"""
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventEncoderConnectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
class MediaLiveEventEncoderDisconnectedEventData(msrest.serialization.Model):
"""Encoder disconnected event data. Schema of the Data property of an EventGridEvent for a Microsoft.Media.LiveEventEncoderDisconnected event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar ingest_url: Gets the ingest URL provided by the live event.
:vartype ingest_url: str
:ivar stream_id: Gets the stream Id.
:vartype stream_id: str
:ivar encoder_ip: Gets the remote IP.
:vartype encoder_ip: str
:ivar encoder_port: Gets the remote port.
:vartype encoder_port: str
:ivar result_code: Gets the result code.
:vartype result_code: str
"""
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'result_code': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventEncoderDisconnectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
self.result_code = None
class MediaLiveEventIncomingDataChunkDroppedEventData(msrest.serialization.Model):
"""Ingest fragment dropped event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventIncomingDataChunkDropped event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar timestamp: Gets the timestamp of the data chunk dropped.
:vartype timestamp: str
:ivar track_type: Gets the type of the track (Audio / Video).
:vartype track_type: str
:ivar bitrate: Gets the bitrate of the track.
:vartype bitrate: long
:ivar timescale: Gets the timescale of the Timestamp.
:vartype timescale: str
:ivar result_code: Gets the result code for fragment drop operation.
:vartype result_code: str
:ivar track_name: Gets the name of the track for which fragment is dropped.
:vartype track_name: str
"""
_validation = {
'timestamp': {'readonly': True},
'track_type': {'readonly': True},
'bitrate': {'readonly': True},
'timescale': {'readonly': True},
'result_code': {'readonly': True},
'track_name': {'readonly': True},
}
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'str'},
'track_type': {'key': 'trackType', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'timescale': {'key': 'timescale', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingDataChunkDroppedEventData, self).__init__(**kwargs)
self.timestamp = None
self.track_type = None
self.bitrate = None
self.timescale = None
self.result_code = None
self.track_name = None
class MediaLiveEventIncomingStreamReceivedEventData(msrest.serialization.Model):
"""Encoder connect event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventIncomingStreamReceived event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar ingest_url: Gets the ingest URL provided by the live event.
:vartype ingest_url: str
:ivar track_type: Gets the type of the track (Audio / Video).
:vartype track_type: str
:ivar track_name: Gets the track name.
:vartype track_name: str
:ivar bitrate: Gets the bitrate of the track.
:vartype bitrate: long
:ivar encoder_ip: Gets the remote IP.
:vartype encoder_ip: str
:ivar encoder_port: Gets the remote port.
:vartype encoder_port: str
:ivar timestamp: Gets the first timestamp of the data chunk received.
:vartype timestamp: str
:ivar duration: Gets the duration of the first data chunk.
:vartype duration: str
:ivar timescale: Gets the timescale in which timestamp is represented.
:vartype timescale: str
"""
_validation = {
'ingest_url': {'readonly': True},
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'timestamp': {'readonly': True},
'duration': {'readonly': True},
'timescale': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'str'},
'duration': {'key': 'duration', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingStreamReceivedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.track_type = None
self.track_name = None
self.bitrate = None
self.encoder_ip = None
self.encoder_port = None
self.timestamp = None
self.duration = None
self.timescale = None
class MediaLiveEventIncomingStreamsOutOfSyncEventData(msrest.serialization.Model):
"""Incoming streams out of sync event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventIncomingStreamsOutOfSync event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar min_last_timestamp: Gets the minimum last timestamp received.
:vartype min_last_timestamp: str
:ivar type_of_stream_with_min_last_timestamp: Gets the type of stream with minimum last
timestamp.
:vartype type_of_stream_with_min_last_timestamp: str
:ivar max_last_timestamp: Gets the maximum timestamp among all the tracks (audio or video).
:vartype max_last_timestamp: str
:ivar type_of_stream_with_max_last_timestamp: Gets the type of stream with maximum last
timestamp.
:vartype type_of_stream_with_max_last_timestamp: str
:ivar timescale_of_min_last_timestamp: Gets the timescale in which "MinLastTimestamp" is
represented.
:vartype timescale_of_min_last_timestamp: str
:ivar timescale_of_max_last_timestamp: Gets the timescale in which "MaxLastTimestamp" is
represented.
:vartype timescale_of_max_last_timestamp: str
"""
_validation = {
'min_last_timestamp': {'readonly': True},
'type_of_stream_with_min_last_timestamp': {'readonly': True},
'max_last_timestamp': {'readonly': True},
'type_of_stream_with_max_last_timestamp': {'readonly': True},
'timescale_of_min_last_timestamp': {'readonly': True},
'timescale_of_max_last_timestamp': {'readonly': True},
}
_attribute_map = {
'min_last_timestamp': {'key': 'minLastTimestamp', 'type': 'str'},
'type_of_stream_with_min_last_timestamp': {'key': 'typeOfStreamWithMinLastTimestamp', 'type': 'str'},
'max_last_timestamp': {'key': 'maxLastTimestamp', 'type': 'str'},
'type_of_stream_with_max_last_timestamp': {'key': 'typeOfStreamWithMaxLastTimestamp', 'type': 'str'},
'timescale_of_min_last_timestamp': {'key': 'timescaleOfMinLastTimestamp', 'type': 'str'},
'timescale_of_max_last_timestamp': {'key': 'timescaleOfMaxLastTimestamp', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingStreamsOutOfSyncEventData, self).__init__(**kwargs)
self.min_last_timestamp = None
self.type_of_stream_with_min_last_timestamp = None
self.max_last_timestamp = None
self.type_of_stream_with_max_last_timestamp = None
self.timescale_of_min_last_timestamp = None
self.timescale_of_max_last_timestamp = None
class MediaLiveEventIncomingVideoStreamsOutOfSyncEventData(msrest.serialization.Model):
"""Incoming video stream out of synch event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar first_timestamp: Gets the first timestamp received for one of the quality levels.
:vartype first_timestamp: str
:ivar first_duration: Gets the duration of the data chunk with first timestamp.
:vartype first_duration: str
:ivar second_timestamp: Gets the timestamp received for some other quality levels.
:vartype second_timestamp: str
:ivar second_duration: Gets the duration of the data chunk with second timestamp.
:vartype second_duration: str
:ivar timescale: Gets the timescale in which both the timestamps and durations are represented.
:vartype timescale: str
"""
_validation = {
'first_timestamp': {'readonly': True},
'first_duration': {'readonly': True},
'second_timestamp': {'readonly': True},
'second_duration': {'readonly': True},
'timescale': {'readonly': True},
}
_attribute_map = {
'first_timestamp': {'key': 'firstTimestamp', 'type': 'str'},
'first_duration': {'key': 'firstDuration', 'type': 'str'},
'second_timestamp': {'key': 'secondTimestamp', 'type': 'str'},
'second_duration': {'key': 'secondDuration', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingVideoStreamsOutOfSyncEventData, self).__init__(**kwargs)
self.first_timestamp = None
self.first_duration = None
self.second_timestamp = None
self.second_duration = None
self.timescale = None
class MediaLiveEventIngestHeartbeatEventData(msrest.serialization.Model):
"""Ingest fragment dropped event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventIngestHeartbeat event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar track_type: Gets the type of the track (Audio / Video).
:vartype track_type: str
:ivar track_name: Gets the track name.
:vartype track_name: str
:ivar bitrate: Gets the bitrate of the track.
:vartype bitrate: long
:ivar incoming_bitrate: Gets the incoming bitrate.
:vartype incoming_bitrate: long
:ivar last_timestamp: Gets the last timestamp.
:vartype last_timestamp: str
:ivar timescale: Gets the timescale of the last timestamp.
:vartype timescale: str
:ivar overlap_count: Gets the fragment Overlap count.
:vartype overlap_count: long
:ivar discontinuity_count: Gets the fragment Discontinuity count.
:vartype discontinuity_count: long
:ivar nonincreasing_count: Gets Non increasing count.
:vartype nonincreasing_count: long
:ivar unexpected_bitrate: Gets a value indicating whether unexpected bitrate is present or not.
:vartype unexpected_bitrate: bool
:ivar state: Gets the state of the live event.
:vartype state: str
:ivar healthy: Gets a value indicating whether preview is healthy or not.
:vartype healthy: bool
"""
_validation = {
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'incoming_bitrate': {'readonly': True},
'last_timestamp': {'readonly': True},
'timescale': {'readonly': True},
'overlap_count': {'readonly': True},
'discontinuity_count': {'readonly': True},
'nonincreasing_count': {'readonly': True},
'unexpected_bitrate': {'readonly': True},
'state': {'readonly': True},
'healthy': {'readonly': True},
}
_attribute_map = {
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'incoming_bitrate': {'key': 'incomingBitrate', 'type': 'long'},
'last_timestamp': {'key': 'lastTimestamp', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
'overlap_count': {'key': 'overlapCount', 'type': 'long'},
'discontinuity_count': {'key': 'discontinuityCount', 'type': 'long'},
'nonincreasing_count': {'key': 'nonincreasingCount', 'type': 'long'},
'unexpected_bitrate': {'key': 'unexpectedBitrate', 'type': 'bool'},
'state': {'key': 'state', 'type': 'str'},
'healthy': {'key': 'healthy', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIngestHeartbeatEventData, self).__init__(**kwargs)
self.track_type = None
self.track_name = None
self.bitrate = None
self.incoming_bitrate = None
self.last_timestamp = None
self.timescale = None
self.overlap_count = None
self.discontinuity_count = None
self.nonincreasing_count = None
self.unexpected_bitrate = None
self.state = None
self.healthy = None
class MediaLiveEventTrackDiscontinuityDetectedEventData(msrest.serialization.Model):
"""Ingest track discontinuity detected event data. Schema of the data property of an EventGridEvent for a Microsoft.Media.LiveEventTrackDiscontinuityDetected event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar track_type: Gets the type of the track (Audio / Video).
:vartype track_type: str
:ivar track_name: Gets the track name.
:vartype track_name: str
:ivar bitrate: Gets the bitrate.
:vartype bitrate: long
:ivar previous_timestamp: Gets the timestamp of the previous fragment.
:vartype previous_timestamp: str
:ivar new_timestamp: Gets the timestamp of the current fragment.
:vartype new_timestamp: str
:ivar timescale: Gets the timescale in which both timestamps and discontinuity gap are
represented.
:vartype timescale: str
:ivar discontinuity_gap: Gets the discontinuity gap between PreviousTimestamp and NewTimestamp.
:vartype discontinuity_gap: str
"""
_validation = {
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'previous_timestamp': {'readonly': True},
'new_timestamp': {'readonly': True},
'timescale': {'readonly': True},
'discontinuity_gap': {'readonly': True},
}
_attribute_map = {
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'previous_timestamp': {'key': 'previousTimestamp', 'type': 'str'},
'new_timestamp': {'key': 'newTimestamp', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
'discontinuity_gap': {'key': 'discontinuityGap', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventTrackDiscontinuityDetectedEventData, self).__init__(**kwargs)
self.track_type = None
self.track_name = None
self.bitrate = None
self.previous_timestamp = None
self.new_timestamp = None
self.timescale = None
self.discontinuity_gap = None
class MicrosoftTeamsUserIdentifierModel(msrest.serialization.Model):
"""A Microsoft Teams user.
All required parameters must be populated in order to send to Azure.
:param user_id: Required. The Id of the Microsoft Teams user. If not anonymous, this is the AAD
object Id of the user.
:type user_id: str
:param is_anonymous: True if the Microsoft Teams user is anonymous. By default false if
missing.
:type is_anonymous: bool
:param cloud: The cloud that the Microsoft Teams user belongs to. By default 'public' if
missing. Possible values include: "public", "dod", "gcch".
:type cloud: str or ~event_grid_publisher_client.models.CommunicationCloudEnvironmentModel
"""
_validation = {
'user_id': {'required': True},
}
_attribute_map = {
'user_id': {'key': 'userId', 'type': 'str'},
'is_anonymous': {'key': 'isAnonymous', 'type': 'bool'},
'cloud': {'key': 'cloud', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MicrosoftTeamsUserIdentifierModel, self).__init__(**kwargs)
self.user_id = kwargs['user_id']
self.is_anonymous = kwargs.get('is_anonymous', None)
self.cloud = kwargs.get('cloud', None)
class PhoneNumberIdentifierModel(msrest.serialization.Model):
"""A phone number.
All required parameters must be populated in order to send to Azure.
:param value: Required. The phone number in E.164 format.
:type value: str
"""
_validation = {
'value': {'required': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PhoneNumberIdentifierModel, self).__init__(**kwargs)
self.value = kwargs['value']
class RedisExportRDBCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ExportRDBCompleted event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param name: The name of this event.
:type name: str
:param status: The status of this event. Failed or succeeded.
:type status: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisExportRDBCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisImportRDBCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ImportRDBCompleted event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param name: The name of this event.
:type name: str
:param status: The status of this event. Failed or succeeded.
:type status: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisImportRDBCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisPatchingCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Cache.PatchingCompleted event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param name: The name of this event.
:type name: str
:param status: The status of this event. Failed or succeeded.
:type status: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisPatchingCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisScalingCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ScalingCompleted event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param name: The name of this event.
:type name: str
:param status: The status of this event. Failed or succeeded.
:type status: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisScalingCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class ResourceActionCancelData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionCancel event. This is raised when a resource action operation is canceled.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceActionFailureData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionFailure event. This is raised when a resource action operation fails.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceActionSuccessData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionSuccess event. This is raised when a resource action operation succeeds.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteCancelData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteCancel event. This is raised when a resource delete operation is canceled.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteFailureData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteFailure event. This is raised when a resource delete operation fails.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteSuccessData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteSuccess event. This is raised when a resource delete operation succeeds.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteCancelData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteCancel event. This is raised when a resource create or update operation is canceled.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteFailureData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteFailure event. This is raised when a resource create or update operation fails.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteSuccessData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteSuccess event. This is raised when a resource create or update operation succeeds.
:param tenant_id: The tenant ID of the resource.
:type tenant_id: str
:param subscription_id: The subscription ID of the resource.
:type subscription_id: str
:param resource_group: The resource group of the resource.
:type resource_group: str
:param resource_provider: The resource provider performing the operation.
:type resource_provider: str
:param resource_uri: The URI of the resource in the operation.
:type resource_uri: str
:param operation_name: The operation that was performed.
:type operation_name: str
:param status: The status of the operation.
:type status: str
:param authorization: The requested authorization for the operation.
:type authorization: str
:param claims: The properties of the claims.
:type claims: str
:param correlation_id: An operation ID used for troubleshooting.
:type correlation_id: str
:param http_request: The details of the operation.
:type http_request: str
"""
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications event.
:param namespace_name: The namespace name of the Microsoft.ServiceBus resource.
:type namespace_name: str
:param request_uri: The endpoint of the Microsoft.ServiceBus resource.
:type request_uri: str
:param entity_type: The entity type of the Microsoft.ServiceBus resource. Could be one of
'queue' or 'subscriber'.
:type entity_type: str
:param queue_name: The name of the Microsoft.ServiceBus queue. If the entity type is of type
'subscriber', then this value will be null.
:type queue_name: str
:param topic_name: The name of the Microsoft.ServiceBus topic. If the entity type is of type
'queue', then this value will be null.
:type topic_name: str
:param subscription_name: The name of the Microsoft.ServiceBus topic's subscription. If the
entity type is of type 'queue', then this value will be null.
:type subscription_name: str
"""
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusActiveMessagesAvailableWithNoListenersEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners event.
:param namespace_name: The namespace name of the Microsoft.ServiceBus resource.
:type namespace_name: str
:param request_uri: The endpoint of the Microsoft.ServiceBus resource.
:type request_uri: str
:param entity_type: The entity type of the Microsoft.ServiceBus resource. Could be one of
'queue' or 'subscriber'.
:type entity_type: str
:param queue_name: The name of the Microsoft.ServiceBus queue. If the entity type is of type
'subscriber', then this value will be null.
:type queue_name: str
:param topic_name: The name of the Microsoft.ServiceBus topic. If the entity type is of type
'queue', then this value will be null.
:type topic_name: str
:param subscription_name: The name of the Microsoft.ServiceBus topic's subscription. If the
entity type is of type 'queue', then this value will be null.
:type subscription_name: str
"""
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusActiveMessagesAvailableWithNoListenersEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications event.
:param namespace_name: The namespace name of the Microsoft.ServiceBus resource.
:type namespace_name: str
:param request_uri: The endpoint of the Microsoft.ServiceBus resource.
:type request_uri: str
:param entity_type: The entity type of the Microsoft.ServiceBus resource. Could be one of
'queue' or 'subscriber'.
:type entity_type: str
:param queue_name: The name of the Microsoft.ServiceBus queue. If the entity type is of type
'subscriber', then this value will be null.
:type queue_name: str
:param topic_name: The name of the Microsoft.ServiceBus topic. If the entity type is of type
'queue', then this value will be null.
:type topic_name: str
:param subscription_name: The name of the Microsoft.ServiceBus topic's subscription. If the
entity type is of type 'queue', then this value will be null.
:type subscription_name: str
"""
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusDeadletterMessagesAvailableWithNoListenersEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListenersEvent event.
:param namespace_name: The namespace name of the Microsoft.ServiceBus resource.
:type namespace_name: str
:param request_uri: The endpoint of the Microsoft.ServiceBus resource.
:type request_uri: str
:param entity_type: The entity type of the Microsoft.ServiceBus resource. Could be one of
'queue' or 'subscriber'.
:type entity_type: str
:param queue_name: The name of the Microsoft.ServiceBus queue. If the entity type is of type
'subscriber', then this value will be null.
:type queue_name: str
:param topic_name: The name of the Microsoft.ServiceBus topic. If the entity type is of type
'queue', then this value will be null.
:type topic_name: str
:param subscription_name: The name of the Microsoft.ServiceBus topic's subscription. If the
entity type is of type 'queue', then this value will be null.
:type subscription_name: str
"""
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusDeadletterMessagesAvailableWithNoListenersEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class SignalRServiceClientConnectionConnectedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionConnected event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param hub_name: The hub of connected client connection.
:type hub_name: str
:param connection_id: The connection Id of connected client connection.
:type connection_id: str
:param user_id: The user Id of connected client connection.
:type user_id: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'connection_id': {'key': 'connectionId', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SignalRServiceClientConnectionConnectedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.hub_name = kwargs.get('hub_name', None)
self.connection_id = kwargs.get('connection_id', None)
self.user_id = kwargs.get('user_id', None)
class SignalRServiceClientConnectionDisconnectedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionDisconnected event.
:param timestamp: The time at which the event occurred.
:type timestamp: ~datetime.datetime
:param hub_name: The hub of connected client connection.
:type hub_name: str
:param connection_id: The connection Id of connected client connection.
:type connection_id: str
:param user_id: The user Id of connected client connection.
:type user_id: str
:param error_message: The message of error that cause the client connection disconnected.
:type error_message: str
"""
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'connection_id': {'key': 'connectionId', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'},
'error_message': {'key': 'errorMessage', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SignalRServiceClientConnectionDisconnectedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.hub_name = kwargs.get('hub_name', None)
self.connection_id = kwargs.get('connection_id', None)
self.user_id = kwargs.get('user_id', None)
self.error_message = kwargs.get('error_message', None)
class StorageAsyncOperationInitiatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.AsyncOperationInitiated event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the Storage service for the storage API
operation that triggered this event.
:type request_id: str
:param content_type: The content type of the blob. This is the same as what would be returned
in the Content-Type header from the blob.
:type content_type: str
:param content_length: The size of the blob in bytes. This is the same as what would be
returned in the Content-Length header from the blob.
:type content_length: long
:param blob_type: The type of blob.
:type blob_type: str
:param url: The path to the blob.
:type url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular blob name. Users can use standard string comparison to understand the relative
sequence of two events on the same blob name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageAsyncOperationInitiatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobCreated event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the Storage service for the storage API
operation that triggered this event.
:type request_id: str
:param e_tag: The etag of the blob at the time this event was triggered.
:type e_tag: str
:param content_type: The content type of the blob. This is the same as what would be returned
in the Content-Type header from the blob.
:type content_type: str
:param content_length: The size of the blob in bytes. This is the same as what would be
returned in the Content-Length header from the blob.
:type content_length: long
:param content_offset: The offset of the blob in bytes.
:type content_offset: long
:param blob_type: The type of blob.
:type blob_type: str
:param url: The path to the blob.
:type url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular blob name. Users can use standard string comparison to understand the relative
sequence of two events on the same blob name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'e_tag': {'key': 'eTag', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'content_offset': {'key': 'contentOffset', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobCreatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.e_tag = kwargs.get('e_tag', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.content_offset = kwargs.get('content_offset', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobDeletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobDeleted event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the Storage service for the storage API
operation that triggered this event.
:type request_id: str
:param content_type: The content type of the blob. This is the same as what would be returned
in the Content-Type header from the blob.
:type content_type: str
:param blob_type: The type of blob.
:type blob_type: str
:param url: The path to the blob.
:type url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular blob name. Users can use standard string comparison to understand the relative
sequence of two events on the same blob name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobDeletedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobRenamedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobRenamed event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the storage service for the storage API
operation that triggered this event.
:type request_id: str
:param source_url: The path to the blob that was renamed.
:type source_url: str
:param destination_url: The new path to the blob after the rename operation.
:type destination_url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular blob name. Users can use standard string comparison to understand the relative
sequence of two events on the same blob name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'source_url': {'key': 'sourceUrl', 'type': 'str'},
'destination_url': {'key': 'destinationUrl', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobRenamedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.source_url = kwargs.get('source_url', None)
self.destination_url = kwargs.get('destination_url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobTierChangedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobTierChanged event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the Storage service for the storage API
operation that triggered this event.
:type request_id: str
:param content_type: The content type of the blob. This is the same as what would be returned
in the Content-Type header from the blob.
:type content_type: str
:param content_length: The size of the blob in bytes. This is the same as what would be
returned in the Content-Length header from the blob.
:type content_length: long
:param blob_type: The type of blob.
:type blob_type: str
:param url: The path to the blob.
:type url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular blob name. Users can use standard string comparison to understand the relative
sequence of two events on the same blob name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobTierChangedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryCreatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryCreated event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the storage service for the storage API
operation that triggered this event.
:type request_id: str
:param e_tag: The etag of the directory at the time this event was triggered.
:type e_tag: str
:param url: The path to the directory.
:type url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular directory name. Users can use standard string comparison to understand the relative
sequence of two events on the same directory name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'e_tag': {'key': 'eTag', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryCreatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.e_tag = kwargs.get('e_tag', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryDeletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryDeleted event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the storage service for the storage API
operation that triggered this event.
:type request_id: str
:param url: The path to the deleted directory.
:type url: str
:param recursive: Is this event for a recursive delete operation.
:type recursive: bool
:param sequencer: An opaque string value representing the logical sequence of events for any
particular directory name. Users can use standard string comparison to understand the relative
sequence of two events on the same directory name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'recursive': {'key': 'recursive', 'type': 'bool'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryDeletedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.url = kwargs.get('url', None)
self.recursive = kwargs.get('recursive', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryRenamedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryRenamed event.
:param api: The name of the API/operation that triggered this event.
:type api: str
:param client_request_id: A request id provided by the client of the storage API operation that
triggered this event.
:type client_request_id: str
:param request_id: The request id generated by the storage service for the storage API
operation that triggered this event.
:type request_id: str
:param source_url: The path to the directory that was renamed.
:type source_url: str
:param destination_url: The new path to the directory after the rename operation.
:type destination_url: str
:param sequencer: An opaque string value representing the logical sequence of events for any
particular directory name. Users can use standard string comparison to understand the relative
sequence of two events on the same directory name.
:type sequencer: str
:param identity: The identity of the requester that triggered this event.
:type identity: str
:param storage_diagnostics: For service use only. Diagnostic data occasionally included by the
Azure Storage service. This property should be ignored by event consumers.
:type storage_diagnostics: object
"""
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'source_url': {'key': 'sourceUrl', 'type': 'str'},
'destination_url': {'key': 'destinationUrl', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryRenamedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.source_url = kwargs.get('source_url', None)
self.destination_url = kwargs.get('destination_url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageLifecyclePolicyActionSummaryDetail(msrest.serialization.Model):
"""Execution statistics of a specific policy action in a Blob Management cycle.
:param total_objects_count: Total number of objects to be acted on by this action.
:type total_objects_count: long
:param success_count: Number of success operations of this action.
:type success_count: long
:param error_list: Error messages of this action if any.
:type error_list: str
"""
_attribute_map = {
'total_objects_count': {'key': 'totalObjectsCount', 'type': 'long'},
'success_count': {'key': 'successCount', 'type': 'long'},
'error_list': {'key': 'errorList', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(StorageLifecyclePolicyActionSummaryDetail, self).__init__(**kwargs)
self.total_objects_count = kwargs.get('total_objects_count', None)
self.success_count = kwargs.get('success_count', None)
self.error_list = kwargs.get('error_list', None)
class StorageLifecyclePolicyCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Storage.LifecyclePolicyCompleted event.
:param schedule_time: The time the policy task was scheduled.
:type schedule_time: str
:param delete_summary: Execution statistics of a specific policy action in a Blob Management
cycle.
:type delete_summary:
~event_grid_publisher_client.models.StorageLifecyclePolicyActionSummaryDetail
:param tier_to_cool_summary: Execution statistics of a specific policy action in a Blob
Management cycle.
:type tier_to_cool_summary:
~event_grid_publisher_client.models.StorageLifecyclePolicyActionSummaryDetail
:param tier_to_archive_summary: Execution statistics of a specific policy action in a Blob
Management cycle.
:type tier_to_archive_summary:
~event_grid_publisher_client.models.StorageLifecyclePolicyActionSummaryDetail
"""
_attribute_map = {
'schedule_time': {'key': 'scheduleTime', 'type': 'str'},
'delete_summary': {'key': 'deleteSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
'tier_to_cool_summary': {'key': 'tierToCoolSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
'tier_to_archive_summary': {'key': 'tierToArchiveSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
}
def __init__(
self,
**kwargs
):
super(StorageLifecyclePolicyCompletedEventData, self).__init__(**kwargs)
self.schedule_time = kwargs.get('schedule_time', None)
self.delete_summary = kwargs.get('delete_summary', None)
self.tier_to_cool_summary = kwargs.get('tier_to_cool_summary', None)
self.tier_to_archive_summary = kwargs.get('tier_to_archive_summary', None)
class SubscriptionDeletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.EventGrid.SubscriptionDeletedEvent event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar event_subscription_id: The Azure resource ID of the deleted event subscription.
:vartype event_subscription_id: str
"""
_validation = {
'event_subscription_id': {'readonly': True},
}
_attribute_map = {
'event_subscription_id': {'key': 'eventSubscriptionId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionDeletedEventData, self).__init__(**kwargs)
self.event_subscription_id = None
class SubscriptionValidationEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.EventGrid.SubscriptionValidationEvent event.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar validation_code: The validation code sent by Azure Event Grid to validate an event
subscription. To complete the validation handshake, the subscriber must either respond with
this validation code as part of the validation response, or perform a GET request on the
validationUrl (available starting version 2018-05-01-preview).
:vartype validation_code: str
:ivar validation_url: The validation URL sent by Azure Event Grid (available starting version
2018-05-01-preview). To complete the validation handshake, the subscriber must either respond
with the validationCode as part of the validation response, or perform a GET request on the
validationUrl (available starting version 2018-05-01-preview).
:vartype validation_url: str
"""
_validation = {
'validation_code': {'readonly': True},
'validation_url': {'readonly': True},
}
_attribute_map = {
'validation_code': {'key': 'validationCode', 'type': 'str'},
'validation_url': {'key': 'validationUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionValidationEventData, self).__init__(**kwargs)
self.validation_code = None
self.validation_url = None
class SubscriptionValidationResponse(msrest.serialization.Model):
"""To complete an event subscription validation handshake, a subscriber can use either the validationCode or the validationUrl received in a SubscriptionValidationEvent. When the validationCode is used, the SubscriptionValidationResponse can be used to build the response.
:param validation_response: The validation response sent by the subscriber to Azure Event Grid
to complete the validation of an event subscription.
:type validation_response: str
"""
_attribute_map = {
'validation_response': {'key': 'validationResponse', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionValidationResponse, self).__init__(**kwargs)
self.validation_response = kwargs.get('validation_response', None)
class WebAppServicePlanUpdatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppServicePlanUpdated event.
:param app_service_plan_event_type_detail: Detail of action on the app service plan.
:type app_service_plan_event_type_detail:
~event_grid_publisher_client.models.AppServicePlanEventTypeDetail
:param sku: sku of app service plan.
:type sku: ~event_grid_publisher_client.models.WebAppServicePlanUpdatedEventDataSku
:param name: name of the app service plan that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the app
service plan API operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
app service plan API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the app service plan API
operation that triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_service_plan_event_type_detail': {'key': 'appServicePlanEventTypeDetail', 'type': 'AppServicePlanEventTypeDetail'},
'sku': {'key': 'sku', 'type': 'WebAppServicePlanUpdatedEventDataSku'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppServicePlanUpdatedEventData, self).__init__(**kwargs)
self.app_service_plan_event_type_detail = kwargs.get('app_service_plan_event_type_detail', None)
self.sku = kwargs.get('sku', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebAppServicePlanUpdatedEventDataSku(msrest.serialization.Model):
"""sku of app service plan.
:param name: name of app service plan sku.
:type name: str
:param tier: tier of app service plan sku.
:type tier: str
:param size: size of app service plan sku.
:type size: str
:param family: family of app service plan sku.
:type family: str
:param capacity: capacity of app service plan sku.
:type capacity: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'Tier', 'type': 'str'},
'size': {'key': 'Size', 'type': 'str'},
'family': {'key': 'Family', 'type': 'str'},
'capacity': {'key': 'Capacity', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppServicePlanUpdatedEventDataSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.size = kwargs.get('size', None)
self.family = kwargs.get('family', None)
self.capacity = kwargs.get('capacity', None)
class WebAppUpdatedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppUpdated event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppUpdatedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationCompleted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationFailedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationFailed event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationStartedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationStarted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationCompleted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationFailedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationFailed event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationStartedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationStarted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapCompletedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapCompleted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapFailedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapFailed event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapStartedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapStarted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapWithPreviewCancelledEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewCancelled event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapWithPreviewCancelledEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapWithPreviewStartedEventData(msrest.serialization.Model):
"""Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewStarted event.
:param app_event_type_detail: Detail of action on the app.
:type app_event_type_detail: ~event_grid_publisher_client.models.AppEventTypeDetail
:param name: name of the web site that had this event.
:type name: str
:param client_request_id: The client request id generated by the app service for the site API
operation that triggered this event.
:type client_request_id: str
:param correlation_request_id: The correlation request id generated by the app service for the
site API operation that triggered this event.
:type correlation_request_id: str
:param request_id: The request id generated by the app service for the site API operation that
triggered this event.
:type request_id: str
:param address: HTTP request URL of this operation.
:type address: str
:param verb: HTTP verb of this operation.
:type verb: str
"""
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapWithPreviewStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
| 43.177377 | 276 | 0.671298 |
import msrest.serialization
class AcsChatEventBaseProperties(msrest.serialization.Model):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatEventBaseProperties, self).__init__(**kwargs)
self.recipient_communication_identifier = kwargs.get('recipient_communication_identifier', None)
self.transaction_id = kwargs.get('transaction_id', None)
self.thread_id = kwargs.get('thread_id', None)
class AcsChatEventInThreadBaseProperties(msrest.serialization.Model):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatEventInThreadBaseProperties, self).__init__(**kwargs)
self.transaction_id = kwargs.get('transaction_id', None)
self.thread_id = kwargs.get('thread_id', None)
class AcsChatMessageEventBaseProperties(AcsChatEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEventBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.sender_communication_identifier = kwargs.get('sender_communication_identifier', None)
self.sender_display_name = kwargs.get('sender_display_name', None)
self.compose_time = kwargs.get('compose_time', None)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', None)
class AcsChatMessageDeletedEventData(AcsChatMessageEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageDeletedEventData, self).__init__(**kwargs)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatMessageEventInThreadBaseProperties(AcsChatEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEventInThreadBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.sender_communication_identifier = kwargs.get('sender_communication_identifier', None)
self.sender_display_name = kwargs.get('sender_display_name', None)
self.compose_time = kwargs.get('compose_time', None)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', None)
class AcsChatMessageDeletedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageDeletedInThreadEventData, self).__init__(**kwargs)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatMessageEditedEventData(AcsChatMessageEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEditedEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
self.edit_time = kwargs.get('edit_time', None)
class AcsChatMessageEditedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageEditedInThreadEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
self.edit_time = kwargs.get('edit_time', None)
class AcsChatMessageReceivedEventData(AcsChatMessageEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageReceivedEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
class AcsChatMessageReceivedInThreadEventData(AcsChatMessageEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'message_id': {'key': 'messageId', 'type': 'str'},
'sender_communication_identifier': {'key': 'senderCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'sender_display_name': {'key': 'senderDisplayName', 'type': 'str'},
'compose_time': {'key': 'composeTime', 'type': 'iso-8601'},
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'long'},
'message_body': {'key': 'messageBody', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsChatMessageReceivedInThreadEventData, self).__init__(**kwargs)
self.message_body = kwargs.get('message_body', None)
class AcsChatParticipantAddedToThreadEventData(AcsChatEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'added_by_communication_identifier': {'key': 'addedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_added': {'key': 'participantAdded', 'type': 'AcsChatThreadParticipantProperties'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantAddedToThreadEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.added_by_communication_identifier = kwargs.get('added_by_communication_identifier', None)
self.participant_added = kwargs.get('participant_added', None)
self.version = kwargs.get('version', None)
class AcsChatThreadEventBaseProperties(AcsChatEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadEventBaseProperties, self).__init__(**kwargs)
self.create_time = kwargs.get('create_time', None)
self.version = kwargs.get('version', None)
class AcsChatParticipantAddedToThreadWithUserEventData(AcsChatThreadEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'time': {'key': 'time', 'type': 'iso-8601'},
'added_by_communication_identifier': {'key': 'addedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_added': {'key': 'participantAdded', 'type': 'AcsChatThreadParticipantProperties'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantAddedToThreadWithUserEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.added_by_communication_identifier = kwargs.get('added_by_communication_identifier', None)
self.participant_added = kwargs.get('participant_added', None)
class AcsChatParticipantRemovedFromThreadEventData(AcsChatEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'removed_by_communication_identifier': {'key': 'removedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_removed': {'key': 'participantRemoved', 'type': 'AcsChatThreadParticipantProperties'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantRemovedFromThreadEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.removed_by_communication_identifier = kwargs.get('removed_by_communication_identifier', None)
self.participant_removed = kwargs.get('participant_removed', None)
self.version = kwargs.get('version', None)
class AcsChatParticipantRemovedFromThreadWithUserEventData(AcsChatThreadEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'time': {'key': 'time', 'type': 'iso-8601'},
'removed_by_communication_identifier': {'key': 'removedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'participant_removed': {'key': 'participantRemoved', 'type': 'AcsChatThreadParticipantProperties'},
}
def __init__(
self,
**kwargs
):
super(AcsChatParticipantRemovedFromThreadWithUserEventData, self).__init__(**kwargs)
self.time = kwargs.get('time', None)
self.removed_by_communication_identifier = kwargs.get('removed_by_communication_identifier', None)
self.participant_removed = kwargs.get('participant_removed', None)
class AcsChatThreadEventInThreadBaseProperties(AcsChatEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadEventInThreadBaseProperties, self).__init__(**kwargs)
self.create_time = kwargs.get('create_time', None)
self.version = kwargs.get('version', None)
class AcsChatThreadCreatedEventData(AcsChatThreadEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'created_by_communication_identifier': {'key': 'createdByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'properties': {'key': 'properties', 'type': '{object}'},
'participants': {'key': 'participants', 'type': '[AcsChatThreadParticipantProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadCreatedEventData, self).__init__(**kwargs)
self.created_by_communication_identifier = kwargs.get('created_by_communication_identifier', None)
self.properties = kwargs.get('properties', None)
self.participants = kwargs.get('participants', None)
class AcsChatThreadCreatedWithUserEventData(AcsChatThreadEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'created_by_communication_identifier': {'key': 'createdByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'properties': {'key': 'properties', 'type': '{object}'},
'participants': {'key': 'participants', 'type': '[AcsChatThreadParticipantProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadCreatedWithUserEventData, self).__init__(**kwargs)
self.created_by_communication_identifier = kwargs.get('created_by_communication_identifier', None)
self.properties = kwargs.get('properties', None)
self.participants = kwargs.get('participants', None)
class AcsChatThreadDeletedEventData(AcsChatThreadEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'deleted_by_communication_identifier': {'key': 'deletedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadDeletedEventData, self).__init__(**kwargs)
self.deleted_by_communication_identifier = kwargs.get('deleted_by_communication_identifier', None)
self.delete_time = kwargs.get('delete_time', None)
class AcsChatThreadParticipantProperties(msrest.serialization.Model):
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'participant_communication_identifier': {'key': 'participantCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadParticipantProperties, self).__init__(**kwargs)
self.display_name = kwargs.get('display_name', None)
self.participant_communication_identifier = kwargs.get('participant_communication_identifier', None)
class AcsChatThreadPropertiesUpdatedEventData(AcsChatThreadEventInThreadBaseProperties):
_attribute_map = {
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'edited_by_communication_identifier': {'key': 'editedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
'properties': {'key': 'properties', 'type': '{object}'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadPropertiesUpdatedEventData, self).__init__(**kwargs)
self.edited_by_communication_identifier = kwargs.get('edited_by_communication_identifier', None)
self.edit_time = kwargs.get('edit_time', None)
self.properties = kwargs.get('properties', None)
class AcsChatThreadPropertiesUpdatedPerUserEventData(AcsChatThreadEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'edited_by_communication_identifier': {'key': 'editedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'edit_time': {'key': 'editTime', 'type': 'iso-8601'},
'properties': {'key': 'properties', 'type': '{object}'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadPropertiesUpdatedPerUserEventData, self).__init__(**kwargs)
self.edited_by_communication_identifier = kwargs.get('edited_by_communication_identifier', None)
self.edit_time = kwargs.get('edit_time', None)
self.properties = kwargs.get('properties', None)
class AcsChatThreadWithUserDeletedEventData(AcsChatThreadEventBaseProperties):
_attribute_map = {
'recipient_communication_identifier': {'key': 'recipientCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'transaction_id': {'key': 'transactionId', 'type': 'str'},
'thread_id': {'key': 'threadId', 'type': 'str'},
'create_time': {'key': 'createTime', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'long'},
'deleted_by_communication_identifier': {'key': 'deletedByCommunicationIdentifier', 'type': 'CommunicationIdentifierModel'},
'delete_time': {'key': 'deleteTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsChatThreadWithUserDeletedEventData, self).__init__(**kwargs)
self.deleted_by_communication_identifier = kwargs.get('deleted_by_communication_identifier', None)
self.delete_time = kwargs.get('delete_time', None)
class AcsRecordingChunkInfoProperties(msrest.serialization.Model):
_attribute_map = {
'document_id': {'key': 'documentId', 'type': 'str'},
'index': {'key': 'index', 'type': 'long'},
'end_reason': {'key': 'endReason', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingChunkInfoProperties, self).__init__(**kwargs)
self.document_id = kwargs.get('document_id', None)
self.index = kwargs.get('index', None)
self.end_reason = kwargs.get('end_reason', None)
class AcsRecordingFileStatusUpdatedEventData(msrest.serialization.Model):
_attribute_map = {
'recording_storage_info': {'key': 'recordingStorageInfo', 'type': 'AcsRecordingStorageInfoProperties'},
'recording_start_time': {'key': 'recordingStartTime', 'type': 'iso-8601'},
'recording_duration_ms': {'key': 'recordingDurationMs', 'type': 'long'},
'session_end_reason': {'key': 'sessionEndReason', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingFileStatusUpdatedEventData, self).__init__(**kwargs)
self.recording_storage_info = kwargs.get('recording_storage_info', None)
self.recording_start_time = kwargs.get('recording_start_time', None)
self.recording_duration_ms = kwargs.get('recording_duration_ms', None)
self.session_end_reason = kwargs.get('session_end_reason', None)
class AcsRecordingStorageInfoProperties(msrest.serialization.Model):
_attribute_map = {
'recording_chunks': {'key': 'recordingChunks', 'type': '[AcsRecordingChunkInfoProperties]'},
}
def __init__(
self,
**kwargs
):
super(AcsRecordingStorageInfoProperties, self).__init__(**kwargs)
self.recording_chunks = kwargs.get('recording_chunks', None)
class AcsSmsDeliveryAttemptProperties(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'segments_succeeded': {'key': 'segmentsSucceeded', 'type': 'int'},
'segments_failed': {'key': 'segmentsFailed', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsDeliveryAttemptProperties, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.segments_succeeded = kwargs.get('segments_succeeded', None)
self.segments_failed = kwargs.get('segments_failed', None)
class AcsSmsEventBaseProperties(msrest.serialization.Model):
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsEventBaseProperties, self).__init__(**kwargs)
self.message_id = kwargs.get('message_id', None)
self.from_property = kwargs.get('from_property', None)
self.to = kwargs.get('to', None)
class AcsSmsDeliveryReportReceivedEventData(AcsSmsEventBaseProperties):
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
'delivery_status': {'key': 'deliveryStatus', 'type': 'str'},
'delivery_status_details': {'key': 'deliveryStatusDetails', 'type': 'str'},
'delivery_attempts': {'key': 'deliveryAttempts', 'type': '[AcsSmsDeliveryAttemptProperties]'},
'received_timestamp': {'key': 'receivedTimestamp', 'type': 'iso-8601'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsDeliveryReportReceivedEventData, self).__init__(**kwargs)
self.delivery_status = kwargs.get('delivery_status', None)
self.delivery_status_details = kwargs.get('delivery_status_details', None)
self.delivery_attempts = kwargs.get('delivery_attempts', None)
self.received_timestamp = kwargs.get('received_timestamp', None)
self.tag = kwargs.get('tag', None)
class AcsSmsReceivedEventData(AcsSmsEventBaseProperties):
_attribute_map = {
'message_id': {'key': 'messageId', 'type': 'str'},
'from_property': {'key': 'from', 'type': 'str'},
'to': {'key': 'to', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'received_timestamp': {'key': 'receivedTimestamp', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AcsSmsReceivedEventData, self).__init__(**kwargs)
self.message = kwargs.get('message', None)
self.received_timestamp = kwargs.get('received_timestamp', None)
class AppConfigurationKeyValueDeletedEventData(msrest.serialization.Model):
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'label': {'key': 'label', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'sync_token': {'key': 'syncToken', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppConfigurationKeyValueDeletedEventData, self).__init__(**kwargs)
self.key = kwargs.get('key', None)
self.label = kwargs.get('label', None)
self.etag = kwargs.get('etag', None)
self.sync_token = kwargs.get('sync_token', None)
class AppConfigurationKeyValueModifiedEventData(msrest.serialization.Model):
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'label': {'key': 'label', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'sync_token': {'key': 'syncToken', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppConfigurationKeyValueModifiedEventData, self).__init__(**kwargs)
self.key = kwargs.get('key', None)
self.label = kwargs.get('label', None)
self.etag = kwargs.get('etag', None)
self.sync_token = kwargs.get('sync_token', None)
class AppEventTypeDetail(msrest.serialization.Model):
_attribute_map = {
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppEventTypeDetail, self).__init__(**kwargs)
self.action = kwargs.get('action', None)
class AppServicePlanEventTypeDetail(msrest.serialization.Model):
_attribute_map = {
'stamp_kind': {'key': 'stampKind', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AppServicePlanEventTypeDetail, self).__init__(**kwargs)
self.stamp_kind = kwargs.get('stamp_kind', None)
self.action = kwargs.get('action', None)
self.status = kwargs.get('status', None)
class CloudEvent(msrest.serialization.Model):
_validation = {
'id': {'required': True},
'source': {'required': True},
'type': {'required': True},
'specversion': {'required': True},
}
_attribute_map = {
'additional_properties': {'key': '', 'type': '{object}'},
'id': {'key': 'id', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'},
'data': {'key': 'data', 'type': 'object'},
'data_base64': {'key': 'data_base64', 'type': 'bytearray'},
'type': {'key': 'type', 'type': 'str'},
'time': {'key': 'time', 'type': 'iso-8601'},
'specversion': {'key': 'specversion', 'type': 'str'},
'dataschema': {'key': 'dataschema', 'type': 'str'},
'datacontenttype': {'key': 'datacontenttype', 'type': 'str'},
'subject': {'key': 'subject', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CloudEvent, self).__init__(**kwargs)
self.additional_properties = kwargs.get('additional_properties', None)
self.id = kwargs['id']
self.source = kwargs['source']
self.data = kwargs.get('data', None)
self.data_base64 = kwargs.get('data_base64', None)
self.type = kwargs['type']
self.time = kwargs.get('time', None)
self.specversion = kwargs['specversion']
self.dataschema = kwargs.get('dataschema', None)
self.datacontenttype = kwargs.get('datacontenttype', None)
self.subject = kwargs.get('subject', None)
class CommunicationIdentifierModel(msrest.serialization.Model):
_attribute_map = {
'raw_id': {'key': 'rawId', 'type': 'str'},
'communication_user': {'key': 'communicationUser', 'type': 'CommunicationUserIdentifierModel'},
'phone_number': {'key': 'phoneNumber', 'type': 'PhoneNumberIdentifierModel'},
'microsoft_teams_user': {'key': 'microsoftTeamsUser', 'type': 'MicrosoftTeamsUserIdentifierModel'},
}
def __init__(
self,
**kwargs
):
super(CommunicationIdentifierModel, self).__init__(**kwargs)
self.raw_id = kwargs.get('raw_id', None)
self.communication_user = kwargs.get('communication_user', None)
self.phone_number = kwargs.get('phone_number', None)
self.microsoft_teams_user = kwargs.get('microsoft_teams_user', None)
class CommunicationUserIdentifierModel(msrest.serialization.Model):
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CommunicationUserIdentifierModel, self).__init__(**kwargs)
self.id = kwargs['id']
class ContainerRegistryArtifactEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryArtifactEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.timestamp = kwargs.get('timestamp', None)
self.action = kwargs.get('action', None)
self.target = kwargs.get('target', None)
class ContainerRegistryArtifactEventTarget(msrest.serialization.Model):
_attribute_map = {
'media_type': {'key': 'mediaType', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'digest': {'key': 'digest', 'type': 'str'},
'repository': {'key': 'repository', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryArtifactEventTarget, self).__init__(**kwargs)
self.media_type = kwargs.get('media_type', None)
self.size = kwargs.get('size', None)
self.digest = kwargs.get('digest', None)
self.repository = kwargs.get('repository', None)
self.tag = kwargs.get('tag', None)
self.name = kwargs.get('name', None)
self.version = kwargs.get('version', None)
class ContainerRegistryChartDeletedEventData(ContainerRegistryArtifactEventData):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryChartDeletedEventData, self).__init__(**kwargs)
class ContainerRegistryChartPushedEventData(ContainerRegistryArtifactEventData):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryArtifactEventTarget'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryChartPushedEventData, self).__init__(**kwargs)
class ContainerRegistryEventActor(msrest.serialization.Model):
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventActor, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class ContainerRegistryEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.timestamp = kwargs.get('timestamp', None)
self.action = kwargs.get('action', None)
self.target = kwargs.get('target', None)
self.request = kwargs.get('request', None)
self.actor = kwargs.get('actor', None)
self.source = kwargs.get('source', None)
class ContainerRegistryEventRequest(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'addr': {'key': 'addr', 'type': 'str'},
'host': {'key': 'host', 'type': 'str'},
'method': {'key': 'method', 'type': 'str'},
'useragent': {'key': 'useragent', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventRequest, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.addr = kwargs.get('addr', None)
self.host = kwargs.get('host', None)
self.method = kwargs.get('method', None)
self.useragent = kwargs.get('useragent', None)
class ContainerRegistryEventSource(msrest.serialization.Model):
_attribute_map = {
'addr': {'key': 'addr', 'type': 'str'},
'instance_id': {'key': 'instanceID', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventSource, self).__init__(**kwargs)
self.addr = kwargs.get('addr', None)
self.instance_id = kwargs.get('instance_id', None)
class ContainerRegistryEventTarget(msrest.serialization.Model):
_attribute_map = {
'media_type': {'key': 'mediaType', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'digest': {'key': 'digest', 'type': 'str'},
'length': {'key': 'length', 'type': 'long'},
'repository': {'key': 'repository', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryEventTarget, self).__init__(**kwargs)
self.media_type = kwargs.get('media_type', None)
self.size = kwargs.get('size', None)
self.digest = kwargs.get('digest', None)
self.length = kwargs.get('length', None)
self.repository = kwargs.get('repository', None)
self.url = kwargs.get('url', None)
self.tag = kwargs.get('tag', None)
class ContainerRegistryImageDeletedEventData(ContainerRegistryEventData):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryImageDeletedEventData, self).__init__(**kwargs)
class ContainerRegistryImagePushedEventData(ContainerRegistryEventData):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'action': {'key': 'action', 'type': 'str'},
'target': {'key': 'target', 'type': 'ContainerRegistryEventTarget'},
'request': {'key': 'request', 'type': 'ContainerRegistryEventRequest'},
'actor': {'key': 'actor', 'type': 'ContainerRegistryEventActor'},
'source': {'key': 'source', 'type': 'ContainerRegistryEventSource'},
}
def __init__(
self,
**kwargs
):
super(ContainerRegistryImagePushedEventData, self).__init__(**kwargs)
class DeviceConnectionStateEventInfo(msrest.serialization.Model):
_attribute_map = {
'sequence_number': {'key': 'sequenceNumber', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceConnectionStateEventInfo, self).__init__(**kwargs)
self.sequence_number = kwargs.get('sequence_number', None)
class DeviceConnectionStateEventProperties(msrest.serialization.Model):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(DeviceConnectionStateEventProperties, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.module_id = kwargs.get('module_id', None)
self.hub_name = kwargs.get('hub_name', None)
self.device_connection_state_event_info = kwargs.get('device_connection_state_event_info', None)
class DeviceLifeCycleEventProperties(msrest.serialization.Model):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(DeviceLifeCycleEventProperties, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.hub_name = kwargs.get('hub_name', None)
self.twin = kwargs.get('twin', None)
class DeviceTelemetryEventProperties(msrest.serialization.Model):
_attribute_map = {
'body': {'key': 'body', 'type': 'object'},
'properties': {'key': 'properties', 'type': '{str}'},
'system_properties': {'key': 'systemProperties', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(DeviceTelemetryEventProperties, self).__init__(**kwargs)
self.body = kwargs.get('body', None)
self.properties = kwargs.get('properties', None)
self.system_properties = kwargs.get('system_properties', None)
class DeviceTwinInfo(msrest.serialization.Model):
_attribute_map = {
'authentication_type': {'key': 'authenticationType', 'type': 'str'},
'cloud_to_device_message_count': {'key': 'cloudToDeviceMessageCount', 'type': 'float'},
'connection_state': {'key': 'connectionState', 'type': 'str'},
'device_id': {'key': 'deviceId', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'last_activity_time': {'key': 'lastActivityTime', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'DeviceTwinInfoProperties'},
'status': {'key': 'status', 'type': 'str'},
'status_update_time': {'key': 'statusUpdateTime', 'type': 'str'},
'version': {'key': 'version', 'type': 'float'},
'x509_thumbprint': {'key': 'x509Thumbprint', 'type': 'DeviceTwinInfoX509Thumbprint'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfo, self).__init__(**kwargs)
self.authentication_type = kwargs.get('authentication_type', None)
self.cloud_to_device_message_count = kwargs.get('cloud_to_device_message_count', None)
self.connection_state = kwargs.get('connection_state', None)
self.device_id = kwargs.get('device_id', None)
self.etag = kwargs.get('etag', None)
self.last_activity_time = kwargs.get('last_activity_time', None)
self.properties = kwargs.get('properties', None)
self.status = kwargs.get('status', None)
self.status_update_time = kwargs.get('status_update_time', None)
self.version = kwargs.get('version', None)
self.x509_thumbprint = kwargs.get('x509_thumbprint', None)
class DeviceTwinInfoProperties(msrest.serialization.Model):
_attribute_map = {
'desired': {'key': 'desired', 'type': 'DeviceTwinProperties'},
'reported': {'key': 'reported', 'type': 'DeviceTwinProperties'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfoProperties, self).__init__(**kwargs)
self.desired = kwargs.get('desired', None)
self.reported = kwargs.get('reported', None)
class DeviceTwinInfoX509Thumbprint(msrest.serialization.Model):
_attribute_map = {
'primary_thumbprint': {'key': 'primaryThumbprint', 'type': 'str'},
'secondary_thumbprint': {'key': 'secondaryThumbprint', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinInfoX509Thumbprint, self).__init__(**kwargs)
self.primary_thumbprint = kwargs.get('primary_thumbprint', None)
self.secondary_thumbprint = kwargs.get('secondary_thumbprint', None)
class DeviceTwinMetadata(msrest.serialization.Model):
_attribute_map = {
'last_updated': {'key': 'lastUpdated', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinMetadata, self).__init__(**kwargs)
self.last_updated = kwargs.get('last_updated', None)
class DeviceTwinProperties(msrest.serialization.Model):
_attribute_map = {
'metadata': {'key': 'metadata', 'type': 'DeviceTwinMetadata'},
'version': {'key': 'version', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(DeviceTwinProperties, self).__init__(**kwargs)
self.metadata = kwargs.get('metadata', None)
self.version = kwargs.get('version', None)
class EventGridEvent(msrest.serialization.Model):
_validation = {
'id': {'required': True},
'subject': {'required': True},
'data': {'required': True},
'event_type': {'required': True},
'event_time': {'required': True},
'metadata_version': {'readonly': True},
'data_version': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'topic': {'key': 'topic', 'type': 'str'},
'subject': {'key': 'subject', 'type': 'str'},
'data': {'key': 'data', 'type': 'object'},
'event_type': {'key': 'eventType', 'type': 'str'},
'event_time': {'key': 'eventTime', 'type': 'iso-8601'},
'metadata_version': {'key': 'metadataVersion', 'type': 'str'},
'data_version': {'key': 'dataVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EventGridEvent, self).__init__(**kwargs)
self.id = kwargs['id']
self.topic = kwargs.get('topic', None)
self.subject = kwargs['subject']
self.data = kwargs['data']
self.event_type = kwargs['event_type']
self.event_time = kwargs['event_time']
self.metadata_version = None
self.data_version = kwargs['data_version']
class EventHubCaptureFileCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'fileurl': {'key': 'fileurl', 'type': 'str'},
'file_type': {'key': 'fileType', 'type': 'str'},
'partition_id': {'key': 'partitionId', 'type': 'str'},
'size_in_bytes': {'key': 'sizeInBytes', 'type': 'int'},
'event_count': {'key': 'eventCount', 'type': 'int'},
'first_sequence_number': {'key': 'firstSequenceNumber', 'type': 'int'},
'last_sequence_number': {'key': 'lastSequenceNumber', 'type': 'int'},
'first_enqueue_time': {'key': 'firstEnqueueTime', 'type': 'iso-8601'},
'last_enqueue_time': {'key': 'lastEnqueueTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(EventHubCaptureFileCreatedEventData, self).__init__(**kwargs)
self.fileurl = kwargs.get('fileurl', None)
self.file_type = kwargs.get('file_type', None)
self.partition_id = kwargs.get('partition_id', None)
self.size_in_bytes = kwargs.get('size_in_bytes', None)
self.event_count = kwargs.get('event_count', None)
self.first_sequence_number = kwargs.get('first_sequence_number', None)
self.last_sequence_number = kwargs.get('last_sequence_number', None)
self.first_enqueue_time = kwargs.get('first_enqueue_time', None)
self.last_enqueue_time = kwargs.get('last_enqueue_time', None)
class IotHubDeviceConnectedEventData(DeviceConnectionStateEventProperties):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceConnectedEventData, self).__init__(**kwargs)
class IotHubDeviceCreatedEventData(DeviceLifeCycleEventProperties):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceCreatedEventData, self).__init__(**kwargs)
class IotHubDeviceDeletedEventData(DeviceLifeCycleEventProperties):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'twin': {'key': 'twin', 'type': 'DeviceTwinInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceDeletedEventData, self).__init__(**kwargs)
class IotHubDeviceDisconnectedEventData(DeviceConnectionStateEventProperties):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'module_id': {'key': 'moduleId', 'type': 'str'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'device_connection_state_event_info': {'key': 'deviceConnectionStateEventInfo', 'type': 'DeviceConnectionStateEventInfo'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceDisconnectedEventData, self).__init__(**kwargs)
class IotHubDeviceTelemetryEventData(DeviceTelemetryEventProperties):
_attribute_map = {
'body': {'key': 'body', 'type': 'object'},
'properties': {'key': 'properties', 'type': '{str}'},
'system_properties': {'key': 'systemProperties', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(IotHubDeviceTelemetryEventData, self).__init__(**kwargs)
class KeyVaultAccessPolicyChangedEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultAccessPolicyChangedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateExpiredEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateNearExpiryEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultCertificateNewVersionCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultCertificateNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyExpiredEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyNearExpiryEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultKeyNewVersionCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultKeyNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretExpiredEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretExpiredEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretNearExpiryEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretNearExpiryEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class KeyVaultSecretNewVersionCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'vault_name': {'key': 'vaultName', 'type': 'str'},
'object_type': {'key': 'objectType', 'type': 'str'},
'object_name': {'key': 'objectName', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'nbf': {'key': 'nbf', 'type': 'float'},
'exp': {'key': 'exp', 'type': 'float'},
}
def __init__(
self,
**kwargs
):
super(KeyVaultSecretNewVersionCreatedEventData, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.vault_name = kwargs.get('vault_name', None)
self.object_type = kwargs.get('object_type', None)
self.object_name = kwargs.get('object_name', None)
self.version = kwargs.get('version', None)
self.nbf = kwargs.get('nbf', None)
self.exp = kwargs.get('exp', None)
class MachineLearningServicesDatasetDriftDetectedEventData(msrest.serialization.Model):
_attribute_map = {
'data_drift_id': {'key': 'dataDriftId', 'type': 'str'},
'data_drift_name': {'key': 'dataDriftName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'base_dataset_id': {'key': 'baseDatasetId', 'type': 'str'},
'target_dataset_id': {'key': 'targetDatasetId', 'type': 'str'},
'drift_coefficient': {'key': 'driftCoefficient', 'type': 'float'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesDatasetDriftDetectedEventData, self).__init__(**kwargs)
self.data_drift_id = kwargs.get('data_drift_id', None)
self.data_drift_name = kwargs.get('data_drift_name', None)
self.run_id = kwargs.get('run_id', None)
self.base_dataset_id = kwargs.get('base_dataset_id', None)
self.target_dataset_id = kwargs.get('target_dataset_id', None)
self.drift_coefficient = kwargs.get('drift_coefficient', None)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
class MachineLearningServicesModelDeployedEventData(msrest.serialization.Model):
_attribute_map = {
'service_name': {'key': 'serviceName', 'type': 'str'},
'service_compute_type': {'key': 'serviceComputeType', 'type': 'str'},
'model_ids': {'key': 'modelIds', 'type': 'str'},
'service_tags': {'key': 'serviceTags', 'type': 'object'},
'service_properties': {'key': 'serviceProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesModelDeployedEventData, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.service_compute_type = kwargs.get('service_compute_type', None)
self.model_ids = kwargs.get('model_ids', None)
self.service_tags = kwargs.get('service_tags', None)
self.service_properties = kwargs.get('service_properties', None)
class MachineLearningServicesModelRegisteredEventData(msrest.serialization.Model):
_attribute_map = {
'model_name': {'key': 'modelName', 'type': 'str'},
'model_version': {'key': 'modelVersion', 'type': 'str'},
'model_tags': {'key': 'modelTags', 'type': 'object'},
'model_properties': {'key': 'modelProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesModelRegisteredEventData, self).__init__(**kwargs)
self.model_name = kwargs.get('model_name', None)
self.model_version = kwargs.get('model_version', None)
self.model_tags = kwargs.get('model_tags', None)
self.model_properties = kwargs.get('model_properties', None)
class MachineLearningServicesRunCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'experiment_id': {'key': 'experimentId', 'type': 'str'},
'experiment_name': {'key': 'experimentName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'run_type': {'key': 'runType', 'type': 'str'},
'run_tags': {'key': 'runTags', 'type': 'object'},
'run_properties': {'key': 'runProperties', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesRunCompletedEventData, self).__init__(**kwargs)
self.experiment_id = kwargs.get('experiment_id', None)
self.experiment_name = kwargs.get('experiment_name', None)
self.run_id = kwargs.get('run_id', None)
self.run_type = kwargs.get('run_type', None)
self.run_tags = kwargs.get('run_tags', None)
self.run_properties = kwargs.get('run_properties', None)
class MachineLearningServicesRunStatusChangedEventData(msrest.serialization.Model):
_attribute_map = {
'experiment_id': {'key': 'experimentId', 'type': 'str'},
'experiment_name': {'key': 'experimentName', 'type': 'str'},
'run_id': {'key': 'runId', 'type': 'str'},
'run_type': {'key': 'runType', 'type': 'str'},
'run_tags': {'key': 'runTags', 'type': 'object'},
'run_properties': {'key': 'runProperties', 'type': 'object'},
'run_status': {'key': 'runStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MachineLearningServicesRunStatusChangedEventData, self).__init__(**kwargs)
self.experiment_id = kwargs.get('experiment_id', None)
self.experiment_name = kwargs.get('experiment_name', None)
self.run_id = kwargs.get('run_id', None)
self.run_type = kwargs.get('run_type', None)
self.run_tags = kwargs.get('run_tags', None)
self.run_properties = kwargs.get('run_properties', None)
self.run_status = kwargs.get('run_status', None)
class MapsGeofenceEventProperties(msrest.serialization.Model):
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceEventProperties, self).__init__(**kwargs)
self.expired_geofence_geometry_id = kwargs.get('expired_geofence_geometry_id', None)
self.geometries = kwargs.get('geometries', None)
self.invalid_period_geofence_geometry_id = kwargs.get('invalid_period_geofence_geometry_id', None)
self.is_event_published = kwargs.get('is_event_published', None)
class MapsGeofenceEnteredEventData(MapsGeofenceEventProperties):
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceEnteredEventData, self).__init__(**kwargs)
class MapsGeofenceExitedEventData(MapsGeofenceEventProperties):
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceExitedEventData, self).__init__(**kwargs)
class MapsGeofenceGeometry(msrest.serialization.Model):
_attribute_map = {
'device_id': {'key': 'deviceId', 'type': 'str'},
'distance': {'key': 'distance', 'type': 'float'},
'geometry_id': {'key': 'geometryId', 'type': 'str'},
'nearest_lat': {'key': 'nearestLat', 'type': 'float'},
'nearest_lon': {'key': 'nearestLon', 'type': 'float'},
'ud_id': {'key': 'udId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceGeometry, self).__init__(**kwargs)
self.device_id = kwargs.get('device_id', None)
self.distance = kwargs.get('distance', None)
self.geometry_id = kwargs.get('geometry_id', None)
self.nearest_lat = kwargs.get('nearest_lat', None)
self.nearest_lon = kwargs.get('nearest_lon', None)
self.ud_id = kwargs.get('ud_id', None)
class MapsGeofenceResultEventData(MapsGeofenceEventProperties):
_attribute_map = {
'expired_geofence_geometry_id': {'key': 'expiredGeofenceGeometryId', 'type': '[str]'},
'geometries': {'key': 'geometries', 'type': '[MapsGeofenceGeometry]'},
'invalid_period_geofence_geometry_id': {'key': 'invalidPeriodGeofenceGeometryId', 'type': '[str]'},
'is_event_published': {'key': 'isEventPublished', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MapsGeofenceResultEventData, self).__init__(**kwargs)
class MediaJobStateChangeEventData(msrest.serialization.Model):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobStateChangeEventData, self).__init__(**kwargs)
self.previous_state = None
self.state = None
self.correlation_data = kwargs.get('correlation_data', None)
class MediaJobCanceledEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobCanceledEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobCancelingEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobCancelingEventData, self).__init__(**kwargs)
class MediaJobError(msrest.serialization.Model):
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
'category': {'readonly': True},
'retry': {'readonly': True},
'details': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'category': {'key': 'category', 'type': 'str'},
'retry': {'key': 'retry', 'type': 'str'},
'details': {'key': 'details', 'type': '[MediaJobErrorDetail]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobError, self).__init__(**kwargs)
self.code = None
self.message = None
self.category = None
self.retry = None
self.details = None
class MediaJobErrorDetail(msrest.serialization.Model):
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaJobErrorDetail, self).__init__(**kwargs)
self.code = None
self.message = None
class MediaJobErroredEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobErroredEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobFinishedEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
'outputs': {'key': 'outputs', 'type': '[MediaJobOutput]'},
}
def __init__(
self,
**kwargs
):
super(MediaJobFinishedEventData, self).__init__(**kwargs)
self.outputs = kwargs.get('outputs', None)
class MediaJobOutput(msrest.serialization.Model):
_validation = {
'progress': {'required': True},
'state': {'required': True},
}
_attribute_map = {
'odata_type': {'key': '@odata\\.type', 'type': 'str'},
'error': {'key': 'error', 'type': 'MediaJobError'},
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'state': {'key': 'state', 'type': 'str'},
}
_subtype_map = {
'odata_type': {'#Microsoft.Media.JobOutputAsset': 'MediaJobOutputAsset'}
}
def __init__(
self,
**kwargs
):
super(MediaJobOutput, self).__init__(**kwargs)
self.odata_type = None
self.error = kwargs.get('error', None)
self.label = kwargs.get('label', None)
self.progress = kwargs['progress']
self.state = kwargs['state']
class MediaJobOutputAsset(MediaJobOutput):
_validation = {
'progress': {'required': True},
'state': {'required': True},
}
_attribute_map = {
'odata_type': {'key': '@odata\\.type', 'type': 'str'},
'error': {'key': 'error', 'type': 'MediaJobError'},
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'state': {'key': 'state', 'type': 'str'},
'asset_name': {'key': 'assetName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputAsset, self).__init__(**kwargs)
self.odata_type = '#Microsoft.Media.JobOutputAsset'
self.asset_name = kwargs.get('asset_name', None)
class MediaJobOutputStateChangeEventData(msrest.serialization.Model):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputStateChangeEventData, self).__init__(**kwargs)
self.previous_state = None
self.output = kwargs.get('output', None)
self.job_correlation_data = kwargs.get('job_correlation_data', None)
class MediaJobOutputCanceledEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputCanceledEventData, self).__init__(**kwargs)
class MediaJobOutputCancelingEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputCancelingEventData, self).__init__(**kwargs)
class MediaJobOutputErroredEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputErroredEventData, self).__init__(**kwargs)
class MediaJobOutputFinishedEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputFinishedEventData, self).__init__(**kwargs)
class MediaJobOutputProcessingEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputProcessingEventData, self).__init__(**kwargs)
class MediaJobOutputProgressEventData(msrest.serialization.Model):
_attribute_map = {
'label': {'key': 'label', 'type': 'str'},
'progress': {'key': 'progress', 'type': 'long'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputProgressEventData, self).__init__(**kwargs)
self.label = kwargs.get('label', None)
self.progress = kwargs.get('progress', None)
self.job_correlation_data = kwargs.get('job_correlation_data', None)
class MediaJobOutputScheduledEventData(MediaJobOutputStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'output': {'key': 'output', 'type': 'MediaJobOutput'},
'job_correlation_data': {'key': 'jobCorrelationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobOutputScheduledEventData, self).__init__(**kwargs)
class MediaJobProcessingEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobProcessingEventData, self).__init__(**kwargs)
class MediaJobScheduledEventData(MediaJobStateChangeEventData):
_validation = {
'previous_state': {'readonly': True},
'state': {'readonly': True},
}
_attribute_map = {
'previous_state': {'key': 'previousState', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'correlation_data': {'key': 'correlationData', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(MediaJobScheduledEventData, self).__init__(**kwargs)
class MediaLiveEventConnectionRejectedEventData(msrest.serialization.Model):
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'result_code': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventConnectionRejectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
self.result_code = None
class MediaLiveEventEncoderConnectedEventData(msrest.serialization.Model):
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventEncoderConnectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
class MediaLiveEventEncoderDisconnectedEventData(msrest.serialization.Model):
_validation = {
'ingest_url': {'readonly': True},
'stream_id': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'result_code': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'stream_id': {'key': 'streamId', 'type': 'str'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventEncoderDisconnectedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.stream_id = None
self.encoder_ip = None
self.encoder_port = None
self.result_code = None
class MediaLiveEventIncomingDataChunkDroppedEventData(msrest.serialization.Model):
_validation = {
'timestamp': {'readonly': True},
'track_type': {'readonly': True},
'bitrate': {'readonly': True},
'timescale': {'readonly': True},
'result_code': {'readonly': True},
'track_name': {'readonly': True},
}
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'str'},
'track_type': {'key': 'trackType', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'timescale': {'key': 'timescale', 'type': 'str'},
'result_code': {'key': 'resultCode', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingDataChunkDroppedEventData, self).__init__(**kwargs)
self.timestamp = None
self.track_type = None
self.bitrate = None
self.timescale = None
self.result_code = None
self.track_name = None
class MediaLiveEventIncomingStreamReceivedEventData(msrest.serialization.Model):
_validation = {
'ingest_url': {'readonly': True},
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'encoder_ip': {'readonly': True},
'encoder_port': {'readonly': True},
'timestamp': {'readonly': True},
'duration': {'readonly': True},
'timescale': {'readonly': True},
}
_attribute_map = {
'ingest_url': {'key': 'ingestUrl', 'type': 'str'},
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'encoder_ip': {'key': 'encoderIp', 'type': 'str'},
'encoder_port': {'key': 'encoderPort', 'type': 'str'},
'timestamp': {'key': 'timestamp', 'type': 'str'},
'duration': {'key': 'duration', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingStreamReceivedEventData, self).__init__(**kwargs)
self.ingest_url = None
self.track_type = None
self.track_name = None
self.bitrate = None
self.encoder_ip = None
self.encoder_port = None
self.timestamp = None
self.duration = None
self.timescale = None
class MediaLiveEventIncomingStreamsOutOfSyncEventData(msrest.serialization.Model):
_validation = {
'min_last_timestamp': {'readonly': True},
'type_of_stream_with_min_last_timestamp': {'readonly': True},
'max_last_timestamp': {'readonly': True},
'type_of_stream_with_max_last_timestamp': {'readonly': True},
'timescale_of_min_last_timestamp': {'readonly': True},
'timescale_of_max_last_timestamp': {'readonly': True},
}
_attribute_map = {
'min_last_timestamp': {'key': 'minLastTimestamp', 'type': 'str'},
'type_of_stream_with_min_last_timestamp': {'key': 'typeOfStreamWithMinLastTimestamp', 'type': 'str'},
'max_last_timestamp': {'key': 'maxLastTimestamp', 'type': 'str'},
'type_of_stream_with_max_last_timestamp': {'key': 'typeOfStreamWithMaxLastTimestamp', 'type': 'str'},
'timescale_of_min_last_timestamp': {'key': 'timescaleOfMinLastTimestamp', 'type': 'str'},
'timescale_of_max_last_timestamp': {'key': 'timescaleOfMaxLastTimestamp', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingStreamsOutOfSyncEventData, self).__init__(**kwargs)
self.min_last_timestamp = None
self.type_of_stream_with_min_last_timestamp = None
self.max_last_timestamp = None
self.type_of_stream_with_max_last_timestamp = None
self.timescale_of_min_last_timestamp = None
self.timescale_of_max_last_timestamp = None
class MediaLiveEventIncomingVideoStreamsOutOfSyncEventData(msrest.serialization.Model):
_validation = {
'first_timestamp': {'readonly': True},
'first_duration': {'readonly': True},
'second_timestamp': {'readonly': True},
'second_duration': {'readonly': True},
'timescale': {'readonly': True},
}
_attribute_map = {
'first_timestamp': {'key': 'firstTimestamp', 'type': 'str'},
'first_duration': {'key': 'firstDuration', 'type': 'str'},
'second_timestamp': {'key': 'secondTimestamp', 'type': 'str'},
'second_duration': {'key': 'secondDuration', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIncomingVideoStreamsOutOfSyncEventData, self).__init__(**kwargs)
self.first_timestamp = None
self.first_duration = None
self.second_timestamp = None
self.second_duration = None
self.timescale = None
class MediaLiveEventIngestHeartbeatEventData(msrest.serialization.Model):
_validation = {
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'incoming_bitrate': {'readonly': True},
'last_timestamp': {'readonly': True},
'timescale': {'readonly': True},
'overlap_count': {'readonly': True},
'discontinuity_count': {'readonly': True},
'nonincreasing_count': {'readonly': True},
'unexpected_bitrate': {'readonly': True},
'state': {'readonly': True},
'healthy': {'readonly': True},
}
_attribute_map = {
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'incoming_bitrate': {'key': 'incomingBitrate', 'type': 'long'},
'last_timestamp': {'key': 'lastTimestamp', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
'overlap_count': {'key': 'overlapCount', 'type': 'long'},
'discontinuity_count': {'key': 'discontinuityCount', 'type': 'long'},
'nonincreasing_count': {'key': 'nonincreasingCount', 'type': 'long'},
'unexpected_bitrate': {'key': 'unexpectedBitrate', 'type': 'bool'},
'state': {'key': 'state', 'type': 'str'},
'healthy': {'key': 'healthy', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventIngestHeartbeatEventData, self).__init__(**kwargs)
self.track_type = None
self.track_name = None
self.bitrate = None
self.incoming_bitrate = None
self.last_timestamp = None
self.timescale = None
self.overlap_count = None
self.discontinuity_count = None
self.nonincreasing_count = None
self.unexpected_bitrate = None
self.state = None
self.healthy = None
class MediaLiveEventTrackDiscontinuityDetectedEventData(msrest.serialization.Model):
_validation = {
'track_type': {'readonly': True},
'track_name': {'readonly': True},
'bitrate': {'readonly': True},
'previous_timestamp': {'readonly': True},
'new_timestamp': {'readonly': True},
'timescale': {'readonly': True},
'discontinuity_gap': {'readonly': True},
}
_attribute_map = {
'track_type': {'key': 'trackType', 'type': 'str'},
'track_name': {'key': 'trackName', 'type': 'str'},
'bitrate': {'key': 'bitrate', 'type': 'long'},
'previous_timestamp': {'key': 'previousTimestamp', 'type': 'str'},
'new_timestamp': {'key': 'newTimestamp', 'type': 'str'},
'timescale': {'key': 'timescale', 'type': 'str'},
'discontinuity_gap': {'key': 'discontinuityGap', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MediaLiveEventTrackDiscontinuityDetectedEventData, self).__init__(**kwargs)
self.track_type = None
self.track_name = None
self.bitrate = None
self.previous_timestamp = None
self.new_timestamp = None
self.timescale = None
self.discontinuity_gap = None
class MicrosoftTeamsUserIdentifierModel(msrest.serialization.Model):
_validation = {
'user_id': {'required': True},
}
_attribute_map = {
'user_id': {'key': 'userId', 'type': 'str'},
'is_anonymous': {'key': 'isAnonymous', 'type': 'bool'},
'cloud': {'key': 'cloud', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MicrosoftTeamsUserIdentifierModel, self).__init__(**kwargs)
self.user_id = kwargs['user_id']
self.is_anonymous = kwargs.get('is_anonymous', None)
self.cloud = kwargs.get('cloud', None)
class PhoneNumberIdentifierModel(msrest.serialization.Model):
_validation = {
'value': {'required': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PhoneNumberIdentifierModel, self).__init__(**kwargs)
self.value = kwargs['value']
class RedisExportRDBCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisExportRDBCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisImportRDBCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisImportRDBCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisPatchingCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisPatchingCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class RedisScalingCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RedisScalingCompletedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.name = kwargs.get('name', None)
self.status = kwargs.get('status', None)
class ResourceActionCancelData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceActionFailureData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceActionSuccessData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceActionSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteCancelData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteFailureData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceDeleteSuccessData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceDeleteSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteCancelData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteCancelData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteFailureData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteFailureData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ResourceWriteSuccessData(msrest.serialization.Model):
_attribute_map = {
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'subscription_id': {'key': 'subscriptionId', 'type': 'str'},
'resource_group': {'key': 'resourceGroup', 'type': 'str'},
'resource_provider': {'key': 'resourceProvider', 'type': 'str'},
'resource_uri': {'key': 'resourceUri', 'type': 'str'},
'operation_name': {'key': 'operationName', 'type': 'str'},
'status': {'key': 'status', 'type': 'str'},
'authorization': {'key': 'authorization', 'type': 'str'},
'claims': {'key': 'claims', 'type': 'str'},
'correlation_id': {'key': 'correlationId', 'type': 'str'},
'http_request': {'key': 'httpRequest', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceWriteSuccessData, self).__init__(**kwargs)
self.tenant_id = kwargs.get('tenant_id', None)
self.subscription_id = kwargs.get('subscription_id', None)
self.resource_group = kwargs.get('resource_group', None)
self.resource_provider = kwargs.get('resource_provider', None)
self.resource_uri = kwargs.get('resource_uri', None)
self.operation_name = kwargs.get('operation_name', None)
self.status = kwargs.get('status', None)
self.authorization = kwargs.get('authorization', None)
self.claims = kwargs.get('claims', None)
self.correlation_id = kwargs.get('correlation_id', None)
self.http_request = kwargs.get('http_request', None)
class ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData(msrest.serialization.Model):
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusActiveMessagesAvailableWithNoListenersEventData(msrest.serialization.Model):
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusActiveMessagesAvailableWithNoListenersEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData(msrest.serialization.Model):
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class ServiceBusDeadletterMessagesAvailableWithNoListenersEventData(msrest.serialization.Model):
_attribute_map = {
'namespace_name': {'key': 'namespaceName', 'type': 'str'},
'request_uri': {'key': 'requestUri', 'type': 'str'},
'entity_type': {'key': 'entityType', 'type': 'str'},
'queue_name': {'key': 'queueName', 'type': 'str'},
'topic_name': {'key': 'topicName', 'type': 'str'},
'subscription_name': {'key': 'subscriptionName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceBusDeadletterMessagesAvailableWithNoListenersEventData, self).__init__(**kwargs)
self.namespace_name = kwargs.get('namespace_name', None)
self.request_uri = kwargs.get('request_uri', None)
self.entity_type = kwargs.get('entity_type', None)
self.queue_name = kwargs.get('queue_name', None)
self.topic_name = kwargs.get('topic_name', None)
self.subscription_name = kwargs.get('subscription_name', None)
class SignalRServiceClientConnectionConnectedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'connection_id': {'key': 'connectionId', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SignalRServiceClientConnectionConnectedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.hub_name = kwargs.get('hub_name', None)
self.connection_id = kwargs.get('connection_id', None)
self.user_id = kwargs.get('user_id', None)
class SignalRServiceClientConnectionDisconnectedEventData(msrest.serialization.Model):
_attribute_map = {
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'},
'hub_name': {'key': 'hubName', 'type': 'str'},
'connection_id': {'key': 'connectionId', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'},
'error_message': {'key': 'errorMessage', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SignalRServiceClientConnectionDisconnectedEventData, self).__init__(**kwargs)
self.timestamp = kwargs.get('timestamp', None)
self.hub_name = kwargs.get('hub_name', None)
self.connection_id = kwargs.get('connection_id', None)
self.user_id = kwargs.get('user_id', None)
self.error_message = kwargs.get('error_message', None)
class StorageAsyncOperationInitiatedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageAsyncOperationInitiatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'e_tag': {'key': 'eTag', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'content_offset': {'key': 'contentOffset', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobCreatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.e_tag = kwargs.get('e_tag', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.content_offset = kwargs.get('content_offset', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobDeletedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobDeletedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobRenamedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'source_url': {'key': 'sourceUrl', 'type': 'str'},
'destination_url': {'key': 'destinationUrl', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobRenamedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.source_url = kwargs.get('source_url', None)
self.destination_url = kwargs.get('destination_url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageBlobTierChangedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'content_type': {'key': 'contentType', 'type': 'str'},
'content_length': {'key': 'contentLength', 'type': 'long'},
'blob_type': {'key': 'blobType', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageBlobTierChangedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.content_type = kwargs.get('content_type', None)
self.content_length = kwargs.get('content_length', None)
self.blob_type = kwargs.get('blob_type', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryCreatedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'e_tag': {'key': 'eTag', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryCreatedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.e_tag = kwargs.get('e_tag', None)
self.url = kwargs.get('url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryDeletedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'recursive': {'key': 'recursive', 'type': 'bool'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryDeletedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.url = kwargs.get('url', None)
self.recursive = kwargs.get('recursive', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageDirectoryRenamedEventData(msrest.serialization.Model):
_attribute_map = {
'api': {'key': 'api', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'source_url': {'key': 'sourceUrl', 'type': 'str'},
'destination_url': {'key': 'destinationUrl', 'type': 'str'},
'sequencer': {'key': 'sequencer', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'str'},
'storage_diagnostics': {'key': 'storageDiagnostics', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(StorageDirectoryRenamedEventData, self).__init__(**kwargs)
self.api = kwargs.get('api', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.source_url = kwargs.get('source_url', None)
self.destination_url = kwargs.get('destination_url', None)
self.sequencer = kwargs.get('sequencer', None)
self.identity = kwargs.get('identity', None)
self.storage_diagnostics = kwargs.get('storage_diagnostics', None)
class StorageLifecyclePolicyActionSummaryDetail(msrest.serialization.Model):
_attribute_map = {
'total_objects_count': {'key': 'totalObjectsCount', 'type': 'long'},
'success_count': {'key': 'successCount', 'type': 'long'},
'error_list': {'key': 'errorList', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(StorageLifecyclePolicyActionSummaryDetail, self).__init__(**kwargs)
self.total_objects_count = kwargs.get('total_objects_count', None)
self.success_count = kwargs.get('success_count', None)
self.error_list = kwargs.get('error_list', None)
class StorageLifecyclePolicyCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'schedule_time': {'key': 'scheduleTime', 'type': 'str'},
'delete_summary': {'key': 'deleteSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
'tier_to_cool_summary': {'key': 'tierToCoolSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
'tier_to_archive_summary': {'key': 'tierToArchiveSummary', 'type': 'StorageLifecyclePolicyActionSummaryDetail'},
}
def __init__(
self,
**kwargs
):
super(StorageLifecyclePolicyCompletedEventData, self).__init__(**kwargs)
self.schedule_time = kwargs.get('schedule_time', None)
self.delete_summary = kwargs.get('delete_summary', None)
self.tier_to_cool_summary = kwargs.get('tier_to_cool_summary', None)
self.tier_to_archive_summary = kwargs.get('tier_to_archive_summary', None)
class SubscriptionDeletedEventData(msrest.serialization.Model):
_validation = {
'event_subscription_id': {'readonly': True},
}
_attribute_map = {
'event_subscription_id': {'key': 'eventSubscriptionId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionDeletedEventData, self).__init__(**kwargs)
self.event_subscription_id = None
class SubscriptionValidationEventData(msrest.serialization.Model):
_validation = {
'validation_code': {'readonly': True},
'validation_url': {'readonly': True},
}
_attribute_map = {
'validation_code': {'key': 'validationCode', 'type': 'str'},
'validation_url': {'key': 'validationUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionValidationEventData, self).__init__(**kwargs)
self.validation_code = None
self.validation_url = None
class SubscriptionValidationResponse(msrest.serialization.Model):
_attribute_map = {
'validation_response': {'key': 'validationResponse', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubscriptionValidationResponse, self).__init__(**kwargs)
self.validation_response = kwargs.get('validation_response', None)
class WebAppServicePlanUpdatedEventData(msrest.serialization.Model):
_attribute_map = {
'app_service_plan_event_type_detail': {'key': 'appServicePlanEventTypeDetail', 'type': 'AppServicePlanEventTypeDetail'},
'sku': {'key': 'sku', 'type': 'WebAppServicePlanUpdatedEventDataSku'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppServicePlanUpdatedEventData, self).__init__(**kwargs)
self.app_service_plan_event_type_detail = kwargs.get('app_service_plan_event_type_detail', None)
self.sku = kwargs.get('sku', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebAppServicePlanUpdatedEventDataSku(msrest.serialization.Model):
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'Tier', 'type': 'str'},
'size': {'key': 'Size', 'type': 'str'},
'family': {'key': 'Family', 'type': 'str'},
'capacity': {'key': 'Capacity', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppServicePlanUpdatedEventDataSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.size = kwargs.get('size', None)
self.family = kwargs.get('family', None)
self.capacity = kwargs.get('capacity', None)
class WebAppUpdatedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebAppUpdatedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationFailedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebBackupOperationStartedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebBackupOperationStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationFailedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebRestoreOperationStartedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebRestoreOperationStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapCompletedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapCompletedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapFailedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapFailedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapStartedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapWithPreviewCancelledEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapWithPreviewCancelledEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
class WebSlotSwapWithPreviewStartedEventData(msrest.serialization.Model):
_attribute_map = {
'app_event_type_detail': {'key': 'appEventTypeDetail', 'type': 'AppEventTypeDetail'},
'name': {'key': 'name', 'type': 'str'},
'client_request_id': {'key': 'clientRequestId', 'type': 'str'},
'correlation_request_id': {'key': 'correlationRequestId', 'type': 'str'},
'request_id': {'key': 'requestId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'verb': {'key': 'verb', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebSlotSwapWithPreviewStartedEventData, self).__init__(**kwargs)
self.app_event_type_detail = kwargs.get('app_event_type_detail', None)
self.name = kwargs.get('name', None)
self.client_request_id = kwargs.get('client_request_id', None)
self.correlation_request_id = kwargs.get('correlation_request_id', None)
self.request_id = kwargs.get('request_id', None)
self.address = kwargs.get('address', None)
self.verb = kwargs.get('verb', None)
| true | true |
f71b922170a32d261f523c660af62772c3182168 | 5,687 | py | Python | mjmpc/control/olgaussian_mpc.py | mohakbhardwaj/mjmpc | 097e8d9bdaf0b3a15afa39030b2f53b00dfa25de | [
"Apache-2.0"
] | 2 | 2021-08-15T22:23:50.000Z | 2021-12-03T13:09:13.000Z | mjmpc/control/olgaussian_mpc.py | mohakbhardwaj/mjmpc | 097e8d9bdaf0b3a15afa39030b2f53b00dfa25de | [
"Apache-2.0"
] | null | null | null | mjmpc/control/olgaussian_mpc.py | mohakbhardwaj/mjmpc | 097e8d9bdaf0b3a15afa39030b2f53b00dfa25de | [
"Apache-2.0"
] | 1 | 2022-02-18T10:22:49.000Z | 2022-02-18T10:22:49.000Z | """
MPC with open-loop Gaussian policies
"""
from .controller import Controller
from mjmpc.utils.control_utils import generate_noise, scale_ctrl
import copy
import numpy as np
import scipy.special
class OLGaussianMPC(Controller):
def __init__(self,
d_state,
d_obs,
d_action,
action_lows,
action_highs,
horizon,
init_cov,
init_mean,
base_action,
num_particles,
gamma,
n_iters,
step_size,
filter_coeffs,
set_sim_state_fn=None,
rollout_fn=None,
cov_type='diagonal',
sample_mode='mean',
batch_size=1,
seed=0,
use_zero_control_seq=False):
"""
Parameters
__________
base_action : str
Action to append at the end when shifting solution to next timestep
'random' : appends random action
'null' : appends zero action
'repeat' : repeats second to last action
num_particles : int
Number of particles sampled at every iteration
"""
super(OLGaussianMPC, self).__init__(d_state,
d_obs,
d_action,
action_lows,
action_highs,
horizon,
gamma,
n_iters,
set_sim_state_fn,
rollout_fn,
sample_mode,
batch_size,
seed)
self.init_cov = np.array([init_cov] * self.d_action)
self.init_mean = init_mean.copy()
self.mean_action = init_mean
self.base_action = base_action
self.num_particles = num_particles
self.cov_type = cov_type
self.cov_action = np.diag(self.init_cov)
self.step_size = step_size
self.filter_coeffs = filter_coeffs
self.use_zero_control_seq = use_zero_control_seq
def _get_next_action(self, state, mode='mean'):
if mode == 'mean':
next_action = self.mean_action[0].copy()
elif mode == 'sample':
delta = generate_noise(self.cov_action, self.filter_coeffs,
shape=(1, 1), base_seed=self.seed_val + 123*self.num_steps)
next_action = self.mean_action[0].copy() + delta.reshape(self.d_action).copy()
else:
raise ValueError('Unidentified sampling mode in get_next_action')
return next_action
# def sample_actions(self):
# delta = generate_noise(self.cov_action, self.filter_coeffs,
# shape=(self.num_particles, self.horizon),
# base_seed = self.seed_val + self.num_steps)
# act_seq = self.mean_action[None, :, :] + delta
# # act_seq = scale_ctrl(act_seq, self.action_lows, self.action_highs)
# return np.array(act_seq)
def sample_noise(self):
delta = generate_noise(self.cov_action, self.filter_coeffs,
shape=(self.num_particles, self.horizon),
base_seed = self.seed_val + self.num_steps)
# act_seq = scale_ctrl(act_seq, self.action_lows, self.action_highs)
return delta
def generate_rollouts(self, state):
"""
Samples a batch of actions, rolls out trajectories for each particle
and returns the resulting observations, costs,
actions
Parameters
----------
state : dict or np.ndarray
Initial state to set the simulation env to
"""
self._set_sim_state_fn(copy.deepcopy(state)) #set state of simulation
# input('....')
delta = self.sample_noise() #sample noise from covariance of current control distribution
if self.use_zero_control_seq:
delta[-1,:] = -1.0 * self.mean_action.copy()
trajectories = self._rollout_fn(self.num_particles, self.horizon,
self.mean_action, delta, mode="open_loop")
return trajectories
def _shift(self):
"""
Predict good parameters for the next time step by
shifting the mean forward one step
"""
self.mean_action[:-1] = self.mean_action[1:]
if self.base_action == 'random':
self.mean_action[-1] = np.random.normal(0, self.init_cov, self.d_action)
elif self.base_action == 'null':
self.mean_action[-1] = np.zeros((self.d_action, ))
elif self.base_action == 'repeat':
self.mean_action[-1] = self.mean_action[-2]
else:
raise NotImplementedError("invalid option for base action during shift")
def reset(self):
self.num_steps = 0
self.mean_action = np.zeros(shape=(self.horizon, self.d_action))
self.cov_action = np.diag(self.init_cov)
self.gamma_seq = np.cumprod([1.0] + [self.gamma] * (self.horizon - 1)).reshape(1, self.horizon)
def _calc_val(self, cost_seq, act_seq):
raise NotImplementedError("_calc_val not implemented")
| 40.621429 | 103 | 0.523475 | from .controller import Controller
from mjmpc.utils.control_utils import generate_noise, scale_ctrl
import copy
import numpy as np
import scipy.special
class OLGaussianMPC(Controller):
def __init__(self,
d_state,
d_obs,
d_action,
action_lows,
action_highs,
horizon,
init_cov,
init_mean,
base_action,
num_particles,
gamma,
n_iters,
step_size,
filter_coeffs,
set_sim_state_fn=None,
rollout_fn=None,
cov_type='diagonal',
sample_mode='mean',
batch_size=1,
seed=0,
use_zero_control_seq=False):
super(OLGaussianMPC, self).__init__(d_state,
d_obs,
d_action,
action_lows,
action_highs,
horizon,
gamma,
n_iters,
set_sim_state_fn,
rollout_fn,
sample_mode,
batch_size,
seed)
self.init_cov = np.array([init_cov] * self.d_action)
self.init_mean = init_mean.copy()
self.mean_action = init_mean
self.base_action = base_action
self.num_particles = num_particles
self.cov_type = cov_type
self.cov_action = np.diag(self.init_cov)
self.step_size = step_size
self.filter_coeffs = filter_coeffs
self.use_zero_control_seq = use_zero_control_seq
def _get_next_action(self, state, mode='mean'):
if mode == 'mean':
next_action = self.mean_action[0].copy()
elif mode == 'sample':
delta = generate_noise(self.cov_action, self.filter_coeffs,
shape=(1, 1), base_seed=self.seed_val + 123*self.num_steps)
next_action = self.mean_action[0].copy() + delta.reshape(self.d_action).copy()
else:
raise ValueError('Unidentified sampling mode in get_next_action')
return next_action
lf.cov_action, self.filter_coeffs,
shape=(self.num_particles, self.horizon),
base_seed = self.seed_val + self.num_steps)
return delta
def generate_rollouts(self, state):
self._set_sim_state_fn(copy.deepcopy(state))
delta = self.sample_noise()
if self.use_zero_control_seq:
delta[-1,:] = -1.0 * self.mean_action.copy()
trajectories = self._rollout_fn(self.num_particles, self.horizon,
self.mean_action, delta, mode="open_loop")
return trajectories
def _shift(self):
self.mean_action[:-1] = self.mean_action[1:]
if self.base_action == 'random':
self.mean_action[-1] = np.random.normal(0, self.init_cov, self.d_action)
elif self.base_action == 'null':
self.mean_action[-1] = np.zeros((self.d_action, ))
elif self.base_action == 'repeat':
self.mean_action[-1] = self.mean_action[-2]
else:
raise NotImplementedError("invalid option for base action during shift")
def reset(self):
self.num_steps = 0
self.mean_action = np.zeros(shape=(self.horizon, self.d_action))
self.cov_action = np.diag(self.init_cov)
self.gamma_seq = np.cumprod([1.0] + [self.gamma] * (self.horizon - 1)).reshape(1, self.horizon)
def _calc_val(self, cost_seq, act_seq):
raise NotImplementedError("_calc_val not implemented")
| true | true |
f71b92878fc1fad9e2f4829b6b8365831bd39735 | 612 | py | Python | combine/indicator/combination_indicator.py | cwwang15/fudan-monte-carlo-pwd | 807a4d9f45112ed6520a08d14ea65ca79efe33ea | [
"Apache-2.0"
] | 1 | 2021-08-04T09:51:55.000Z | 2021-08-04T09:51:55.000Z | combine/indicator/combination_indicator.py | cwwang15/pwd-monte-carlo | 807a4d9f45112ed6520a08d14ea65ca79efe33ea | [
"Apache-2.0"
] | null | null | null | combine/indicator/combination_indicator.py | cwwang15/pwd-monte-carlo | 807a4d9f45112ed6520a08d14ea65ca79efe33ea | [
"Apache-2.0"
] | null | null | null | import abc
class CombinationIndicator(metaclass=abc.ABCMeta):
def __init__(self, threshold: float):
self.__threshold: float = threshold
@property
def threshold(self):
return self.__threshold
@threshold.setter
def threshold(self, new_threshold: float):
self.__threshold = new_threshold
pass
def can_combine(self, master_set: set, servant_set: set) -> bool:
return self.similarity(master_set, servant_set) >= self.threshold
pass
@abc.abstractmethod
def similarity(self, master_set: set, servant_set: set) -> float:
pass
| 25.5 | 73 | 0.676471 | import abc
class CombinationIndicator(metaclass=abc.ABCMeta):
def __init__(self, threshold: float):
self.__threshold: float = threshold
@property
def threshold(self):
return self.__threshold
@threshold.setter
def threshold(self, new_threshold: float):
self.__threshold = new_threshold
pass
def can_combine(self, master_set: set, servant_set: set) -> bool:
return self.similarity(master_set, servant_set) >= self.threshold
pass
@abc.abstractmethod
def similarity(self, master_set: set, servant_set: set) -> float:
pass
| true | true |
f71b95dcc7666004de7d0b909f2b67e00806bb40 | 1,523 | py | Python | simulation/src/simulation_evaluation/src/state_machine/state_machines/priority.py | KITcar-Team/kitcar-gazebo-simulation | 8a9438b5a24c288721ae0302889fe55e26046310 | [
"MIT"
] | 13 | 2020-06-30T17:18:28.000Z | 2021-07-20T16:55:35.000Z | simulation/src/simulation_evaluation/src/state_machine/state_machines/priority.py | KITcar-Team/kitcar-gazebo-simulation | 8a9438b5a24c288721ae0302889fe55e26046310 | [
"MIT"
] | 1 | 2020-11-10T20:15:42.000Z | 2020-12-25T18:27:56.000Z | simulation/src/simulation_evaluation/src/state_machine/state_machines/priority.py | KITcar-Team/kitcar-gazebo-simulation | 8a9438b5a24c288721ae0302889fe55e26046310 | [
"MIT"
] | 3 | 2020-07-20T09:09:08.000Z | 2021-07-20T17:00:37.000Z | """PriorityStateMachine keeps track of stoping or halting in front of stop or halt lines.
See :mod:`simulation.src.simulation_evaluation.src.state_machine.states.priority` for
implementation details of the states used in this StateMachine.
"""
from typing import Callable
from simulation.src.simulation_evaluation.src.state_machine.states.priority import (
FailureInStopZone,
InHaltZone,
InStopZone,
Off,
SuccessfullyStopped,
)
from .state_machine import StateMachine
__copyright__ = "KITcar"
class PriorityStateMachine(StateMachine):
"""Keep track of stoping and halting in front of stop or halt lines."""
off: "State" = Off() # noqa: F821
"""Default state"""
in_stop_zone: "State" = InStopZone() # noqa: F821
"""The car is inside a stop zone"""
in_halt_zone: "State" = InHaltZone() # noqa: F821
"""The car is inside a halt zone"""
successfully_stopped: "State" = SuccessfullyStopped() # noqa: F821
"""The car successfully stopes in the stop zone"""
failure_in_stop_zone: "State" = FailureInStopZone() # noqa: F821
"""End state when the car does not stop inside the stop zone"""
def __init__(self, callback: Callable[[], None]):
"""Initialize PriorityStateMachine.
Arguments:
callback: Function which gets executed when the state changes
"""
super().__init__(
state_machine=self.__class__,
initial_state=PriorityStateMachine.off,
callback=callback,
)
| 32.404255 | 89 | 0.688116 |
from typing import Callable
from simulation.src.simulation_evaluation.src.state_machine.states.priority import (
FailureInStopZone,
InHaltZone,
InStopZone,
Off,
SuccessfullyStopped,
)
from .state_machine import StateMachine
__copyright__ = "KITcar"
class PriorityStateMachine(StateMachine):
off: "State" = Off()
in_stop_zone: "State" = InStopZone()
in_halt_zone: "State" = InHaltZone()
successfully_stopped: "State" = SuccessfullyStopped()
failure_in_stop_zone: "State" = FailureInStopZone()
def __init__(self, callback: Callable[[], None]):
super().__init__(
state_machine=self.__class__,
initial_state=PriorityStateMachine.off,
callback=callback,
)
| true | true |
f71b962aa0b18da3f6fe8e52d30897d155ad960b | 1,042 | py | Python | tests/test_pitch.py | AishaSharif/Pitch-Blog | c5d8cd462246bca96aabeca05817ed41bb7f2d0c | [
"MIT"
] | null | null | null | tests/test_pitch.py | AishaSharif/Pitch-Blog | c5d8cd462246bca96aabeca05817ed41bb7f2d0c | [
"MIT"
] | null | null | null | tests/test_pitch.py | AishaSharif/Pitch-Blog | c5d8cd462246bca96aabeca05817ed41bb7f2d0c | [
"MIT"
] | null | null | null | import unittest
from app.models import Pitch,User
from flask_login import current_user
from app import db
class TestComment(unittest.TestCase):
def setUp(self):
self.user_Lelabo = User(username = 'Lelabo',password = '123Pass', email = 'mail@lelabo.com')
self.new_pitch = Pitch(pitch_id=12345,pitch_title='Pitch Title'user = self.user_Lelabo )
def tearDown(self):
Pitch.query.delete()
User.query.delete()
def test_instance(self):
self.assertTrue(isinstance(self.new_pitch,Pitch))
def test_check_instance_variables(self):
self.assertEquals(self.new_pitch)
self.assertEquals(self.new_pitch.pitch_title,'Pitch Title')
self.assertEquals(self.new_pitch.user,self.user_Lelabo)
def test_save_pitch(self):
self.new_review.save_pitch()
self.assertTrue(len(Pitch.query.all())>0)
def test_get_pitch_by_id(self):
self.new_review.save_pitch()
got_reviews = Pitch.get_pitch(12345)
self.assertTrue(len(got_pitch) == 1) | 28.944444 | 100 | 0.697697 | import unittest
from app.models import Pitch,User
from flask_login import current_user
from app import db
class TestComment(unittest.TestCase):
def setUp(self):
self.user_Lelabo = User(username = 'Lelabo',password = '123Pass', email = 'mail@lelabo.com')
self.new_pitch = Pitch(pitch_id=12345,pitch_title='Pitch Title'user = self.user_Lelabo )
def tearDown(self):
Pitch.query.delete()
User.query.delete()
def test_instance(self):
self.assertTrue(isinstance(self.new_pitch,Pitch))
def test_check_instance_variables(self):
self.assertEquals(self.new_pitch)
self.assertEquals(self.new_pitch.pitch_title,'Pitch Title')
self.assertEquals(self.new_pitch.user,self.user_Lelabo)
def test_save_pitch(self):
self.new_review.save_pitch()
self.assertTrue(len(Pitch.query.all())>0)
def test_get_pitch_by_id(self):
self.new_review.save_pitch()
got_reviews = Pitch.get_pitch(12345)
self.assertTrue(len(got_pitch) == 1) | false | true |
f71b9795d1f9e2621b52a1fb8f3fffa662517f05 | 6,626 | py | Python | wizmann-pic/18-11-19/encrypt.py | Wizmann/assets | 1a34a18e65bc4c57676f9a04d6eb5c2a3806fcfc | [
"MIT"
] | null | null | null | wizmann-pic/18-11-19/encrypt.py | Wizmann/assets | 1a34a18e65bc4c57676f9a04d6eb5c2a3806fcfc | [
"MIT"
] | null | null | null | wizmann-pic/18-11-19/encrypt.py | Wizmann/assets | 1a34a18e65bc4c57676f9a04d6eb5c2a3806fcfc | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# Copyright 2012-2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import random
import string
import binascii
from shadowsocks import common
from shadowsocks.crypto import rc4_md5, openssl, sodium, table
NONCE_RANGE = (32, 512)
NONCE_CONSTANT = binascii.unhexlify('deadbeef')
def make_nonce():
nonce_length = random.randint(*NONCE_RANGE)
nonce = ''.join(
[random.choice(string.ascii_letters) for i in xrange(nonce_length)])
return NONCE_CONSTANT + nonce + NONCE_CONSTANT
method_supported = {}
method_supported.update(rc4_md5.ciphers)
method_supported.update(openssl.ciphers)
method_supported.update(sodium.ciphers)
method_supported.update(table.ciphers)
def random_string(length):
return os.urandom(length)
cached_keys = {}
def try_cipher(key, method=None):
Encryptor(key, method)
def EVP_BytesToKey(password, key_len, iv_len):
# equivalent to OpenSSL's EVP_BytesToKey() with count 1
# so that we make the same key and iv as nodejs version
cached_key = '%s-%d-%d' % (password, key_len, iv_len)
r = cached_keys.get(cached_key, None)
if r:
return r
m = []
i = 0
while len(b''.join(m)) < (key_len + iv_len):
md5 = hashlib.md5()
data = password
if i > 0:
data = m[i - 1] + password
md5.update(data)
m.append(md5.digest())
i += 1
ms = b''.join(m)
key = ms[:key_len]
iv = ms[key_len:key_len + iv_len]
cached_keys[cached_key] = (key, iv)
return key, iv
class Encryptor(object):
def __init__(self, key, method):
self.key = key
self.method = method
self.iv = None
self.iv_sent = False
self.cipher_iv = b''
self.decipher = None
method = method.lower()
self._method_info = self.get_method_info(method)
self.obf_buffer = ''
self.obf_max_length = random.randint(NONCE_RANGE[1], 4096)
self.obf_flag = 0
if self._method_info:
self.cipher = self.get_cipher(key, method, 1,
random_string(self._method_info[1]))
else:
logging.error('method %s not supported' % method)
sys.exit(1)
def get_method_info(self, method):
method = method.lower()
m = method_supported.get(method)
return m
def iv_len(self):
return len(self.cipher_iv)
def get_cipher(self, password, method, op, iv):
password = common.to_bytes(password)
m = self._method_info
if m[0] > 0:
key, iv_ = EVP_BytesToKey(password, m[0], m[1])
else:
# key_length == 0 indicates we should use the key directly
key, iv = password, b''
iv = iv[:m[1]]
if op == 1:
# this iv is for cipher not decipher
self.cipher_iv = iv[:m[1]]
return m[2](method, key, iv, op)
def encrypt(self, buf):
if len(buf) == 0:
return buf
if self.iv_sent:
return self.cipher.update(buf)
else:
self.iv_sent = True
nonce = make_nonce()
return self.cipher_iv + self.cipher.update(nonce + buf)
def decrypt(self, buf):
if len(buf) == 0:
return buf
if self.obf_flag == -1:
return ''
if self.decipher is None:
decipher_iv_len = self._method_info[1]
decipher_iv = buf[:decipher_iv_len]
self.decipher = self.get_cipher(self.key, self.method, 0,
iv=decipher_iv)
buf = buf[decipher_iv_len:]
if len(buf) == 0:
return buf
res = self.decipher.update(buf)
self.obf_buffer += res
if self.obf_flag:
return res
if self.obf_buffer.startswith(NONCE_CONSTANT) \
and self.obf_buffer.index(NONCE_CONSTANT, 1) > 0:
self.obf_flag = 1
pos = self.obf_buffer.index(NONCE_CONSTANT, 1)
return self.obf_buffer[pos + len(NONCE_CONSTANT):]
elif len(self.obf_buffer) > self.obf_max_length:
self.obf_flag = -1
return ''
def encrypt_all(password, method, op, data):
result = []
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if key_len > 0:
key, _ = EVP_BytesToKey(password, key_len, iv_len)
else:
key = password
if op:
iv = random_string(iv_len)
result.append(iv)
nonce = make_nonce()
data = nonce + data
cipher = m(method, key, iv, op)
result.append(cipher.update(data))
return b''.join(result)
else:
iv = data[:iv_len]
data = data[iv_len:]
cipher = m(method, key, iv, op)
data = cipher.update(data)
if data.startswith(NONCE_CONSTANT) and data.index(NONCE_CONSTANT, 1) > 0:
pos = data.index(NONCE_CONSTANT, 1)
data = data[pos + len(NONCE_CONSTANT):]
else:
data = ''
return data
CIPHERS_TO_TEST = [
'aes-128-cfb',
'aes-256-cfb',
'rc4-md5',
'salsa20',
'chacha20',
'table',
]
def test_encryptor():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
encryptor = Encryptor(b'key', method)
decryptor = Encryptor(b'key', method)
for i in xrange(100):
cipher = encryptor.encrypt(plain)
plain2 = decryptor.decrypt(cipher)
assert plain == plain2
def test_encrypt_all():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
cipher = encrypt_all(b'key', method, 1, plain)
plain2 = encrypt_all(b'key', method, 0, cipher)
assert plain == plain2
if __name__ == '__main__':
test_encrypt_all()
test_encryptor()
| 27.957806 | 81 | 0.601419 |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import random
import string
import binascii
from shadowsocks import common
from shadowsocks.crypto import rc4_md5, openssl, sodium, table
NONCE_RANGE = (32, 512)
NONCE_CONSTANT = binascii.unhexlify('deadbeef')
def make_nonce():
nonce_length = random.randint(*NONCE_RANGE)
nonce = ''.join(
[random.choice(string.ascii_letters) for i in xrange(nonce_length)])
return NONCE_CONSTANT + nonce + NONCE_CONSTANT
method_supported = {}
method_supported.update(rc4_md5.ciphers)
method_supported.update(openssl.ciphers)
method_supported.update(sodium.ciphers)
method_supported.update(table.ciphers)
def random_string(length):
return os.urandom(length)
cached_keys = {}
def try_cipher(key, method=None):
Encryptor(key, method)
def EVP_BytesToKey(password, key_len, iv_len):
# so that we make the same key and iv as nodejs version
cached_key = '%s-%d-%d' % (password, key_len, iv_len)
r = cached_keys.get(cached_key, None)
if r:
return r
m = []
i = 0
while len(b''.join(m)) < (key_len + iv_len):
md5 = hashlib.md5()
data = password
if i > 0:
data = m[i - 1] + password
md5.update(data)
m.append(md5.digest())
i += 1
ms = b''.join(m)
key = ms[:key_len]
iv = ms[key_len:key_len + iv_len]
cached_keys[cached_key] = (key, iv)
return key, iv
class Encryptor(object):
def __init__(self, key, method):
self.key = key
self.method = method
self.iv = None
self.iv_sent = False
self.cipher_iv = b''
self.decipher = None
method = method.lower()
self._method_info = self.get_method_info(method)
self.obf_buffer = ''
self.obf_max_length = random.randint(NONCE_RANGE[1], 4096)
self.obf_flag = 0
if self._method_info:
self.cipher = self.get_cipher(key, method, 1,
random_string(self._method_info[1]))
else:
logging.error('method %s not supported' % method)
sys.exit(1)
def get_method_info(self, method):
method = method.lower()
m = method_supported.get(method)
return m
def iv_len(self):
return len(self.cipher_iv)
def get_cipher(self, password, method, op, iv):
password = common.to_bytes(password)
m = self._method_info
if m[0] > 0:
key, iv_ = EVP_BytesToKey(password, m[0], m[1])
else:
# key_length == 0 indicates we should use the key directly
key, iv = password, b''
iv = iv[:m[1]]
if op == 1:
# this iv is for cipher not decipher
self.cipher_iv = iv[:m[1]]
return m[2](method, key, iv, op)
def encrypt(self, buf):
if len(buf) == 0:
return buf
if self.iv_sent:
return self.cipher.update(buf)
else:
self.iv_sent = True
nonce = make_nonce()
return self.cipher_iv + self.cipher.update(nonce + buf)
def decrypt(self, buf):
if len(buf) == 0:
return buf
if self.obf_flag == -1:
return ''
if self.decipher is None:
decipher_iv_len = self._method_info[1]
decipher_iv = buf[:decipher_iv_len]
self.decipher = self.get_cipher(self.key, self.method, 0,
iv=decipher_iv)
buf = buf[decipher_iv_len:]
if len(buf) == 0:
return buf
res = self.decipher.update(buf)
self.obf_buffer += res
if self.obf_flag:
return res
if self.obf_buffer.startswith(NONCE_CONSTANT) \
and self.obf_buffer.index(NONCE_CONSTANT, 1) > 0:
self.obf_flag = 1
pos = self.obf_buffer.index(NONCE_CONSTANT, 1)
return self.obf_buffer[pos + len(NONCE_CONSTANT):]
elif len(self.obf_buffer) > self.obf_max_length:
self.obf_flag = -1
return ''
def encrypt_all(password, method, op, data):
result = []
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if key_len > 0:
key, _ = EVP_BytesToKey(password, key_len, iv_len)
else:
key = password
if op:
iv = random_string(iv_len)
result.append(iv)
nonce = make_nonce()
data = nonce + data
cipher = m(method, key, iv, op)
result.append(cipher.update(data))
return b''.join(result)
else:
iv = data[:iv_len]
data = data[iv_len:]
cipher = m(method, key, iv, op)
data = cipher.update(data)
if data.startswith(NONCE_CONSTANT) and data.index(NONCE_CONSTANT, 1) > 0:
pos = data.index(NONCE_CONSTANT, 1)
data = data[pos + len(NONCE_CONSTANT):]
else:
data = ''
return data
CIPHERS_TO_TEST = [
'aes-128-cfb',
'aes-256-cfb',
'rc4-md5',
'salsa20',
'chacha20',
'table',
]
def test_encryptor():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
encryptor = Encryptor(b'key', method)
decryptor = Encryptor(b'key', method)
for i in xrange(100):
cipher = encryptor.encrypt(plain)
plain2 = decryptor.decrypt(cipher)
assert plain == plain2
def test_encrypt_all():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
cipher = encrypt_all(b'key', method, 1, plain)
plain2 = encrypt_all(b'key', method, 0, cipher)
assert plain == plain2
if __name__ == '__main__':
test_encrypt_all()
test_encryptor()
| true | true |
f71b97d646bf147a35345ec60a2da27de1631ea8 | 968 | py | Python | mysite/mysite/urls.py | FullGhettoAlchemist/cepheusProduction | 951c244d454fafa817b34dd37aaea28a10afa655 | [
"MIT"
] | null | null | null | mysite/mysite/urls.py | FullGhettoAlchemist/cepheusProduction | 951c244d454fafa817b34dd37aaea28a10afa655 | [
"MIT"
] | null | null | null | mysite/mysite/urls.py | FullGhettoAlchemist/cepheusProduction | 951c244d454fafa817b34dd37aaea28a10afa655 | [
"MIT"
] | null | null | null | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^position/$', views.position, name='position'),
url(r'^details/$', views.details, name='details'),
]
| 35.851852 | 80 | 0.670455 | from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^position/$', views.position, name='position'),
url(r'^details/$', views.details, name='details'),
]
| true | true |
f71b995b9c4ad66cf9f2feb286b113ed39ca86d1 | 8,848 | py | Python | STS_v2/compute_high_low_limit_v3.py | kite8/quant_learning | d823974cd2b5a6b8e2a20fe42d7334051fa46ea0 | [
"MIT"
] | 1 | 2019-02-22T08:12:41.000Z | 2019-02-22T08:12:41.000Z | STS_v2/compute_high_low_limit_v3.py | kite8/quant_learning | d823974cd2b5a6b8e2a20fe42d7334051fa46ea0 | [
"MIT"
] | null | null | null | STS_v2/compute_high_low_limit_v3.py | kite8/quant_learning | d823974cd2b5a6b8e2a20fe42d7334051fa46ea0 | [
"MIT"
] | 5 | 2019-02-22T08:14:09.000Z | 2020-06-28T05:54:39.000Z | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 15:19:45 2018
@author: kite
"""
import datetime, time
from pymongo import UpdateOne, ASCENDING, UpdateMany
from database import DB_CONN
from stock_util import get_trading_dates, get_all_codes
import tushare as ts
import numpy as np
import pandas as pd
import requests
import json
import datetime
"""
计算涨跌停价格
只要获取到前一天的价格
获取name和上市日期
最新ipo规则
如果是上市当天,则涨停价是上市发行价格的1.44倍
所以需要获取到发行价格
要不是
"""
# 获取发行价格并保存到数据库中
def fill_issueprice_and_timeToMarket():
"""
ipo_info.xlsx 是从东方choice中提取出来;
columns:
code -- 股票代码
name -- 股票当前名字
issueprice -- 发行价格
timeToMarket -- 上市时间
"""
df = pd.read_excel('data/ipo_info.xlsx', header=0, dtype={'code':str})
df = df.set_index('code')
codes = df.index.tolist()
update_requests = []
for i,code in enumerate(codes):
try:
update_requests.append(
UpdateOne(
{'code':code},
{'$set':{'issueprice':df.issueprice[code],
'timeToMarket':df.timeToMarket[code]}},
upsert=True))
except:
print('code: %s, has problem' % code)
if len(update_requests)>0:
update_result = DB_CONN['basic'].bulk_write(update_requests, ordered=False)
print('填充字段, 字段名: issueprice,数据集:%s,插入:%4d条,更新:%4d条' %
('basic', update_result.upserted_count, update_result.modified_count), flush=True)
def fixing_is_st(start, end):
# 第一阶段
df = pd.read_excel('data/stock_basic.xlsx', header=0, dtype={'code':str})
df = df.set_index('code')
codes = df[df['是否ST过'] == 1].index.tolist()
total = len(codes)
# all_dates = get_trading_dates(start, end)
daily = DB_CONN['daily']
excel_name = 'data/st_info.xlsx'
for i in range(4):
if i == 0:
all_dates = get_trading_dates('2015-01-01', '2015-12-31')
elif i == 1:
all_dates = get_trading_dates('2016-01-01', '2016-12-31')
if i == 2:
all_dates = get_trading_dates('2017-01-01', '2017-12-31')
elif i == 3:
all_dates = get_trading_dates('2018-01-01', '2018-09-30')
print('数据读取中')
df = pd.read_excel(excel_name, i, header=0, dtype={'code':str})
df = df.set_index(['code','state'])
df.columns = df.columns.astype(np.datetime64)
df.columns = df.columns.to_period('D')
df.columns = df.columns.astype('str')
print('数据读取完毕')
for j, code in enumerate(codes):
update_requests = []
for date in all_dates:
try:
st_state = df.xs([code])[date]['是否ST']
sst_state = df.xs([code])[date]['是否*ST']
if (st_state == '否') and (sst_state == '否'):
is_st_flag = False
else:
is_st_flag = True
update_requests.append(
UpdateOne(
{'code':code, 'date':date, 'index':False},
{'$set':{'is_st':is_st_flag}}
)
)
except:
print('something is wrong, code : %s, date : %s' % (code, date))
if len(update_requests)>0:
update_result = daily.bulk_write(update_requests, ordered=False)
print('第%s年填充进度: %s/%s, 字段名: is_st,数据集:%s,插入:%4d条,更新:%4d条' %
(i+1, j+1, total, 'daily', update_result.upserted_count, update_result.modified_count), flush=True)
def fill_high_and_low_price_between(start, end):
"""
for code in codes:
timeToMarket = basic.find()
for
"""
# st_mark = ['st', 'ST', '*st', '*ST']
codes = ts.get_stock_basics().index.tolist()
_df = pd.read_excel('data/stock_basic.xlsx', header=0, dtype={'code':str})
_df = _df.set_index('code')
st_codes = _df[_df['是否ST过'] == 1].index.tolist()
total = len(codes)
error_code = []
for i,code in enumerate(codes):
try:
timeToMarket = DB_CONN['basic'].find_one({'code':code},
projection={'code':True, 'timeToMarket':True, '_id':False})['timeToMarket']
except:
error_code.append(code)
continue
daily_cursor = DB_CONN['daily'].find(
{'code':code, 'date':{'$lte': end, '$gte': timeToMarket}, 'index':False},
projection={'code':True, 'date':True, 'pre_close':True, '_id':False})
update_requests = []
for j,daily in enumerate(daily_cursor):
date = daily['date']
try:
pre_close = daily['pre_close']
except:
if (j == 0) & (timeToMarket != date):
pass
# print('code: %s, time: %s, 数据初始日没有pre_close' % (code, date))
elif timeToMarket == date:
# print('code: %s, date: %s' % (code, date))
issueprice = DB_CONN['basic'].find_one({'code':code},
projection={'issueprice':True, '_id':False})['issueprice']
high_limit = np.round(np.round(issueprice * 1.2, 2) * 1.2, 2)
low_limit = np.round(np.round(issueprice * 0.8, 2) * 0.8, 2)
update_requests.append(
UpdateOne({'code':code, 'date':date, 'index':False},
{'$set':{'high_limit':high_limit, 'low_limit':low_limit}},
upsert=True))
else:
print('code: %s, time: %s, ipo_date: %s, 请速查原因' % (code, date, timeToMarket))
error_code.append(code)
continue
# if date < '2016-08-09':
# _date = '2016-08-09'
# else:
# _date = date
#
# try:
# name = DB_CONN['basic'].find_one({'code':code, 'date':_date},
# projection={'name':True, '_id':False})['name']
# last_name = name
# except:
# if j == 0:
# name = DB_CONN['basic'].find_one({'code':code},
# projection={'name':True, '_id':False})['name']
# last_name = name
# else:
## print('code: %s, date: %s' % (code, date))
# name = last_name
# if timeToMarket == date:
#
# issueprice = DB_CONN['basic'].find_one({'code':code},
# projection={'issueprice':True, '_id':False})['issueprice']
#
# high_limit = np.round(np.round(issueprice * 1.2, 2) * 1.2, 2)
# low_limit = np.round(np.round(issueprice * 0.8, 2) * 0.8, 2)
# if daily['is_st'] :
if code in st_codes:
st_flag = DB_CONN['daily'].find_one({'code':code, 'date':date, 'index':False})['is_st']
if st_flag:
high_limit = np.round(pre_close * 1.05, 2)
low_limit = np.round(pre_close * 0.95, 2)
else:
high_limit = np.round(pre_close * 1.1, 2)
low_limit = np.round(pre_close * 0.9, 2)
update_requests.append(
UpdateOne({'code':code, 'date':date, 'index':False},
{'$set':{'high_limit':high_limit, 'low_limit':low_limit}},
upsert=True))
if len(update_requests)>0:
update_result = DB_CONN['daily'].bulk_write(update_requests, ordered=False)
print('涨跌停计算, 进度: (%s/%s), code:%s, 数据集:%s, 插入:%4d条, 更新:%4d条' %
(i+1, total, code, 'daily', update_result.upserted_count, update_result.modified_count), flush=True)
# print('stock: %s high low limit complish, 进度: (%s/%s)' % (code, i+1, total), flush=True)
# main funciton
if __name__ == '__main__':
daily_col = DB_CONN['daily']
if 'code_1_index_1' not in daily_col.index_information().keys():
daily_col.create_index(
[('code', ASCENDING), ('index', ASCENDING)]
)
start = '2015-01-01'
end = '2018-09-30'
tic = time.process_time()
fixing_is_st(start, end)
# fill_issueprice_and_timeToMarket()
fill_high_and_low_price_between(start, end)
toc = time.process_time()
delta = toc - tic
print(delta) | 36.561983 | 125 | 0.495592 |
import datetime, time
from pymongo import UpdateOne, ASCENDING, UpdateMany
from database import DB_CONN
from stock_util import get_trading_dates, get_all_codes
import tushare as ts
import numpy as np
import pandas as pd
import requests
import json
import datetime
def fill_issueprice_and_timeToMarket():
df = pd.read_excel('data/ipo_info.xlsx', header=0, dtype={'code':str})
df = df.set_index('code')
codes = df.index.tolist()
update_requests = []
for i,code in enumerate(codes):
try:
update_requests.append(
UpdateOne(
{'code':code},
{'$set':{'issueprice':df.issueprice[code],
'timeToMarket':df.timeToMarket[code]}},
upsert=True))
except:
print('code: %s, has problem' % code)
if len(update_requests)>0:
update_result = DB_CONN['basic'].bulk_write(update_requests, ordered=False)
print('填充字段, 字段名: issueprice,数据集:%s,插入:%4d条,更新:%4d条' %
('basic', update_result.upserted_count, update_result.modified_count), flush=True)
def fixing_is_st(start, end):
df = pd.read_excel('data/stock_basic.xlsx', header=0, dtype={'code':str})
df = df.set_index('code')
codes = df[df['是否ST过'] == 1].index.tolist()
total = len(codes)
daily = DB_CONN['daily']
excel_name = 'data/st_info.xlsx'
for i in range(4):
if i == 0:
all_dates = get_trading_dates('2015-01-01', '2015-12-31')
elif i == 1:
all_dates = get_trading_dates('2016-01-01', '2016-12-31')
if i == 2:
all_dates = get_trading_dates('2017-01-01', '2017-12-31')
elif i == 3:
all_dates = get_trading_dates('2018-01-01', '2018-09-30')
print('数据读取中')
df = pd.read_excel(excel_name, i, header=0, dtype={'code':str})
df = df.set_index(['code','state'])
df.columns = df.columns.astype(np.datetime64)
df.columns = df.columns.to_period('D')
df.columns = df.columns.astype('str')
print('数据读取完毕')
for j, code in enumerate(codes):
update_requests = []
for date in all_dates:
try:
st_state = df.xs([code])[date]['是否ST']
sst_state = df.xs([code])[date]['是否*ST']
if (st_state == '否') and (sst_state == '否'):
is_st_flag = False
else:
is_st_flag = True
update_requests.append(
UpdateOne(
{'code':code, 'date':date, 'index':False},
{'$set':{'is_st':is_st_flag}}
)
)
except:
print('something is wrong, code : %s, date : %s' % (code, date))
if len(update_requests)>0:
update_result = daily.bulk_write(update_requests, ordered=False)
print('第%s年填充进度: %s/%s, 字段名: is_st,数据集:%s,插入:%4d条,更新:%4d条' %
(i+1, j+1, total, 'daily', update_result.upserted_count, update_result.modified_count), flush=True)
def fill_high_and_low_price_between(start, end):
codes = ts.get_stock_basics().index.tolist()
_df = pd.read_excel('data/stock_basic.xlsx', header=0, dtype={'code':str})
_df = _df.set_index('code')
st_codes = _df[_df['是否ST过'] == 1].index.tolist()
total = len(codes)
error_code = []
for i,code in enumerate(codes):
try:
timeToMarket = DB_CONN['basic'].find_one({'code':code},
projection={'code':True, 'timeToMarket':True, '_id':False})['timeToMarket']
except:
error_code.append(code)
continue
daily_cursor = DB_CONN['daily'].find(
{'code':code, 'date':{'$lte': end, '$gte': timeToMarket}, 'index':False},
projection={'code':True, 'date':True, 'pre_close':True, '_id':False})
update_requests = []
for j,daily in enumerate(daily_cursor):
date = daily['date']
try:
pre_close = daily['pre_close']
except:
if (j == 0) & (timeToMarket != date):
pass
elif timeToMarket == date:
issueprice = DB_CONN['basic'].find_one({'code':code},
projection={'issueprice':True, '_id':False})['issueprice']
high_limit = np.round(np.round(issueprice * 1.2, 2) * 1.2, 2)
low_limit = np.round(np.round(issueprice * 0.8, 2) * 0.8, 2)
update_requests.append(
UpdateOne({'code':code, 'date':date, 'index':False},
{'$set':{'high_limit':high_limit, 'low_limit':low_limit}},
upsert=True))
else:
print('code: %s, time: %s, ipo_date: %s, 请速查原因' % (code, date, timeToMarket))
error_code.append(code)
continue
st_flag = DB_CONN['daily'].find_one({'code':code, 'date':date, 'index':False})['is_st']
if st_flag:
high_limit = np.round(pre_close * 1.05, 2)
low_limit = np.round(pre_close * 0.95, 2)
else:
high_limit = np.round(pre_close * 1.1, 2)
low_limit = np.round(pre_close * 0.9, 2)
update_requests.append(
UpdateOne({'code':code, 'date':date, 'index':False},
{'$set':{'high_limit':high_limit, 'low_limit':low_limit}},
upsert=True))
if len(update_requests)>0:
update_result = DB_CONN['daily'].bulk_write(update_requests, ordered=False)
print('涨跌停计算, 进度: (%s/%s), code:%s, 数据集:%s, 插入:%4d条, 更新:%4d条' %
(i+1, total, code, 'daily', update_result.upserted_count, update_result.modified_count), flush=True)
if __name__ == '__main__':
daily_col = DB_CONN['daily']
if 'code_1_index_1' not in daily_col.index_information().keys():
daily_col.create_index(
[('code', ASCENDING), ('index', ASCENDING)]
)
start = '2015-01-01'
end = '2018-09-30'
tic = time.process_time()
fixing_is_st(start, end)
fill_high_and_low_price_between(start, end)
toc = time.process_time()
delta = toc - tic
print(delta) | true | true |
f71b9a749d420870b13e967659e88b311fd71f8e | 5,142 | py | Python | dsw_mailer/connection/smtp.py | ds-wizard/mailer | f919cf42a413a9fa530607358900255b55fc233a | [
"Apache-2.0"
] | null | null | null | dsw_mailer/connection/smtp.py | ds-wizard/mailer | f919cf42a413a9fa530607358900255b55fc233a | [
"Apache-2.0"
] | null | null | null | dsw_mailer/connection/smtp.py | ds-wizard/mailer | f919cf42a413a9fa530607358900255b55fc233a | [
"Apache-2.0"
] | null | null | null | import logging
import pathvalidate
import smtplib
import ssl
import tenacity
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from ..config import MailConfig
from ..context import Context
from ..model import MailMessage, MailAttachment
RETRY_SMTP_MULTIPLIER = 0.5
RETRY_SMTP_TRIES = 3
EMAIL_ENCODING = 'utf-8'
class SMTPSender:
def __init__(self, cfg: MailConfig):
self.cfg = cfg
@tenacity.retry(
reraise=True,
wait=tenacity.wait_exponential(multiplier=RETRY_SMTP_MULTIPLIER),
stop=tenacity.stop_after_attempt(RETRY_SMTP_TRIES),
before=tenacity.before_log(Context.logger, logging.DEBUG),
after=tenacity.after_log(Context.logger, logging.DEBUG),
)
def send(self, message: MailMessage):
self._send(message)
def _send(self, mail: MailMessage):
if self.cfg.is_ssl:
return self._send_smtp_ssl(mail=mail)
return self._send_smtp(mail=mail)
def _send_smtp_ssl(self, mail: MailMessage):
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
host=self.cfg.host,
port=self.cfg.port,
context=context,
timeout=self.cfg.timeout,
) as server:
if self.cfg.auth:
server.login(
user=self.cfg.login_user,
password=self.cfg.login_password,
)
return server.send_message(
msg=self._convert_email(mail),
from_addr=formataddr((mail.from_name, mail.from_mail)),
to_addrs=mail.recipients,
)
def _send_smtp(self, mail: MailMessage):
context = ssl.create_default_context()
with smtplib.SMTP(
host=self.cfg.host,
port=self.cfg.port,
timeout=self.cfg.timeout,
) as server:
if self.cfg.is_tls:
server.starttls(context=context)
if self.cfg.auth:
server.login(
user=self.cfg.login_user,
password=self.cfg.login_password,
)
return server.send_message(
msg=self._convert_email(mail),
from_addr=formataddr((mail.from_name, mail.from_mail)),
to_addrs=mail.recipients,
)
def _convert_inline_image(self, image: MailAttachment) -> MIMEBase:
mtype, msubtype = image.content_type.split('/', maxsplit=1)
part = MIMEBase(mtype, msubtype)
part.set_payload(image.data)
encoders.encode_base64(part)
filename = pathvalidate.sanitize_filename(image.name)
part.add_header('Content-ID', f'<{filename}>')
part.add_header('Content-Disposition', f'inline; filename={filename}')
return part
def _convert_html_part(self, mail: MailMessage) -> MIMEBase:
if mail.html_body is None:
raise RuntimeError('Requested HTML body but there is none')
txt_part = MIMEText(mail.html_body, 'html', EMAIL_ENCODING)
txt_part.set_charset(EMAIL_ENCODING)
if len(mail.html_images) > 0:
part = MIMEMultipart('related')
part.attach(txt_part)
for image in mail.html_images:
part.attach(self._convert_inline_image(image))
return part
return txt_part
def _convert_plain_part(self, mail: MailMessage) -> MIMEText:
if mail.plain_body is None:
raise RuntimeError('Requested plain body but there is none')
return MIMEText(mail.plain_body, 'plain', EMAIL_ENCODING)
def _convert_txt_parts(self, mail: MailMessage) -> MIMEBase:
if mail.plain_body is None:
return self._convert_html_part(mail)
if mail.html_body is None:
return self._convert_plain_part(mail)
part = MIMEMultipart('alternative')
part.set_charset(EMAIL_ENCODING)
part.attach(self._convert_plain_part(mail))
part.attach(self._convert_html_part(mail))
return part
def _convert_attachment(self, attachment: MailAttachment) -> MIMEBase:
mtype, msubtype = attachment.content_type.split('/', maxsplit=1)
part = MIMEBase(mtype, msubtype)
part.set_payload(attachment.data)
encoders.encode_base64(part)
filename = pathvalidate.sanitize_filename(attachment.name)
part.add_header('Content-Disposition', f'attachment; filename={filename}')
return part
def _convert_email(self, mail: MailMessage) -> MIMEBase:
msg = self._convert_txt_parts(mail)
if len(mail.attachments) > 0:
txt = msg
msg = MIMEMultipart('mixed')
msg.attach(txt)
for attachment in mail.attachments:
msg.attach(self._convert_attachment(attachment))
msg['From'] = formataddr((mail.from_name, mail.from_mail))
msg['To'] = ', '.join(mail.recipients)
msg['Subject'] = mail.subject
return msg
| 36.211268 | 82 | 0.632439 | import logging
import pathvalidate
import smtplib
import ssl
import tenacity
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from ..config import MailConfig
from ..context import Context
from ..model import MailMessage, MailAttachment
RETRY_SMTP_MULTIPLIER = 0.5
RETRY_SMTP_TRIES = 3
EMAIL_ENCODING = 'utf-8'
class SMTPSender:
def __init__(self, cfg: MailConfig):
self.cfg = cfg
@tenacity.retry(
reraise=True,
wait=tenacity.wait_exponential(multiplier=RETRY_SMTP_MULTIPLIER),
stop=tenacity.stop_after_attempt(RETRY_SMTP_TRIES),
before=tenacity.before_log(Context.logger, logging.DEBUG),
after=tenacity.after_log(Context.logger, logging.DEBUG),
)
def send(self, message: MailMessage):
self._send(message)
def _send(self, mail: MailMessage):
if self.cfg.is_ssl:
return self._send_smtp_ssl(mail=mail)
return self._send_smtp(mail=mail)
def _send_smtp_ssl(self, mail: MailMessage):
context = ssl.create_default_context()
with smtplib.SMTP_SSL(
host=self.cfg.host,
port=self.cfg.port,
context=context,
timeout=self.cfg.timeout,
) as server:
if self.cfg.auth:
server.login(
user=self.cfg.login_user,
password=self.cfg.login_password,
)
return server.send_message(
msg=self._convert_email(mail),
from_addr=formataddr((mail.from_name, mail.from_mail)),
to_addrs=mail.recipients,
)
def _send_smtp(self, mail: MailMessage):
context = ssl.create_default_context()
with smtplib.SMTP(
host=self.cfg.host,
port=self.cfg.port,
timeout=self.cfg.timeout,
) as server:
if self.cfg.is_tls:
server.starttls(context=context)
if self.cfg.auth:
server.login(
user=self.cfg.login_user,
password=self.cfg.login_password,
)
return server.send_message(
msg=self._convert_email(mail),
from_addr=formataddr((mail.from_name, mail.from_mail)),
to_addrs=mail.recipients,
)
def _convert_inline_image(self, image: MailAttachment) -> MIMEBase:
mtype, msubtype = image.content_type.split('/', maxsplit=1)
part = MIMEBase(mtype, msubtype)
part.set_payload(image.data)
encoders.encode_base64(part)
filename = pathvalidate.sanitize_filename(image.name)
part.add_header('Content-ID', f'<{filename}>')
part.add_header('Content-Disposition', f'inline; filename={filename}')
return part
def _convert_html_part(self, mail: MailMessage) -> MIMEBase:
if mail.html_body is None:
raise RuntimeError('Requested HTML body but there is none')
txt_part = MIMEText(mail.html_body, 'html', EMAIL_ENCODING)
txt_part.set_charset(EMAIL_ENCODING)
if len(mail.html_images) > 0:
part = MIMEMultipart('related')
part.attach(txt_part)
for image in mail.html_images:
part.attach(self._convert_inline_image(image))
return part
return txt_part
def _convert_plain_part(self, mail: MailMessage) -> MIMEText:
if mail.plain_body is None:
raise RuntimeError('Requested plain body but there is none')
return MIMEText(mail.plain_body, 'plain', EMAIL_ENCODING)
def _convert_txt_parts(self, mail: MailMessage) -> MIMEBase:
if mail.plain_body is None:
return self._convert_html_part(mail)
if mail.html_body is None:
return self._convert_plain_part(mail)
part = MIMEMultipart('alternative')
part.set_charset(EMAIL_ENCODING)
part.attach(self._convert_plain_part(mail))
part.attach(self._convert_html_part(mail))
return part
def _convert_attachment(self, attachment: MailAttachment) -> MIMEBase:
mtype, msubtype = attachment.content_type.split('/', maxsplit=1)
part = MIMEBase(mtype, msubtype)
part.set_payload(attachment.data)
encoders.encode_base64(part)
filename = pathvalidate.sanitize_filename(attachment.name)
part.add_header('Content-Disposition', f'attachment; filename={filename}')
return part
def _convert_email(self, mail: MailMessage) -> MIMEBase:
msg = self._convert_txt_parts(mail)
if len(mail.attachments) > 0:
txt = msg
msg = MIMEMultipart('mixed')
msg.attach(txt)
for attachment in mail.attachments:
msg.attach(self._convert_attachment(attachment))
msg['From'] = formataddr((mail.from_name, mail.from_mail))
msg['To'] = ', '.join(mail.recipients)
msg['Subject'] = mail.subject
return msg
| true | true |
f71b9ac9f4d7813d05814baf5ec329e7feb1f6b6 | 1,576 | py | Python | setup.py | JakubBlaha/python-jsonstore | 9f79f17e7947fe89aea1e67483d1f8d7313ea4ab | [
"MIT"
] | 2 | 2020-04-30T12:22:15.000Z | 2020-05-15T22:40:39.000Z | setup.py | JakubBlaha/python-jsonstore | 9f79f17e7947fe89aea1e67483d1f8d7313ea4ab | [
"MIT"
] | 6 | 2018-09-05T17:46:21.000Z | 2020-06-01T11:34:26.000Z | setup.py | JakubBlaha/python-jsonstore | 9f79f17e7947fe89aea1e67483d1f8d7313ea4ab | [
"MIT"
] | 5 | 2017-11-25T20:31:28.000Z | 2020-09-04T00:57:07.000Z | import codecs
from os import path
from textwrap import dedent
from setuptools import setup
here = path.abspath(path.dirname(__file__))
with codecs.open(path.join(here, "README.rst"), encoding='utf-8') as f:
long_description = f.read()
setup(
name='python-jsonstore',
use_scm_version=True,
description="",
long_description=long_description,
long_description_content_type='text/x-rst',
author="Oliver Bristow",
author_email='github+pypi@oliverbristow.co.uk',
license='MIT',
classifiers=dedent("""
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: Implementation :: PyPy
Topic :: Database
Topic :: Software Development
""").strip().split('\n'),
keywords='json key value store',
url='https://github.com/Code0x58/python-jsonstore/',
py_modules=dedent("""
jsonstore
""").strip().split('\n'),
setup_requires=["setuptools_scm", "wheel"],
)
| 33.531915 | 71 | 0.645939 | import codecs
from os import path
from textwrap import dedent
from setuptools import setup
here = path.abspath(path.dirname(__file__))
with codecs.open(path.join(here, "README.rst"), encoding='utf-8') as f:
long_description = f.read()
setup(
name='python-jsonstore',
use_scm_version=True,
description="",
long_description=long_description,
long_description_content_type='text/x-rst',
author="Oliver Bristow",
author_email='github+pypi@oliverbristow.co.uk',
license='MIT',
classifiers=dedent("""
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: Implementation :: PyPy
Topic :: Database
Topic :: Software Development
""").strip().split('\n'),
keywords='json key value store',
url='https://github.com/Code0x58/python-jsonstore/',
py_modules=dedent("""
jsonstore
""").strip().split('\n'),
setup_requires=["setuptools_scm", "wheel"],
)
| true | true |
f71b9b08d59205e762bc081291995a3dce88426a | 778 | py | Python | ws2122-lspm/Lib/site-packages/pm4py/objects/log/exporter/xes/util/__init__.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2022-01-19T04:02:46.000Z | 2022-01-19T04:02:46.000Z | ws2122-lspm/Lib/site-packages/pm4py/objects/log/exporter/xes/util/__init__.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2021-11-19T07:21:48.000Z | 2021-11-19T07:21:48.000Z | ws2122-lspm/Lib/site-packages/pm4py/objects/log/exporter/xes/util/__init__.py | Malekhy/ws2122-lspm | e4dc8b801d12f862b8ef536a0f125f346f085a00 | [
"MIT"
] | 1 | 2022-01-14T17:15:38.000Z | 2022-01-14T17:15:38.000Z | '''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PM4Py is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PM4Py. If not, see <https://www.gnu.org/licenses/>.
'''
from pm4py.objects.log.exporter.xes.util import compression
| 43.222222 | 76 | 0.737789 | from pm4py.objects.log.exporter.xes.util import compression
| true | true |
f71b9c6dbdb4556fd1c62de37e6dbb97379d445f | 4,113 | py | Python | homeassistant/components/sensor/rtorrent.py | XRyu/home-assistant | c9c707e368be159f0138a40d21fdea7a2a650ffe | [
"Apache-2.0"
] | 1 | 2019-07-24T09:26:57.000Z | 2019-07-24T09:26:57.000Z | homeassistant/components/sensor/rtorrent.py | XRyu/home-assistant | c9c707e368be159f0138a40d21fdea7a2a650ffe | [
"Apache-2.0"
] | 5 | 2021-02-08T20:32:11.000Z | 2022-01-13T01:19:23.000Z | homeassistant/components/sensor/rtorrent.py | XRyu/home-assistant | c9c707e368be159f0138a40d21fdea7a2a650ffe | [
"Apache-2.0"
] | null | null | null | """Support for monitoring the rtorrent BitTorrent client API."""
import logging
import xmlrpc.client
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_URL, CONF_NAME,
CONF_MONITORED_VARIABLES, STATE_IDLE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import PlatformNotReady
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPE_CURRENT_STATUS = 'current_status'
SENSOR_TYPE_DOWNLOAD_SPEED = 'download_speed'
SENSOR_TYPE_UPLOAD_SPEED = 'upload_speed'
DEFAULT_NAME = 'rtorrent'
SENSOR_TYPES = {
SENSOR_TYPE_CURRENT_STATUS: ['Status', None],
SENSOR_TYPE_DOWNLOAD_SPEED: ['Down Speed', 'kB/s'],
SENSOR_TYPE_UPLOAD_SPEED: ['Up Speed', 'kB/s'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_URL): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MONITORED_VARIABLES, default=[]): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the rtorrent sensors."""
url = config[CONF_URL]
name = config[CONF_NAME]
try:
rtorrent = xmlrpc.client.ServerProxy(url)
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent daemon failed")
raise PlatformNotReady
dev = []
for variable in config[CONF_MONITORED_VARIABLES]:
dev.append(RTorrentSensor(variable, rtorrent, name))
add_entities(dev)
def format_speed(speed):
"""Return a bytes/s measurement as a human readable string."""
kb_spd = float(speed) / 1024
return round(kb_spd, 2 if kb_spd < 0.1 else 1)
class RTorrentSensor(Entity):
"""Representation of an rtorrent sensor."""
def __init__(self, sensor_type, rtorrent_client, client_name):
"""Initialize the sensor."""
self._name = SENSOR_TYPES[sensor_type][0]
self.client = rtorrent_client
self.type = sensor_type
self.client_name = client_name
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.data = None
self._available = False
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self.client_name, self._name)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def available(self):
"""Return true if device is available."""
return self._available
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
"""Get the latest data from rtorrent and updates the state."""
multicall = xmlrpc.client.MultiCall(self.client)
multicall.throttle.global_up.rate()
multicall.throttle.global_down.rate()
try:
self.data = multicall()
self._available = True
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent lost")
self._available = False
return
upload = self.data[0]
download = self.data[1]
if self.type == SENSOR_TYPE_CURRENT_STATUS:
if self.data:
if upload > 0 and download > 0:
self._state = 'Up/Down'
elif upload > 0 and download == 0:
self._state = 'Seeding'
elif upload == 0 and download > 0:
self._state = 'Downloading'
else:
self._state = STATE_IDLE
else:
self._state = None
if self.data:
if self.type == SENSOR_TYPE_DOWNLOAD_SPEED:
self._state = format_speed(download)
elif self.type == SENSOR_TYPE_UPLOAD_SPEED:
self._state = format_speed(upload)
| 32.132813 | 70 | 0.650863 | import logging
import xmlrpc.client
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_URL, CONF_NAME,
CONF_MONITORED_VARIABLES, STATE_IDLE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import PlatformNotReady
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPE_CURRENT_STATUS = 'current_status'
SENSOR_TYPE_DOWNLOAD_SPEED = 'download_speed'
SENSOR_TYPE_UPLOAD_SPEED = 'upload_speed'
DEFAULT_NAME = 'rtorrent'
SENSOR_TYPES = {
SENSOR_TYPE_CURRENT_STATUS: ['Status', None],
SENSOR_TYPE_DOWNLOAD_SPEED: ['Down Speed', 'kB/s'],
SENSOR_TYPE_UPLOAD_SPEED: ['Up Speed', 'kB/s'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_URL): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MONITORED_VARIABLES, default=[]): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
url = config[CONF_URL]
name = config[CONF_NAME]
try:
rtorrent = xmlrpc.client.ServerProxy(url)
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent daemon failed")
raise PlatformNotReady
dev = []
for variable in config[CONF_MONITORED_VARIABLES]:
dev.append(RTorrentSensor(variable, rtorrent, name))
add_entities(dev)
def format_speed(speed):
kb_spd = float(speed) / 1024
return round(kb_spd, 2 if kb_spd < 0.1 else 1)
class RTorrentSensor(Entity):
def __init__(self, sensor_type, rtorrent_client, client_name):
self._name = SENSOR_TYPES[sensor_type][0]
self.client = rtorrent_client
self.type = sensor_type
self.client_name = client_name
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.data = None
self._available = False
@property
def name(self):
return '{} {}'.format(self.client_name, self._name)
@property
def state(self):
return self._state
@property
def available(self):
return self._available
@property
def unit_of_measurement(self):
return self._unit_of_measurement
def update(self):
multicall = xmlrpc.client.MultiCall(self.client)
multicall.throttle.global_up.rate()
multicall.throttle.global_down.rate()
try:
self.data = multicall()
self._available = True
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent lost")
self._available = False
return
upload = self.data[0]
download = self.data[1]
if self.type == SENSOR_TYPE_CURRENT_STATUS:
if self.data:
if upload > 0 and download > 0:
self._state = 'Up/Down'
elif upload > 0 and download == 0:
self._state = 'Seeding'
elif upload == 0 and download > 0:
self._state = 'Downloading'
else:
self._state = STATE_IDLE
else:
self._state = None
if self.data:
if self.type == SENSOR_TYPE_DOWNLOAD_SPEED:
self._state = format_speed(download)
elif self.type == SENSOR_TYPE_UPLOAD_SPEED:
self._state = format_speed(upload)
| true | true |
f71b9cde058636291fadd916f2bb3f983e61f130 | 3,694 | py | Python | BM/1.Pipelines_For_Running_Tools/1.B.pipe_M2S2MH/python.MH_conc.py | hiyoothere/Benchmarking-mosaic-variant-detection | a627602276273c10bbdcf2b9cf30a634765e40f8 | [
"CECILL-B"
] | 2 | 2021-11-24T04:38:34.000Z | 2022-01-21T08:38:24.000Z | BM/1.Pipelines_For_Running_Tools/1.B.pipe_M2S2MH/python.MH_conc.py | hiyoothere/Benchmarking-mosaic-variant-detection | a627602276273c10bbdcf2b9cf30a634765e40f8 | [
"CECILL-B"
] | null | null | null | BM/1.Pipelines_For_Running_Tools/1.B.pipe_M2S2MH/python.MH_conc.py | hiyoothere/Benchmarking-mosaic-variant-detection | a627602276273c10bbdcf2b9cf30a634765e40f8 | [
"CECILL-B"
] | null | null | null | import glob
import sys
##### creatin dict that will have all control positions
def con_pos(con_MH):
con_dict = {}
f = open(con_MH, 'r')
for line in f:
s = line.split()
chr = s[0]
pos = s[1]
ref = int(s[7]) #ref depth
alt = int(s[9]) #alt depth
vaf = float(alt)/(ref+alt)
alt_type = s[8] #alt base
if chr in con_dict:
if pos in con_dict[chr]:
print "ERROR: %s : %s"%(chr, pos)
else:
con_dict[chr][pos] = [[vaf, "NA"], alt_type] ## VAF of con FIRST in list of vaf in position
else:
con_dict[chr] = {pos : [[vaf, "NA"], alt_type]}
f.close()
return con_dict
def combine(con_dict, cas_MH):
cas = open(cas_MH, 'r')
for line in cas:
s = line.split()
chr = s[0]
pos = s[1]
ref = int(s[7]) #ref depth
alt = int(s[9]) #alt depth
vaf = float(alt)/(ref+alt)
alt_type = s[8] #alt base
if chr in con_dict:
if pos in con_dict[chr]:
con_dict[chr][pos][0][1] = vaf
else:
con_dict[chr][pos] = [["NA", vaf], alt_type] ## VAF of cas SECOND in list of vaf in position
else:
con_dict[chr] = {pos : [["NA", vaf], alt_type] }
cas.close()
return con_dict
def rem_het(total_dict):
for chr in total_dict:
for pos in total_dict[chr]:
ls = total_dict[chr][pos][0]
if 'NA' in ls:
continue
else:
if (ls[0] >= 0.30) & (ls[1] >= 0.30): ### remove positions with af 30+ in both tissues
total_dict[chr][pos][0] = ["NA"] ## VAF [con, cas] will be listed as ['NA']
return total_dict
def write_final(passed_dict, con_out, cas_out, sha_out):
#### DISORDERED
for chr in passed_dict:
for pos in passed_dict[chr]:
line = [chr, pos, passed_dict[chr][pos][1]]
ls = passed_dict[chr][pos][0] ### VAF of cas, con or 'NA'
if "NA" in ls:
if len(ls) == 1: #when 'NA'
continue
elif ls[0] == "NA": #when only case
line.append(str(ls[1]))
cas_out.write('\t'.join(line) + '\n')
else: #when only control
line.append(str(ls[0]))
con_out.write('\t'.join(line) + '\n')
else: #shared
con_vaf = passed_dict[chr][pos][0][0] ### add con VAF for future analysis
line = '\t'.join([chr, pos, passed_dict[chr][pos][1], str(con_vaf)]) + '\n'
sha_out.write(line)
def main(ID_con, ID_cas, con_MH, cas_MH, OutPath):
con_dict = con_pos(con_MH) # control positions
total_dict = combine(con_dict, cas_MH) # conc positions of ctrl and case
passed_dict = rem_het(total_dict) # remove any positions with 0.30+ VAF for both ctrl and case
### writing files
###### ctrl specific
###### case specific
###### shared (with 30% af filter)
con_file = OutPath + "/" + '_'.join([ID_cas, ID_con, ID_con]) + ".txt"
cas_file = OutPath + "/" + '_'.join([ID_cas, ID_con, ID_cas]) + ".txt"
sha_file = OutPath + "/" + '_'.join([ID_cas, ID_con]) + ".sha.txt"
con_out = open(con_file, 'w')
cas_out = open(cas_file, 'w')
sha_out = open(sha_file, 'w')
write_final(passed_dict, con_out, cas_out, sha_out)
con_out.close()
cas_out.close()
sha_out.close()
##### EXECUTION ######
MHpath = sys.argv[1]
ID_con = sys.argv[2]
ID_cas = sys.argv[3]
OutPath = sys.argv[4]
DP = sys.argv[5]
if "ND" in DP:
con_MH = MHpath + "/ND-" + ID_con + "/final.passed.tsv"
cas_MH = MHpath + "/ND-" + ID_cas + "/final.passed.tsv"
else:
con_MH = MHpath + "/" + ID_con.replace('.', '-') + "/final.passed.tsv"
cas_MH = MHpath + "/" + ID_cas.replace('.', '-') + "/final.passed.tsv"
main(ID_con, ID_cas, con_MH, cas_MH, OutPath)
| 30.278689 | 96 | 0.566594 | import glob
import sys
if chr in con_dict:
if pos in con_dict[chr]:
print "ERROR: %s : %s"%(chr, pos)
else:
con_dict[chr][pos] = [[vaf, "NA"], alt_type] "], alt_type]}
f.close()
return con_dict
def combine(con_dict, cas_MH):
cas = open(cas_MH, 'r')
for line in cas:
s = line.split()
chr = s[0]
pos = s[1]
ref = int(s[7])
alt = int(s[9])
vaf = float(alt)/(ref+alt)
alt_type = s[8]
if chr in con_dict:
if pos in con_dict[chr]:
con_dict[chr][pos][0][1] = vaf
else:
con_dict[chr][pos] = [["NA", vaf], alt_type] ], alt_type] }
cas.close()
return con_dict
def rem_het(total_dict):
for chr in total_dict:
for pos in total_dict[chr]:
ls = total_dict[chr][pos][0]
if 'NA' in ls:
continue
else:
if (ls[0] >= 0.30) & (ls[1] >= 0.30): passed_dict[chr]:
line = [chr, pos, passed_dict[chr][pos][1]]
ls = passed_dict[chr][pos][0] ls) == 1:
continue
elif ls[0] == "NA":
line.append(str(ls[1]))
cas_out.write('\t'.join(line) + '\n')
else:
line.append(str(ls[0]))
con_out.write('\t'.join(line) + '\n')
else:
con_vaf = passed_dict[chr][pos][0][0] vaf)]) + '\n'
sha_out.write(line)
def main(ID_con, ID_cas, con_MH, cas_MH, OutPath):
con_dict = con_pos(con_MH)
total_dict = combine(con_dict, cas_MH)
passed_dict = rem_het(total_dict)
out, sha_out)
con_out.close()
cas_out.close()
sha_out.close()
v[5]
if "ND" in DP:
con_MH = MHpath + "/ND-" + ID_con + "/final.passed.tsv"
cas_MH = MHpath + "/ND-" + ID_cas + "/final.passed.tsv"
else:
con_MH = MHpath + "/" + ID_con.replace('.', '-') + "/final.passed.tsv"
cas_MH = MHpath + "/" + ID_cas.replace('.', '-') + "/final.passed.tsv"
main(ID_con, ID_cas, con_MH, cas_MH, OutPath)
| false | true |
f71b9da7eaef7e2b15246349f4b4f1045f95882f | 799 | py | Python | backend/scrape_amazon/update_product_db_amazon.py | jayleenli/the-legend-of-compurator | 7fc747ebf6b011acec8733a394861f7fed368d73 | [
"MIT"
] | null | null | null | backend/scrape_amazon/update_product_db_amazon.py | jayleenli/the-legend-of-compurator | 7fc747ebf6b011acec8733a394861f7fed368d73 | [
"MIT"
] | null | null | null | backend/scrape_amazon/update_product_db_amazon.py | jayleenli/the-legend-of-compurator | 7fc747ebf6b011acec8733a394861f7fed368d73 | [
"MIT"
] | null | null | null | from .scrape_objects_MVP import get_attributes, get_id
from pymongo import MongoClient
import os
DB_URL = os.environ['DB_URL']
CLIENT = MongoClient(DB_URL)
DB = CLIENT.compurator
PRODUCTS_COLLECTION = DB["products"]
def check_product_exists(url):
'''
:param url: url of amazon product
:return: false if product does not exist in products_collection, p_id if it does exist
'''
p_id = get_id(url)
if PRODUCTS_COLLECTION.count({'p_id': p_id}) > 0:
return p_id
return False
def add_product_amazon(url):
'''
:param PRODUCTS_COLLECTION, url:
:return prod_document: amazon id containing attributes of product on amazon
'''
prod_document = get_attributes(url)
PRODUCTS_COLLECTION.insert_one(prod_document)
return prod_document['p_id']
| 24.212121 | 90 | 0.720901 | from .scrape_objects_MVP import get_attributes, get_id
from pymongo import MongoClient
import os
DB_URL = os.environ['DB_URL']
CLIENT = MongoClient(DB_URL)
DB = CLIENT.compurator
PRODUCTS_COLLECTION = DB["products"]
def check_product_exists(url):
p_id = get_id(url)
if PRODUCTS_COLLECTION.count({'p_id': p_id}) > 0:
return p_id
return False
def add_product_amazon(url):
prod_document = get_attributes(url)
PRODUCTS_COLLECTION.insert_one(prod_document)
return prod_document['p_id']
| true | true |
f71b9e37908dd5da30752301903bfc85504aa496 | 728 | py | Python | Examples/AcceptAllRevisions.py | aspose-words-cloud/aspose-words-cloud-python | 65c7b55fa4aac69b60d41e7f54aed231df285479 | [
"MIT"
] | 14 | 2018-07-15T17:01:52.000Z | 2018-11-29T06:15:33.000Z | Examples/AcceptAllRevisions.py | aspose-words-cloud/aspose-words-cloud-python | 65c7b55fa4aac69b60d41e7f54aed231df285479 | [
"MIT"
] | 1 | 2018-09-28T12:59:34.000Z | 2019-10-08T08:42:59.000Z | Examples/AcceptAllRevisions.py | aspose-words-cloud/aspose-words-cloud-python | 65c7b55fa4aac69b60d41e7f54aed231df285479 | [
"MIT"
] | 2 | 2020-12-21T07:59:17.000Z | 2022-02-16T21:41:25.000Z | import os
import asposewordscloud
import asposewordscloud.models.requests
from asposewordscloud.rest import ApiException
from shutil import copyfile
words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################')
file_name = 'test_doc.docx'
# Upload original document to cloud storage.
my_var1 = open(file_name, 'rb')
my_var2 = file_name
upload_file_request = asposewordscloud.models.requests.UploadFileRequest(file_content=my_var1, path=my_var2)
words_api.upload_file(upload_file_request)
# Calls AcceptAllRevisions method for document in cloud.
my_var3 = file_name
request = asposewordscloud.models.requests.AcceptAllRevisionsRequest(name=my_var3)
words_api.accept_all_revisions(request) | 38.315789 | 108 | 0.787088 | import os
import asposewordscloud
import asposewordscloud.models.requests
from asposewordscloud.rest import ApiException
from shutil import copyfile
words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################')
file_name = 'test_doc.docx'
my_var1 = open(file_name, 'rb')
my_var2 = file_name
upload_file_request = asposewordscloud.models.requests.UploadFileRequest(file_content=my_var1, path=my_var2)
words_api.upload_file(upload_file_request)
my_var3 = file_name
request = asposewordscloud.models.requests.AcceptAllRevisionsRequest(name=my_var3)
words_api.accept_all_revisions(request) | true | true |
f71b9fe025bede004ce7e9ec58b828318f04188f | 15,536 | py | Python | src/api/block.py | BluCodeGH/Amulet-Map-Editor | 7d1d2243fc29095b3cffe8aa4979235444ba6738 | [
"MIT"
] | 1 | 2020-08-26T22:42:16.000Z | 2020-08-26T22:42:16.000Z | src/api/block.py | BluCodeGH/Amulet-Map-Editor | 7d1d2243fc29095b3cffe8aa4979235444ba6738 | [
"MIT"
] | null | null | null | src/api/block.py | BluCodeGH/Amulet-Map-Editor | 7d1d2243fc29095b3cffe8aa4979235444ba6738 | [
"MIT"
] | null | null | null | from __future__ import annotations
import copy
from sys import getsizeof
import re
from typing import Dict, Iterable, List, Tuple, Union, overload
from api.errors import InvalidBlockException
from utils import Int
class Block:
"""
Class to handle data about various blockstates and allow for extra blocks to be created and interacted with.
.. important::
Creating version specific block objects via the `Block()` constructor instead of using
:meth:`api.world.World.get_block_instance` is supported but not encouraged. To avoid possible caveats of doing this,
make sure to either only instantiate blocks with Amulet blockstate data or use
:meth:`api.world.World.get_block_instance` instead
Here's a few examples on how create a Block object with extra blocks:
Creating a new Block object with the base of ``stone`` and has an extra block of ``water[level=1]``:
>>> stone = Block(blockstate="minecraft:stone")
>>> water_level_1 = Block(blockstate="minecraft:water[level=1]")
>>> stone_with_extra_block = stone + water_level_1
>>> repr(stone_with_extra_block)
'Block(minecraft:stone, minecraft:water[level=1])'
Creating a new Block object using the namespace and base_name:
>>> granite = Block(namespace="minecraft", base_name="granite")
Creating a new Block object with another layer of extra blocks:
>>> stone_water_granite = stone_with_extra_block + granite # Doesn't modify any of the other objects
>>> repr(stone_water_granite)
'Block(minecraft:stone, minecraft:water[level=1], minecraft:granite)'
Creating a new Block object by removing an extra block from all layers:
*Note: This removes all instances of the Block object from extra blocks*
>>> stone_granite = stone_water_granite - water_level_1 # Doesn't modify any of the other objects either
>>> repr(stone_granite)
'Block(minecraft:stone, minecraft:granite)'
Creating a new Block object by removing a specific layer:
>>> oak_log_axis_x = Block(blockstate="minecraft:oak_log[axis=x]")
>>> stone_water_granite_water_oak_log = stone_water_granite + water_level_1 + oak_log_axis_x
>>> repr(stone_water_granite_water_oak_log)
'Block(minecraft:stone, minecraft:water[level=1], minecraft:granite, minecraft:water[level=1], minecraft:oak_log[axis=x])'
>>> stone_granite_water_oak_log = stone_water_granite_water_oak_log.remove_layer(0)
>>> repr(stone_granite_water_oak_log)
'Block(minecraft:stone, minecraft:granite, minecraft:water[level=1], minecraft:oak_log[axis=x])'
"""
__slots__ = (
"_namespace",
"_base_name",
"_properties",
"_extra_blocks",
"_blockstate",
) # Reduces memory footprint
blockstate_regex = re.compile(
r"(?:(?P<namespace>[a-z0-9_.-]+):)?(?P<base_name>[a-z0-9/._-]+)(?:\[(?P<property_name>[a-z0-9_]+)=(?P<property_value>[a-z0-9_]+)(?P<properties>.*)\])?"
)
parameters_regex = re.compile(r"(?:,(?P<name>[a-z0-9_]+)=(?P<value>[a-z0-9_]+))")
def __init__(
self,
blockstate: str = None,
namespace: str = None,
base_name: str = None,
properties: Dict[str, Union[str, bool, int]] = None,
extra_blocks: Union[Block, Iterable[Block]] = None,
):
self._blockstate = blockstate
self._namespace = namespace
self._base_name = base_name
if namespace is not None and base_name is not None and properties is None:
properties = {}
self._properties = properties
self._extra_blocks = ()
if extra_blocks:
if isinstance(extra_blocks, Block):
extra_blocks = [extra_blocks]
self._extra_blocks = tuple(extra_blocks)
if blockstate:
self._gen_blockstate()
@property
def namespace(self) -> str:
"""
The namespace of the blockstate represented by the Block object (IE: `minecraft`)
:return: The namespace of the blockstate
"""
if self._namespace is None:
self._parse_blockstate_string()
return self._namespace
@property
def base_name(self) -> str:
"""
The base name of the blockstate represented by the Block object (IE: `stone`, `dirt`)
:return: The base name of the blockstate
"""
if self._base_name is None:
self._parse_blockstate_string()
return self._base_name
@property
def properties(self) -> Dict[str, Union[str, bool, int]]:
"""
The mapping of properties of the blockstate represented by the Block object (IE: `{"level": "1"}`)
:return: A dictionary of the properties of the blockstate
"""
if self._properties is None:
self._parse_blockstate_string()
return copy.deepcopy(self._properties)
@property
def blockstate(self) -> str:
"""
The full blockstate string of the blockstate represented by the Block object (IE: `minecraft:stone`, `minecraft:oak_log[axis=x]`)
:return: The blockstate string
"""
if self._blockstate is None:
self._gen_blockstate()
return self._blockstate
@property
def extra_blocks(self) -> Union[Tuple, Tuple[Block]]:
"""
Returns a tuple of the extra blocks contained in the Block instance
:return: A tuple of Block objects
"""
return self._extra_blocks
def _gen_blockstate(self):
self._blockstate = f"{self.namespace}:{self.base_name}"
if self.properties:
props = [f"{key}={value}" for key, value in sorted(self.properties.items())]
self._blockstate = f"{self._blockstate}[{','.join(props)}]"
@staticmethod
def parse_blockstate_string(blockstate: str) -> Tuple[str, str, Dict[str, str]]:
match = Block.blockstate_regex.match(blockstate)
namespace = match.group("namespace") or "minecraft"
base_name = match.group("base_name")
if match.group("property_name") is not None:
properties = {match.group("property_name"): match.group("property_value")}
else:
properties = {}
properties_string = match.group("properties")
if properties_string is not None:
properties_match = Block.parameters_regex.finditer(properties_string)
for match in properties_match:
properties[match.group("name")] = match.group("value")
return namespace, base_name, {k: v for k, v in sorted(properties.items())}
def _parse_blockstate_string(self):
self._namespace, self._base_name, self._properties = self.parse_blockstate_string(
self._blockstate
)
def __str__(self) -> str:
"""
:return: The base blockstate string of the Block object
"""
return self.blockstate
def __repr__(self) -> str:
"""
:return: The base blockstate string of the Block object along with the blockstate strings of included extra blocks
"""
return f"Block({', '.join([str(b) for b in (self, *self.extra_blocks)])})"
def __len__(self):
return len(self._extra_blocks) + 1
def _compare_extra_blocks(self, other: Block) -> bool:
if len(self.extra_blocks) != len(other.extra_blocks):
return False
if len(self.extra_blocks) == 0:
return True
for our_extra_block, their_extra_block in zip(
self.extra_blocks, other.extra_blocks
):
if our_extra_block != their_extra_block:
return False
return True
def __eq__(self, other: Block) -> bool:
"""
Checks the equality of this Block object to another Block object
:param other: The Block object to check against
:return: True if the Blocks objects are equal, False otherwise
"""
if self.__class__ != other.__class__:
return False
return self.blockstate == other.blockstate and self._compare_extra_blocks(other)
def __hash__(self) -> int:
"""
Hashes the Block object
:return: A hash of the Block object
"""
current_hash = hash(self.blockstate)
if self.extra_blocks:
current_hash = current_hash + hash(self.extra_blocks)
return current_hash
def __add__(self, other: Block) -> Block:
"""
Allows for other Block objects to be added to this Block object's ``extra_blocks``
:param other: The Block object to add to the end of this Block object's `extra_blocks`
:return: A new Block object with the same data but with an additional Block at the end of ``extra_blocks``
"""
if not isinstance(other, Block):
return NotImplemented
if (
len(other.extra_blocks) == 0
): # Reduces the amount of extra objects/references created
other_cpy = other
else:
other_cpy = Block(
namespace=other.namespace,
base_name=other.base_name,
properties=other.properties,
)
other_extras = []
for eb in other.extra_blocks:
if (
len(eb.extra_blocks) == 0
): # Reduces the amount of extra objects/references created
other_extras.append(eb)
else:
other_extras.append(
Block(
namespace=eb.namespace,
base_name=eb.base_name,
properties=eb.properties,
)
)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=[*self.extra_blocks, other_cpy, *other_extras],
)
def __sub__(self, other: Block) -> Block:
"""
Allows for other Block objects to be subtracted from this Block object's ``extra_blocks``
:param other: The Block object to subtract from this Block objects' ``extra_blocks``
:return: A new Block object without any instances of the subtracted block in ``extra_blocks``
"""
if not isinstance(other, Block):
return NotImplemented
if (
len(other.extra_blocks) == 0
): # Reduces the amount of extra objects/references created
other_cpy = other
else:
other_cpy = Block(
namespace=other.namespace,
base_name=other.base_name,
properties=other.properties,
)
other_extras = []
for eb in other.extra_blocks:
if len(eb.extra_blocks) == 0:
other_extras.append(eb)
else:
other_extras.append(
Block(
namespace=eb.namespace,
base_name=eb.base_name,
properties=eb.properties,
)
)
# Sets are unordered, so a regular set subtraction doesn't always return the order we want (it sometimes will!)
# So we loop through all of our extra blocks and only append those to the new_extras list if they aren't in
# extra_blocks_to_remove
new_extras = []
extra_blocks_to_remove = (other_cpy, *other_extras)
for eb in self.extra_blocks:
if eb not in extra_blocks_to_remove:
new_extras.append(eb)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=new_extras,
)
def remove_layer(self, layer: int) -> Block:
"""
Removes the Block object from the specified layer and returns the resulting new Block object
:param layer: The layer of extra block to remove
:return: A new instance of Block with the same data but with the extra block at specified layer removed
:raises `InvalidBlockException`: Raised when you remove the base block from a Block with no other extra blocks
"""
if (
layer == 0
and len(self.extra_blocks) > 0
and layer <= len(self.extra_blocks)
):
new_base = self._extra_blocks[0]
return Block(
namespace=new_base.namespace,
base_name=new_base.base_name,
properties=new_base.properties,
extra_blocks=[*self._extra_blocks[1:]],
)
elif layer > len(self.extra_blocks):
raise InvalidBlockException("You cannot remove a non-existant layer")
elif layer == 0:
raise InvalidBlockException(
"Removing the base block with no extra blocks is not supported"
)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=[*self.extra_blocks[: layer - 1], *self.extra_blocks[layer:]],
)
def __sizeof__(self):
size = (
getsizeof(self.namespace)
+ getsizeof(self.base_name)
+ getsizeof(self.properties)
+ getsizeof(self.blockstate)
)
for eb in self.extra_blocks:
size += getsizeof(eb)
return size
class BlockManager:
"""
Class to handle the mappings between Block objects and their index-based internal IDs
"""
def __init__(self):
"""
Creates a new BlockManager object
"""
self._index_to_block: List[Block] = []
self._block_to_index_map: Dict[Block, int] = {}
def __len__(self):
return len(self._index_to_block)
def __contains__(self, item: Block) -> bool:
return item in self._block_to_index_map
@overload
def __getitem__(self, item: Block) -> int:
...
@overload
def __getitem__(self, item: Int) -> Block:
...
def __getitem__(self, item):
"""
If a Block object is passed to this function, it'll return the internal ID/index of the
blockstate. If an int is given, this method will return the Block object at that specified index.
:param item: The Block object or int to get the mapping data of
:return: An int if a Block object was supplied, a Block object if an int was supplied
"""
try:
if isinstance(item, Block):
return self._block_to_index_map[item]
return self._index_to_block[item]
except (KeyError, IndexError):
raise KeyError(
f"There is no {item} in the BlockManager. "
f"You might want to use the `add_block` function for your blocks before accessing them."
)
def get_add_block(self, block: Block) -> int:
"""
Adds a Block object to the internal Block object/ID mappings. If the Block already exists in the mappings,
then the existing ID is returned
:param block: The Block to add to the manager
:return: The internal ID of the Block
"""
if block in self._block_to_index_map:
return self._block_to_index_map[block]
self._block_to_index_map[block] = i = len(self._block_to_index_map)
self._index_to_block.append(block)
return i
| 35.149321 | 159 | 0.613092 | from __future__ import annotations
import copy
from sys import getsizeof
import re
from typing import Dict, Iterable, List, Tuple, Union, overload
from api.errors import InvalidBlockException
from utils import Int
class Block:
__slots__ = (
"_namespace",
"_base_name",
"_properties",
"_extra_blocks",
"_blockstate",
)
blockstate_regex = re.compile(
r"(?:(?P<namespace>[a-z0-9_.-]+):)?(?P<base_name>[a-z0-9/._-]+)(?:\[(?P<property_name>[a-z0-9_]+)=(?P<property_value>[a-z0-9_]+)(?P<properties>.*)\])?"
)
parameters_regex = re.compile(r"(?:,(?P<name>[a-z0-9_]+)=(?P<value>[a-z0-9_]+))")
def __init__(
self,
blockstate: str = None,
namespace: str = None,
base_name: str = None,
properties: Dict[str, Union[str, bool, int]] = None,
extra_blocks: Union[Block, Iterable[Block]] = None,
):
self._blockstate = blockstate
self._namespace = namespace
self._base_name = base_name
if namespace is not None and base_name is not None and properties is None:
properties = {}
self._properties = properties
self._extra_blocks = ()
if extra_blocks:
if isinstance(extra_blocks, Block):
extra_blocks = [extra_blocks]
self._extra_blocks = tuple(extra_blocks)
if blockstate:
self._gen_blockstate()
@property
def namespace(self) -> str:
if self._namespace is None:
self._parse_blockstate_string()
return self._namespace
@property
def base_name(self) -> str:
if self._base_name is None:
self._parse_blockstate_string()
return self._base_name
@property
def properties(self) -> Dict[str, Union[str, bool, int]]:
if self._properties is None:
self._parse_blockstate_string()
return copy.deepcopy(self._properties)
@property
def blockstate(self) -> str:
if self._blockstate is None:
self._gen_blockstate()
return self._blockstate
@property
def extra_blocks(self) -> Union[Tuple, Tuple[Block]]:
return self._extra_blocks
def _gen_blockstate(self):
self._blockstate = f"{self.namespace}:{self.base_name}"
if self.properties:
props = [f"{key}={value}" for key, value in sorted(self.properties.items())]
self._blockstate = f"{self._blockstate}[{','.join(props)}]"
@staticmethod
def parse_blockstate_string(blockstate: str) -> Tuple[str, str, Dict[str, str]]:
match = Block.blockstate_regex.match(blockstate)
namespace = match.group("namespace") or "minecraft"
base_name = match.group("base_name")
if match.group("property_name") is not None:
properties = {match.group("property_name"): match.group("property_value")}
else:
properties = {}
properties_string = match.group("properties")
if properties_string is not None:
properties_match = Block.parameters_regex.finditer(properties_string)
for match in properties_match:
properties[match.group("name")] = match.group("value")
return namespace, base_name, {k: v for k, v in sorted(properties.items())}
def _parse_blockstate_string(self):
self._namespace, self._base_name, self._properties = self.parse_blockstate_string(
self._blockstate
)
def __str__(self) -> str:
return self.blockstate
def __repr__(self) -> str:
return f"Block({', '.join([str(b) for b in (self, *self.extra_blocks)])})"
def __len__(self):
return len(self._extra_blocks) + 1
def _compare_extra_blocks(self, other: Block) -> bool:
if len(self.extra_blocks) != len(other.extra_blocks):
return False
if len(self.extra_blocks) == 0:
return True
for our_extra_block, their_extra_block in zip(
self.extra_blocks, other.extra_blocks
):
if our_extra_block != their_extra_block:
return False
return True
def __eq__(self, other: Block) -> bool:
if self.__class__ != other.__class__:
return False
return self.blockstate == other.blockstate and self._compare_extra_blocks(other)
def __hash__(self) -> int:
current_hash = hash(self.blockstate)
if self.extra_blocks:
current_hash = current_hash + hash(self.extra_blocks)
return current_hash
def __add__(self, other: Block) -> Block:
if not isinstance(other, Block):
return NotImplemented
if (
len(other.extra_blocks) == 0
):
other_cpy = other
else:
other_cpy = Block(
namespace=other.namespace,
base_name=other.base_name,
properties=other.properties,
)
other_extras = []
for eb in other.extra_blocks:
if (
len(eb.extra_blocks) == 0
):
other_extras.append(eb)
else:
other_extras.append(
Block(
namespace=eb.namespace,
base_name=eb.base_name,
properties=eb.properties,
)
)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=[*self.extra_blocks, other_cpy, *other_extras],
)
def __sub__(self, other: Block) -> Block:
if not isinstance(other, Block):
return NotImplemented
if (
len(other.extra_blocks) == 0
):
other_cpy = other
else:
other_cpy = Block(
namespace=other.namespace,
base_name=other.base_name,
properties=other.properties,
)
other_extras = []
for eb in other.extra_blocks:
if len(eb.extra_blocks) == 0:
other_extras.append(eb)
else:
other_extras.append(
Block(
namespace=eb.namespace,
base_name=eb.base_name,
properties=eb.properties,
)
)
# So we loop through all of our extra blocks and only append those to the new_extras list if they aren't in
new_extras = []
extra_blocks_to_remove = (other_cpy, *other_extras)
for eb in self.extra_blocks:
if eb not in extra_blocks_to_remove:
new_extras.append(eb)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=new_extras,
)
def remove_layer(self, layer: int) -> Block:
if (
layer == 0
and len(self.extra_blocks) > 0
and layer <= len(self.extra_blocks)
):
new_base = self._extra_blocks[0]
return Block(
namespace=new_base.namespace,
base_name=new_base.base_name,
properties=new_base.properties,
extra_blocks=[*self._extra_blocks[1:]],
)
elif layer > len(self.extra_blocks):
raise InvalidBlockException("You cannot remove a non-existant layer")
elif layer == 0:
raise InvalidBlockException(
"Removing the base block with no extra blocks is not supported"
)
return Block(
namespace=self.namespace,
base_name=self.base_name,
properties=self.properties,
extra_blocks=[*self.extra_blocks[: layer - 1], *self.extra_blocks[layer:]],
)
def __sizeof__(self):
size = (
getsizeof(self.namespace)
+ getsizeof(self.base_name)
+ getsizeof(self.properties)
+ getsizeof(self.blockstate)
)
for eb in self.extra_blocks:
size += getsizeof(eb)
return size
class BlockManager:
def __init__(self):
self._index_to_block: List[Block] = []
self._block_to_index_map: Dict[Block, int] = {}
def __len__(self):
return len(self._index_to_block)
def __contains__(self, item: Block) -> bool:
return item in self._block_to_index_map
@overload
def __getitem__(self, item: Block) -> int:
...
@overload
def __getitem__(self, item: Int) -> Block:
...
def __getitem__(self, item):
try:
if isinstance(item, Block):
return self._block_to_index_map[item]
return self._index_to_block[item]
except (KeyError, IndexError):
raise KeyError(
f"There is no {item} in the BlockManager. "
f"You might want to use the `add_block` function for your blocks before accessing them."
)
def get_add_block(self, block: Block) -> int:
if block in self._block_to_index_map:
return self._block_to_index_map[block]
self._block_to_index_map[block] = i = len(self._block_to_index_map)
self._index_to_block.append(block)
return i
| true | true |
f71ba01410b6baed59ee6dcd47fff57fa191f5b4 | 22,545 | py | Python | tests/test_setup.py | PiotrMachowski/core | b9d7d0cae2ccd2d88e90e49cc09e154a27ed809b | [
"Apache-2.0"
] | 3 | 2020-11-27T06:26:27.000Z | 2020-12-09T14:55:16.000Z | tests/test_setup.py | PiotrMachowski/core | b9d7d0cae2ccd2d88e90e49cc09e154a27ed809b | [
"Apache-2.0"
] | 18 | 2021-11-24T06:26:13.000Z | 2022-03-31T06:25:15.000Z | tests/test_setup.py | PiotrMachowski/core | b9d7d0cae2ccd2d88e90e49cc09e154a27ed809b | [
"Apache-2.0"
] | 3 | 2021-11-14T13:29:33.000Z | 2021-12-27T17:05:22.000Z | """Test component/platform setup."""
# pylint: disable=protected-access
import asyncio
import datetime
import threading
from unittest.mock import AsyncMock, Mock, patch
import pytest
import voluptuous as vol
from homeassistant import config_entries, setup
from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START
from homeassistant.core import callback
from homeassistant.helpers import discovery
from homeassistant.helpers.config_validation import (
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
assert_setup_component,
mock_entity_platform,
mock_integration,
)
@pytest.fixture
def mock_handlers():
"""Mock config flows."""
class MockFlowHandler(config_entries.ConfigFlow):
"""Define a mock flow handler."""
VERSION = 1
with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}):
yield
async def test_validate_component_config(hass):
"""Test validating component configuration."""
config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True)
mock_integration(hass, MockModule("comp_conf", config_schema=config_schema))
with assert_setup_component(0):
assert not await setup.async_setup_component(hass, "comp_conf", {})
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": None}
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": {}}
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass,
"comp_conf",
{"comp_conf": {"hello": "world", "invalid": "extra"}},
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": {"hello": "world"}}
)
async def test_validate_platform_config(hass, caplog):
"""Test validating platform configuration."""
platform_schema = PLATFORM_SCHEMA.extend({"hello": str})
platform_schema_base = PLATFORM_SCHEMA_BASE.extend({})
mock_integration(
hass,
MockModule("platform_conf", platform_schema_base=platform_schema_base),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform(platform_schema=platform_schema),
)
with assert_setup_component(0):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": {"platform": "not_existing", "hello": "world"}},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": {"platform": "whatever", "hello": "world"}},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": [{"platform": "whatever", "hello": "world"}]},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
# Any falsey platform config will be ignored (None, {}, etc)
with assert_setup_component(0) as config:
assert await setup.async_setup_component(
hass, "platform_conf", {"platform_conf": None}
)
assert "platform_conf" in hass.config.components
assert not config["platform_conf"] # empty
assert await setup.async_setup_component(
hass, "platform_conf", {"platform_conf": {}}
)
assert "platform_conf" in hass.config.components
assert not config["platform_conf"] # empty
async def test_validate_platform_config_2(hass, caplog):
"""Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA."""
platform_schema = PLATFORM_SCHEMA.extend({"hello": str})
platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"})
mock_integration(
hass,
MockModule(
"platform_conf",
platform_schema=platform_schema,
platform_schema_base=platform_schema_base,
),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform("whatever", platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
# pass
"platform_conf": {"platform": "whatever", "hello": "world"},
# fail: key hello violates component platform_schema_base
"platform_conf 2": {"platform": "whatever", "hello": "there"},
},
)
async def test_validate_platform_config_3(hass, caplog):
"""Test fallback to component PLATFORM_SCHEMA."""
component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str})
platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"})
mock_integration(
hass, MockModule("platform_conf", platform_schema=component_schema)
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform("whatever", platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
# pass
"platform_conf": {"platform": "whatever", "hello": "world"},
# fail: key hello violates component platform_schema
"platform_conf 2": {"platform": "whatever", "hello": "there"},
},
)
async def test_validate_platform_config_4(hass):
"""Test entity_namespace in PLATFORM_SCHEMA."""
component_schema = PLATFORM_SCHEMA_BASE
platform_schema = PLATFORM_SCHEMA
mock_integration(
hass,
MockModule("platform_conf", platform_schema_base=component_schema),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform(platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
"platform_conf": {
# pass: entity_namespace accepted by PLATFORM_SCHEMA
"platform": "whatever",
"entity_namespace": "yummy",
}
},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
async def test_component_not_found(hass):
"""setup_component should not crash if component doesn't exist."""
assert await setup.async_setup_component(hass, "non_existing", {}) is False
async def test_component_not_double_initialized(hass):
"""Test we do not set up a component twice."""
mock_setup = Mock(return_value=True)
mock_integration(hass, MockModule("comp", setup=mock_setup))
assert await setup.async_setup_component(hass, "comp", {})
assert mock_setup.called
mock_setup.reset_mock()
assert await setup.async_setup_component(hass, "comp", {})
assert not mock_setup.called
async def test_component_not_installed_if_requirement_fails(hass):
"""Component setup should fail if requirement can't install."""
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
with patch("homeassistant.util.package.install_package", return_value=False):
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_not_setup_twice_if_loaded_during_other_setup(hass):
"""Test component setup while waiting for lock is not set up twice."""
result = []
async def async_setup(hass, config):
"""Tracking Setup."""
result.append(1)
mock_integration(hass, MockModule("comp", async_setup=async_setup))
def setup_component():
"""Set up the component."""
setup.setup_component(hass, "comp", {})
thread = threading.Thread(target=setup_component)
thread.start()
await setup.async_setup_component(hass, "comp", {})
await hass.async_add_executor_job(thread.join)
assert len(result) == 1
async def test_component_not_setup_missing_dependencies(hass):
"""Test we do not set up a component if not all dependencies loaded."""
deps = ["maybe_existing"]
mock_integration(hass, MockModule("comp", dependencies=deps))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(hass, MockModule("comp2", dependencies=deps))
mock_integration(hass, MockModule("maybe_existing"))
assert await setup.async_setup_component(hass, "comp2", {})
async def test_component_failing_setup(hass):
"""Test component that fails setup."""
mock_integration(hass, MockModule("comp", setup=lambda hass, config: False))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_exception_setup(hass):
"""Test component that raises exception during setup."""
def exception_setup(hass, config):
"""Raise exception."""
raise Exception("fail!")
mock_integration(hass, MockModule("comp", setup=exception_setup))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_setup_with_validation_and_dependency(hass):
"""Test all config is passed to dependencies."""
def config_check_setup(hass, config):
"""Test that config is passed in."""
if config.get("comp_a", {}).get("valid", False):
return True
raise Exception(f"Config not passed in: {config}")
platform = MockPlatform()
mock_integration(hass, MockModule("comp_a", setup=config_check_setup))
mock_integration(
hass,
MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]),
)
mock_entity_platform(hass, "switch.platform_a", platform)
await setup.async_setup_component(
hass,
"switch",
{"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}},
)
await hass.async_block_till_done()
assert "comp_a" in hass.config.components
async def test_platform_specific_config_validation(hass):
"""Test platform that specifies config."""
platform_schema = PLATFORM_SCHEMA.extend({"valid": True}, extra=vol.PREVENT_EXTRA)
mock_setup = Mock(spec_set=True)
mock_entity_platform(
hass,
"switch.platform_a",
MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup),
)
with assert_setup_component(0, "switch"):
assert await setup.async_setup_component(
hass,
"switch",
{"switch": {"platform": "platform_a", "invalid": True}},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 0
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
with assert_setup_component(0):
assert await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "platform_a",
"valid": True,
"invalid_extra": True,
}
},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 0
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
with assert_setup_component(1, "switch"):
assert await setup.async_setup_component(
hass,
"switch",
{"switch": {"platform": "platform_a", "valid": True}},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 1
async def test_disable_component_if_invalid_return(hass):
"""Test disabling component if invalid return."""
mock_integration(
hass, MockModule("disabled_component", setup=lambda hass, config: None)
)
assert not await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(
hass,
MockModule("disabled_component", setup=lambda hass, config: False),
)
assert not await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(
hass, MockModule("disabled_component", setup=lambda hass, config: True)
)
assert await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" in hass.config.components
async def test_all_work_done_before_start(hass):
"""Test all init work done till start."""
call_order = []
async def component1_setup(hass, config):
"""Set up mock component."""
await discovery.async_discover(
hass, "test_component2", {}, "test_component2", {}
)
await discovery.async_discover(
hass, "test_component3", {}, "test_component3", {}
)
return True
def component_track_setup(hass, config):
"""Set up mock component."""
call_order.append(1)
return True
mock_integration(hass, MockModule("test_component1", async_setup=component1_setup))
mock_integration(hass, MockModule("test_component2", setup=component_track_setup))
mock_integration(hass, MockModule("test_component3", setup=component_track_setup))
@callback
def track_start(event):
"""Track start event."""
call_order.append(2)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, track_start)
hass.add_job(setup.async_setup_component(hass, "test_component1", {}))
await hass.async_block_till_done()
await hass.async_start()
assert call_order == [1, 1, 2]
async def test_component_warn_slow_setup(hass):
"""Warn we log when a component setup takes a long time."""
mock_integration(hass, MockModule("test_component1"))
with patch.object(hass.loop, "call_later") as mock_call:
result = await setup.async_setup_component(hass, "test_component1", {})
assert result
assert mock_call.called
assert len(mock_call.mock_calls) == 3
timeout, logger_method = mock_call.mock_calls[0][1][:2]
assert timeout == setup.SLOW_SETUP_WARNING
assert logger_method == setup._LOGGER.warning
assert mock_call().cancel.called
async def test_platform_no_warn_slow(hass):
"""Do not warn for long entity setup time."""
mock_integration(
hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA)
)
with patch.object(hass.loop, "call_later") as mock_call:
result = await setup.async_setup_component(hass, "test_component1", {})
assert result
assert len(mock_call.mock_calls) == 0
async def test_platform_error_slow_setup(hass, caplog):
"""Don't block startup more than SLOW_SETUP_MAX_WAIT."""
with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 0.1):
called = []
async def async_setup(*args):
"""Tracking Setup."""
called.append(1)
await asyncio.sleep(2)
mock_integration(hass, MockModule("test_component1", async_setup=async_setup))
result = await setup.async_setup_component(hass, "test_component1", {})
assert len(called) == 1
assert not result
assert "test_component1 is taking longer than 0.1 seconds" in caplog.text
async def test_when_setup_already_loaded(hass):
"""Test when setup."""
calls = []
async def mock_callback(hass, component):
"""Mock callback."""
calls.append(component)
setup.async_when_setup(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == []
hass.config.components.add("test")
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
# Event listener should be gone
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
# Should be called right away
setup.async_when_setup(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
async def test_async_when_setup_or_start_already_loaded(hass):
"""Test when setup or start."""
calls = []
async def mock_callback(hass, component):
"""Mock callback."""
calls.append(component)
setup.async_when_setup_or_start(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == []
hass.config.components.add("test")
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
# Event listener should be gone
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
# Should be called right away
setup.async_when_setup_or_start(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
setup.async_when_setup_or_start(hass, "not_loaded", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert calls == ["test", "test", "not_loaded"]
async def test_setup_import_blows_up(hass):
"""Test that we handle it correctly when importing integration blows up."""
with patch(
"homeassistant.loader.Integration.get_component", side_effect=ImportError
):
assert not await setup.async_setup_component(hass, "sun", {})
async def test_parallel_entry_setup(hass, mock_handlers):
"""Test config entries are set up in parallel."""
MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass)
MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass)
calls = []
async def mock_async_setup_entry(hass, entry):
"""Mock setting up an entry."""
calls.append(entry.data["value"])
await asyncio.sleep(0)
calls.append(entry.data["value"])
return True
mock_integration(
hass,
MockModule(
"comp",
async_setup_entry=mock_async_setup_entry,
),
)
mock_entity_platform(hass, "config_flow.comp", None)
await setup.async_setup_component(hass, "comp", {})
assert calls == [1, 2, 1, 2]
async def test_integration_disabled(hass, caplog):
"""Test we can disable an integration."""
disabled_reason = "Dependency contains code that breaks Home Assistant"
mock_integration(
hass,
MockModule("test_component1", partial_manifest={"disabled": disabled_reason}),
)
result = await setup.async_setup_component(hass, "test_component1", {})
assert not result
assert disabled_reason in caplog.text
async def test_async_get_loaded_integrations(hass):
"""Test we can enumerate loaded integations."""
hass.config.components.add("notbase")
hass.config.components.add("switch")
hass.config.components.add("notbase.switch")
hass.config.components.add("myintegration")
hass.config.components.add("device_tracker")
hass.config.components.add("device_tracker.other")
hass.config.components.add("myintegration.light")
assert setup.async_get_loaded_integrations(hass) == {
"other",
"switch",
"notbase",
"myintegration",
"device_tracker",
}
async def test_integration_no_setup(hass, caplog):
"""Test we fail integration setup without setup functions."""
mock_integration(
hass,
MockModule("test_integration_without_setup", setup=False),
)
result = await setup.async_setup_component(
hass, "test_integration_without_setup", {}
)
assert not result
assert "No setup or config entry setup function defined" in caplog.text
async def test_integration_only_setup_entry(hass):
"""Test we have an integration with only a setup entry method."""
mock_integration(
hass,
MockModule(
"test_integration_only_entry",
setup=False,
async_setup_entry=AsyncMock(return_value=True),
),
)
assert await setup.async_setup_component(hass, "test_integration_only_entry", {})
async def test_async_start_setup(hass):
"""Test setup started context manager keeps track of setup times."""
with setup.async_start_setup(hass, ["august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime
)
with setup.async_start_setup(hass, ["august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime
)
assert "august" not in hass.data[setup.DATA_SETUP_STARTED]
assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta)
assert "august_2" not in hass.data[setup.DATA_SETUP_TIME]
async def test_async_start_setup_platforms(hass):
"""Test setup started context manager keeps track of setup times for platforms."""
with setup.async_start_setup(hass, ["sensor.august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime
)
assert "august" not in hass.data[setup.DATA_SETUP_STARTED]
assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta)
assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
| 32.485591 | 87 | 0.668751 |
import asyncio
import datetime
import threading
from unittest.mock import AsyncMock, Mock, patch
import pytest
import voluptuous as vol
from homeassistant import config_entries, setup
from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START
from homeassistant.core import callback
from homeassistant.helpers import discovery
from homeassistant.helpers.config_validation import (
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
assert_setup_component,
mock_entity_platform,
mock_integration,
)
@pytest.fixture
def mock_handlers():
class MockFlowHandler(config_entries.ConfigFlow):
VERSION = 1
with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}):
yield
async def test_validate_component_config(hass):
config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True)
mock_integration(hass, MockModule("comp_conf", config_schema=config_schema))
with assert_setup_component(0):
assert not await setup.async_setup_component(hass, "comp_conf", {})
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": None}
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": {}}
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(0):
assert not await setup.async_setup_component(
hass,
"comp_conf",
{"comp_conf": {"hello": "world", "invalid": "extra"}},
)
hass.data.pop(setup.DATA_SETUP)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass, "comp_conf", {"comp_conf": {"hello": "world"}}
)
async def test_validate_platform_config(hass, caplog):
platform_schema = PLATFORM_SCHEMA.extend({"hello": str})
platform_schema_base = PLATFORM_SCHEMA_BASE.extend({})
mock_integration(
hass,
MockModule("platform_conf", platform_schema_base=platform_schema_base),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform(platform_schema=platform_schema),
)
with assert_setup_component(0):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": {"platform": "not_existing", "hello": "world"}},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": {"platform": "whatever", "hello": "world"}},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{"platform_conf": [{"platform": "whatever", "hello": "world"}]},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
with assert_setup_component(0) as config:
assert await setup.async_setup_component(
hass, "platform_conf", {"platform_conf": None}
)
assert "platform_conf" in hass.config.components
assert not config["platform_conf"]
assert await setup.async_setup_component(
hass, "platform_conf", {"platform_conf": {}}
)
assert "platform_conf" in hass.config.components
assert not config["platform_conf"]
async def test_validate_platform_config_2(hass, caplog):
platform_schema = PLATFORM_SCHEMA.extend({"hello": str})
platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"})
mock_integration(
hass,
MockModule(
"platform_conf",
platform_schema=platform_schema,
platform_schema_base=platform_schema_base,
),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform("whatever", platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
"platform_conf": {"platform": "whatever", "hello": "world"},
"platform_conf 2": {"platform": "whatever", "hello": "there"},
},
)
async def test_validate_platform_config_3(hass, caplog):
component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str})
platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"})
mock_integration(
hass, MockModule("platform_conf", platform_schema=component_schema)
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform("whatever", platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
"platform_conf": {"platform": "whatever", "hello": "world"},
"platform_conf 2": {"platform": "whatever", "hello": "there"},
},
)
async def test_validate_platform_config_4(hass):
component_schema = PLATFORM_SCHEMA_BASE
platform_schema = PLATFORM_SCHEMA
mock_integration(
hass,
MockModule("platform_conf", platform_schema_base=component_schema),
)
mock_entity_platform(
hass,
"platform_conf.whatever",
MockPlatform(platform_schema=platform_schema),
)
with assert_setup_component(1):
assert await setup.async_setup_component(
hass,
"platform_conf",
{
"platform_conf": {
"platform": "whatever",
"entity_namespace": "yummy",
}
},
)
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("platform_conf")
async def test_component_not_found(hass):
assert await setup.async_setup_component(hass, "non_existing", {}) is False
async def test_component_not_double_initialized(hass):
mock_setup = Mock(return_value=True)
mock_integration(hass, MockModule("comp", setup=mock_setup))
assert await setup.async_setup_component(hass, "comp", {})
assert mock_setup.called
mock_setup.reset_mock()
assert await setup.async_setup_component(hass, "comp", {})
assert not mock_setup.called
async def test_component_not_installed_if_requirement_fails(hass):
hass.config.skip_pip = False
mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"]))
with patch("homeassistant.util.package.install_package", return_value=False):
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_not_setup_twice_if_loaded_during_other_setup(hass):
result = []
async def async_setup(hass, config):
result.append(1)
mock_integration(hass, MockModule("comp", async_setup=async_setup))
def setup_component():
setup.setup_component(hass, "comp", {})
thread = threading.Thread(target=setup_component)
thread.start()
await setup.async_setup_component(hass, "comp", {})
await hass.async_add_executor_job(thread.join)
assert len(result) == 1
async def test_component_not_setup_missing_dependencies(hass):
deps = ["maybe_existing"]
mock_integration(hass, MockModule("comp", dependencies=deps))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(hass, MockModule("comp2", dependencies=deps))
mock_integration(hass, MockModule("maybe_existing"))
assert await setup.async_setup_component(hass, "comp2", {})
async def test_component_failing_setup(hass):
mock_integration(hass, MockModule("comp", setup=lambda hass, config: False))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_exception_setup(hass):
def exception_setup(hass, config):
raise Exception("fail!")
mock_integration(hass, MockModule("comp", setup=exception_setup))
assert not await setup.async_setup_component(hass, "comp", {})
assert "comp" not in hass.config.components
async def test_component_setup_with_validation_and_dependency(hass):
def config_check_setup(hass, config):
if config.get("comp_a", {}).get("valid", False):
return True
raise Exception(f"Config not passed in: {config}")
platform = MockPlatform()
mock_integration(hass, MockModule("comp_a", setup=config_check_setup))
mock_integration(
hass,
MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]),
)
mock_entity_platform(hass, "switch.platform_a", platform)
await setup.async_setup_component(
hass,
"switch",
{"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}},
)
await hass.async_block_till_done()
assert "comp_a" in hass.config.components
async def test_platform_specific_config_validation(hass):
platform_schema = PLATFORM_SCHEMA.extend({"valid": True}, extra=vol.PREVENT_EXTRA)
mock_setup = Mock(spec_set=True)
mock_entity_platform(
hass,
"switch.platform_a",
MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup),
)
with assert_setup_component(0, "switch"):
assert await setup.async_setup_component(
hass,
"switch",
{"switch": {"platform": "platform_a", "invalid": True}},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 0
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
with assert_setup_component(0):
assert await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "platform_a",
"valid": True,
"invalid_extra": True,
}
},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 0
hass.data.pop(setup.DATA_SETUP)
hass.config.components.remove("switch")
with assert_setup_component(1, "switch"):
assert await setup.async_setup_component(
hass,
"switch",
{"switch": {"platform": "platform_a", "valid": True}},
)
await hass.async_block_till_done()
assert mock_setup.call_count == 1
async def test_disable_component_if_invalid_return(hass):
mock_integration(
hass, MockModule("disabled_component", setup=lambda hass, config: None)
)
assert not await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(
hass,
MockModule("disabled_component", setup=lambda hass, config: False),
)
assert not await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" not in hass.config.components
hass.data.pop(setup.DATA_SETUP)
mock_integration(
hass, MockModule("disabled_component", setup=lambda hass, config: True)
)
assert await setup.async_setup_component(hass, "disabled_component", {})
assert "disabled_component" in hass.config.components
async def test_all_work_done_before_start(hass):
call_order = []
async def component1_setup(hass, config):
await discovery.async_discover(
hass, "test_component2", {}, "test_component2", {}
)
await discovery.async_discover(
hass, "test_component3", {}, "test_component3", {}
)
return True
def component_track_setup(hass, config):
call_order.append(1)
return True
mock_integration(hass, MockModule("test_component1", async_setup=component1_setup))
mock_integration(hass, MockModule("test_component2", setup=component_track_setup))
mock_integration(hass, MockModule("test_component3", setup=component_track_setup))
@callback
def track_start(event):
call_order.append(2)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, track_start)
hass.add_job(setup.async_setup_component(hass, "test_component1", {}))
await hass.async_block_till_done()
await hass.async_start()
assert call_order == [1, 1, 2]
async def test_component_warn_slow_setup(hass):
mock_integration(hass, MockModule("test_component1"))
with patch.object(hass.loop, "call_later") as mock_call:
result = await setup.async_setup_component(hass, "test_component1", {})
assert result
assert mock_call.called
assert len(mock_call.mock_calls) == 3
timeout, logger_method = mock_call.mock_calls[0][1][:2]
assert timeout == setup.SLOW_SETUP_WARNING
assert logger_method == setup._LOGGER.warning
assert mock_call().cancel.called
async def test_platform_no_warn_slow(hass):
mock_integration(
hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA)
)
with patch.object(hass.loop, "call_later") as mock_call:
result = await setup.async_setup_component(hass, "test_component1", {})
assert result
assert len(mock_call.mock_calls) == 0
async def test_platform_error_slow_setup(hass, caplog):
with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 0.1):
called = []
async def async_setup(*args):
called.append(1)
await asyncio.sleep(2)
mock_integration(hass, MockModule("test_component1", async_setup=async_setup))
result = await setup.async_setup_component(hass, "test_component1", {})
assert len(called) == 1
assert not result
assert "test_component1 is taking longer than 0.1 seconds" in caplog.text
async def test_when_setup_already_loaded(hass):
calls = []
async def mock_callback(hass, component):
calls.append(component)
setup.async_when_setup(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == []
hass.config.components.add("test")
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
setup.async_when_setup(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
async def test_async_when_setup_or_start_already_loaded(hass):
calls = []
async def mock_callback(hass, component):
calls.append(component)
setup.async_when_setup_or_start(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == []
hass.config.components.add("test")
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"})
await hass.async_block_till_done()
assert calls == ["test"]
setup.async_when_setup_or_start(hass, "test", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
setup.async_when_setup_or_start(hass, "not_loaded", mock_callback)
await hass.async_block_till_done()
assert calls == ["test", "test"]
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert calls == ["test", "test", "not_loaded"]
async def test_setup_import_blows_up(hass):
with patch(
"homeassistant.loader.Integration.get_component", side_effect=ImportError
):
assert not await setup.async_setup_component(hass, "sun", {})
async def test_parallel_entry_setup(hass, mock_handlers):
MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass)
MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass)
calls = []
async def mock_async_setup_entry(hass, entry):
calls.append(entry.data["value"])
await asyncio.sleep(0)
calls.append(entry.data["value"])
return True
mock_integration(
hass,
MockModule(
"comp",
async_setup_entry=mock_async_setup_entry,
),
)
mock_entity_platform(hass, "config_flow.comp", None)
await setup.async_setup_component(hass, "comp", {})
assert calls == [1, 2, 1, 2]
async def test_integration_disabled(hass, caplog):
disabled_reason = "Dependency contains code that breaks Home Assistant"
mock_integration(
hass,
MockModule("test_component1", partial_manifest={"disabled": disabled_reason}),
)
result = await setup.async_setup_component(hass, "test_component1", {})
assert not result
assert disabled_reason in caplog.text
async def test_async_get_loaded_integrations(hass):
hass.config.components.add("notbase")
hass.config.components.add("switch")
hass.config.components.add("notbase.switch")
hass.config.components.add("myintegration")
hass.config.components.add("device_tracker")
hass.config.components.add("device_tracker.other")
hass.config.components.add("myintegration.light")
assert setup.async_get_loaded_integrations(hass) == {
"other",
"switch",
"notbase",
"myintegration",
"device_tracker",
}
async def test_integration_no_setup(hass, caplog):
mock_integration(
hass,
MockModule("test_integration_without_setup", setup=False),
)
result = await setup.async_setup_component(
hass, "test_integration_without_setup", {}
)
assert not result
assert "No setup or config entry setup function defined" in caplog.text
async def test_integration_only_setup_entry(hass):
mock_integration(
hass,
MockModule(
"test_integration_only_entry",
setup=False,
async_setup_entry=AsyncMock(return_value=True),
),
)
assert await setup.async_setup_component(hass, "test_integration_only_entry", {})
async def test_async_start_setup(hass):
with setup.async_start_setup(hass, ["august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime
)
with setup.async_start_setup(hass, ["august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime
)
assert "august" not in hass.data[setup.DATA_SETUP_STARTED]
assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta)
assert "august_2" not in hass.data[setup.DATA_SETUP_TIME]
async def test_async_start_setup_platforms(hass):
with setup.async_start_setup(hass, ["sensor.august"]):
assert isinstance(
hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime
)
assert "august" not in hass.data[setup.DATA_SETUP_STARTED]
assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta)
assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
| true | true |
f71ba0d3b326ae8b8647aa96334c5b3c71a2f678 | 865 | py | Python | epycom/univariate/__init__.py | ICRC-BME/epycom | 5bfa3fb9020f04536b7a08382533c8abf56ca85f | [
"Apache-2.0"
] | null | null | null | epycom/univariate/__init__.py | ICRC-BME/epycom | 5bfa3fb9020f04536b7a08382533c8abf56ca85f | [
"Apache-2.0"
] | 1 | 2020-10-22T19:10:57.000Z | 2020-10-22T21:09:02.000Z | epycom/univariate/__init__.py | ICRC-BME/epycom | 5bfa3fb9020f04536b7a08382533c8abf56ca85f | [
"Apache-2.0"
] | 1 | 2021-02-24T10:07:32.000Z | 2021-02-24T10:07:32.000Z | from .signal_stats import compute_signal_stats, SignalStats
from .hjorth_mobility import compute_hjorth_mobility, HjorthMobility
from .hjorth_complexity import compute_hjorth_complexity, HjorthComplexity
from .lyapunov_exponent import compute_lyapunov_exponent, LyapunovExponent
from .power_spectral_entropy import compute_pse, PowerSpectralEntropy
from .modulation_index import compute_mi_count, ModulationIndex
from .mean_vector_length import compute_mvl_count, MeanVectorLength
from .phase_locking_value import compute_plv_count, PhaseLockingValue
from .arr import compute_arr, AutoregressiveResidualModulation
from .shannon_entropy import compute_shanon_entropy, ShannonEntropy
from .approximate_entropy import (compute_approximate_entropy,
ApproximateEntropy)
from .sample_entropy import compute_sample_entropy, SampleEntropy
| 61.785714 | 74 | 0.861272 | from .signal_stats import compute_signal_stats, SignalStats
from .hjorth_mobility import compute_hjorth_mobility, HjorthMobility
from .hjorth_complexity import compute_hjorth_complexity, HjorthComplexity
from .lyapunov_exponent import compute_lyapunov_exponent, LyapunovExponent
from .power_spectral_entropy import compute_pse, PowerSpectralEntropy
from .modulation_index import compute_mi_count, ModulationIndex
from .mean_vector_length import compute_mvl_count, MeanVectorLength
from .phase_locking_value import compute_plv_count, PhaseLockingValue
from .arr import compute_arr, AutoregressiveResidualModulation
from .shannon_entropy import compute_shanon_entropy, ShannonEntropy
from .approximate_entropy import (compute_approximate_entropy,
ApproximateEntropy)
from .sample_entropy import compute_sample_entropy, SampleEntropy
| true | true |
f71ba1197905e6582410e47931bec23c9ece6799 | 8,846 | py | Python | Code/CarbonEquiv_Talmy.py | gshowalt/VirusPopModel | 8d41294fa06a44e8fa22ef390d6db14fba7818a1 | [
"CC0-1.0"
] | null | null | null | Code/CarbonEquiv_Talmy.py | gshowalt/VirusPopModel | 8d41294fa06a44e8fa22ef390d6db14fba7818a1 | [
"CC0-1.0"
] | null | null | null | Code/CarbonEquiv_Talmy.py | gshowalt/VirusPopModel | 8d41294fa06a44e8fa22ef390d6db14fba7818a1 | [
"CC0-1.0"
] | null | null | null |
# importing all modules
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib import cm
import matplotlib.tri as tri
from matplotlib.colors import LogNorm
import matplotlib.patches as mpatches
from matplotlib.ticker import LogFormatter
from collections import Counter
from functools import wraps
import csv
import sys
import itertools
from itertools import islice, cycle, chain
import scipy as sp
from scipy.interpolate import griddata
from scipy import interpolate
from scipy.integrate import odeint
from scipy.stats import pareto
from scipy.stats import loguniform
import seaborn as sns
import pandas as pd
import statistics as stats
import lhsmdu
from math import nan
from SALib.sample import saltelli, latin, ff
from SALib.analyze import sobol
import random
# define the function which includes the differential equations
# this was adapted from the leak/lyse experiment so I just left that in and set it to a final value later
def f2(s,t, leak, lyse, temp):
# first define the relative contact rate (RCR) and brine concentrating factor (BCF) by temp
if temp < -1:
RCR = 0.0716*temp**4 + 2.9311*temp**3 + 34.108*temp**2 + 45.826*temp + 3.5125 #Fit from Wells and Deming, 2006
BCF = -0.0106 * temp **2 - 0.519 * temp + 0.2977
sal = 32 * BCF
else:
RCR = 1
sal = 32
# these are our scaling factors for the temperature-dependent parameter distributions
mux = 1 # for growth rate
betx = 1 # for burst size
phix = 1e-5 # for adsorption rate
gamx = 1 # for lytic fraction
# Temp-dependent parameter distribution for burst size
beta = betx*(0.0064 * temp**3 - 0.3047 * temp ** 2 + 0.7701 * temp + 93.605)
# also parameterized as a curve with a standard deviation (std) for other experiments
# but here was simply a set curve for reproducibility
""" beta_std = 0.0095 * temp **3 - 0.5184 * temp**2 + 2.2456 * temp + 126.59
if beta_std < 0:
beta_std = 0.
beta = np.random.normal(beta_mu, beta_std)"""
# Temp-dependent parameter distribution for growth rate
# (we had two different distributions, but I went with the exponential one)
# mu = mux*(2e-5*temp**3 + 0.0008 * temp **2 + 0.0091 * temp + 0.0386)
# mu = 3e-6*temp**4 + 0.0001*temp**3+0.0014*temp**2 + 0.0092 * temp +0.0333
mu = 0.0441*np.exp(0.4991*temp)
"""mu_std = 0.1*2e-5*temp**3 + 0.0009 * temp **2 + 0.0144 * temp + 0.0818
if mu_std<0:
mu_std = 0.001
mu = np.random.normal(mu_mu, mu_std)"""
# Temp-dependent parameter distribution for adsorption rate
# I also tried it as a function of salinity (immediately below), but chose temp for consistency
#phi = phix * -1e-11*sal**2 +4e-9*sal - 9e-8
phi = phix * (6e-13 * temp **5 - 2e-11 * temp ** 4 + 1e-10 * temp ** 3 + 3e-9 * temp ** 2 - 3e-8 * temp + 5e-8)
"""phi_std = -2e-11*sal**2 + 4e-9*sal - 9e-8
if phi_std < 0:
phi_std = 0
phi = np.random.normal(phi_mu, phi_std)"""
# set conditions for when curve goes below zero
if mu <= 0:
mu = 0.000
if beta < 0:
beta = 1
if phi < 0:
phi = 1e-15
# now we want to scale adsorption rate by RCR to incorporate the sea ice
phi = phi * RCR
# SET PARAMETERS
alpha = 1.2e-7*3**((temp-23)/10)#4.2e-7 at +8, or 1.2e-7 at lower temps, at -5 --> mu = 0.25/day = 0.01/hr = 1e-8
# alpha is a coefficient that we'd like to change with temperature? Or change eta?
#nutrient transfer coefficient to bacteria (ug/cell * hr)
Q = 0.022
#half saturation constant (ug/mL)
d = 1e-8
#constant of bacterial death (1/hr)
m = 1e-6
#constant of viral decay (1/hr)
g = leak
#POM transfer coefficient from bacteria (ug/cell*hr)
n = lyse
#POM transfer coefficient from viral lysis ug/[burst]cell
#gamma is a lysogeny value
gamma = 1 #-1/temp #*mu
# set up solution matrix
N = s[0]
B = s[1]
V = s[2]
P = s[3]
#systems of equations below
dNdt = - alpha * (N / (N + Q)) * B + g * (alpha * (N/(N+Q))*B) + (n * 1e-7 * (gamma) * phi * V * B)
if N < 0:
N = 0
dBdt = (mu) * (N/(Q + N)) * B - gamma * phi * V * B - d*B
if B < 1:
B = 1
dVdt = gamma*beta * B * phi*V - phi * V * B - m*V
if V < 1:
V = 1
#dPdt = (g * (0.0083*1e-7))*B + (n * 1e-7 * phi * V * B*RCR) + 1e-10*m*V + 1.0e-7*d*B - (P/(P+Q))*alpha * B
dPdt = g * alpha * (N/ (N+Q))*B + n * 1e-7 * (gamma)*phi*B*V
# according to Jover, 2014 - virus has 0.02 to 0.05 fg carbon/virion => translate into ug Carbon = 5e-11
VCarbonEQ = 5e-11
BCarbonEQ = 1e-7 #from Bionumbers
# building the carbon equivalent for viruses, lysate as per Talmy et al 2019
rv = 90 #virus radius (nm)
Qv = (41 * (rv - 2.5)**3 + 130*(7.5*(rv)**2 - 18.74 * rv + 15.63)) * (10e6/(6.022 * 10**23)) # virus carbon eq
phiEQ = (phi)/(Qv)
Qh = 1e-7
etav = beta * (Qv/Qh)
TotalVCarbon = (phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
VirusCarbon = etav * (phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
LysateCarbon = (1-etav)*(phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
LeakCarbon = g * (alpha * (N/(N+Q))*B)
#print (mu, beta, phi, gamma)
return [dNdt, dBdt, dVdt, dPdt, TotalVCarbon, VirusCarbon, LysateCarbon, LeakCarbon]
# define time, temperature scale
time = 5000
temp_list = [-12.5,-10, -8, -6, -4, -2]
t = np.linspace(1,time,1000)
# set up empty matricies
DOMX = []
DOMA = []
DOMB = []
DOMC = []
DOM1 = []
DOM10 = []
DOM100 = []
RCRlist = []
Mulist = []
endvals1 = []
endvals2 = []
endvals3 = []
endvals4 = []
Burstlist = []
Adsorplist = []
count = 0
plt.rcParams["font.family"] = "sans-serif"
fig1 = plt.figure(figsize=(20,15))
fig1.tight_layout()
plt.rcParams.update({'font.size': 15})
for xx in temp_list:
temp = xx
count +=1
mu = 0.0441*np.exp(0.4991*temp)
gamma = 1
#print ("gamma is:", gamma, "and mu is:", mu)
if temp < -1:
RCR = 0.0716*temp**4 + 2.9311*temp**3 + 34.108*temp**2 + 45.826*temp + 3.5125 #Fit from Wells and Deming, 2006
BCF = -0.0106 * temp **2 - 0.519 * temp + 0.2977
sal = 32 * BCF
else:
BCF = 1
sal = 32
s0=[0.12*BCF,1e4*BCF, 1e5*BCF,0,0,0,0,0]
s = odeint(f2,s0,t, args = (0.4,0.99, temp))
xend.append(sum(s[:,3]))
y1 = s[:,4]/(0.12)
y2 = s[:,5]/(0.12)
y3 = s[:,6]/(0.12)
y4 = s[:,7]/(0.12)
plt.subplot(3, 3, count)
colors1 = ['cadetblue', '#FF6F61'] #, 'darkblue']
plt.stackplot(t,y2,y3, colors = colors1,labels=['To Virus','To Lysate'])
plt.legend(loc='lower right')
plt.xlabel('Temperature: {} (˚C)'.format(temp))
plt.yscale('log')
plt.ylabel('% Initial Nutrient')
# take last value of each returned number for the temp-dependent plot
endvals1.append(y1[-1])
endvals2.append(y2[-1])
endvals3.append(y3[-1])
endvals4.append(y4[-1])
# make lists of calculated temp-dependent parameters if we want to plot against them alter
RCRlist.append(RCR)
Mulist.append(mu)
beta = 1*(0.0064 * temp**3 - 0.3047 * temp ** 2 + 0.7701 * temp + 93.605)
Burstlist.append(beta)
phi = RCR* 1 * (6e-13 * temp **5 - 2e-11 * temp ** 4 + 1e-10 * temp ** 3 + 3e-9 * temp ** 2 - 3e-8 * temp + 5e-8)
Adsorplist.append(phi)
plt.subplots_adjust(hspace = 1)
fig1.suptitle("Cumulative organic carbon recycled into Virions or Lysate ",fontsize=15)
# Plot as a funciton of temperature
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams.update({'font.size': 20})
fig2 = plt.figure(figsize=(10,5))
fig2.tight_layout()
endvals1_b = [i/max(endvals1) for i in endvals1]
endvals2_b = [i/max(endvals2) for i in endvals2]
endvals3_b = [i/max(endvals3) for i in endvals3]
endvals4_b = [i/max(endvals4) for i in endvals4]
#ax1 = plt.stackplot(temp_list, endvals2_b, endvals3, colors = colors1) #, labels=['To Virus','To Lysate', 'Cell exudate'])
#ax1 = plt.plot(temp_list, Burstlist)
plt.plot(temp_list,endvals2_b, c = 'cadetblue', marker = 'o', markeredgecolor='white', markersize=15, label='to Virions')
plt.plot(temp_list, endvals3_b, c = '#FA7268', marker = 'o', markeredgecolor='white', markersize=15, label='to Lysate')
plt.xlabel('Temperature (˚C)')
plt.ylabel('Carbon Flow (Relative to Maximum)')
plt.legend(loc='lower right')
fig2.suptitle("Cumulative organic carbon recycled into \nVirions or Lysate as a function of temperature\n",fontsize=15)
# In[88]:
#fig1.savefig('CE_Grid_withRCR_runaway.jpeg', bbox_inches="tight", dpi=300,transparent=True)
#fig2.savefig('CE_Temp_noRCR_line.jpeg', bbox_inches="tight", dpi=300,transparent=True)
| 31.592857 | 123 | 0.618698 |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib import cm
import matplotlib.tri as tri
from matplotlib.colors import LogNorm
import matplotlib.patches as mpatches
from matplotlib.ticker import LogFormatter
from collections import Counter
from functools import wraps
import csv
import sys
import itertools
from itertools import islice, cycle, chain
import scipy as sp
from scipy.interpolate import griddata
from scipy import interpolate
from scipy.integrate import odeint
from scipy.stats import pareto
from scipy.stats import loguniform
import seaborn as sns
import pandas as pd
import statistics as stats
import lhsmdu
from math import nan
from SALib.sample import saltelli, latin, ff
from SALib.analyze import sobol
import random
def f2(s,t, leak, lyse, temp):
if temp < -1:
RCR = 0.0716*temp**4 + 2.9311*temp**3 + 34.108*temp**2 + 45.826*temp + 3.5125
BCF = -0.0106 * temp **2 - 0.519 * temp + 0.2977
sal = 32 * BCF
else:
RCR = 1
sal = 32
mux = 1
betx = 1
phix = 1e-5
gamx = 1
beta = betx*(0.0064 * temp**3 - 0.3047 * temp ** 2 + 0.7701 * temp + 93.605)
mu = 0.0441*np.exp(0.4991*temp)
phi = phix * (6e-13 * temp **5 - 2e-11 * temp ** 4 + 1e-10 * temp ** 3 + 3e-9 * temp ** 2 - 3e-8 * temp + 5e-8)
if mu <= 0:
mu = 0.000
if beta < 0:
beta = 1
if phi < 0:
phi = 1e-15
phi = phi * RCR
alpha = 1.2e-7*3**((temp-23)/10)
#nutrient transfer coefficient to bacteria (ug/cell * hr)
Q = 0.022
#half saturation constant (ug/mL)
d = 1e-8
#constant of bacterial death (1/hr)
m = 1e-6
#constant of viral decay (1/hr)
g = leak
#POM transfer coefficient from bacteria (ug/cell*hr)
n = lyse
#POM transfer coefficient from viral lysis ug/[burst]cell
#gamma is a lysogeny value
gamma = 1 #-1/temp #*mu
# set up solution matrix
N = s[0]
B = s[1]
V = s[2]
P = s[3]
#systems of equations below
dNdt = - alpha * (N / (N + Q)) * B + g * (alpha * (N/(N+Q))*B) + (n * 1e-7 * (gamma) * phi * V * B)
if N < 0:
N = 0
dBdt = (mu) * (N/(Q + N)) * B - gamma * phi * V * B - d*B
if B < 1:
B = 1
dVdt = gamma*beta * B * phi*V - phi * V * B - m*V
if V < 1:
V = 1
#dPdt = (g * (0.0083*1e-7))*B + (n * 1e-7 * phi * V * B*RCR) + 1e-10*m*V + 1.0e-7*d*B - (P/(P+Q))*alpha * B
dPdt = g * alpha * (N/ (N+Q))*B + n * 1e-7 * (gamma)*phi*B*V
# according to Jover, 2014 - virus has 0.02 to 0.05 fg carbon/virion => translate into ug Carbon = 5e-11
VCarbonEQ = 5e-11
BCarbonEQ = 1e-7 #from Bionumbers
# building the carbon equivalent for viruses, lysate as per Talmy et al 2019
rv = 90 #virus radius (nm)
Qv = (41 * (rv - 2.5)**3 + 130*(7.5*(rv)**2 - 18.74 * rv + 15.63)) * (10e6/(6.022 * 10**23)) # virus carbon eq
phiEQ = (phi)/(Qv)
Qh = 1e-7
etav = beta * (Qv/Qh)
TotalVCarbon = (phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
VirusCarbon = etav * (phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
LysateCarbon = (1-etav)*(phiEQ * (gamma) * (V*VCarbonEQ) * (B*BCarbonEQ))
LeakCarbon = g * (alpha * (N/(N+Q))*B)
#print (mu, beta, phi, gamma)
return [dNdt, dBdt, dVdt, dPdt, TotalVCarbon, VirusCarbon, LysateCarbon, LeakCarbon]
# define time, temperature scale
time = 5000
temp_list = [-12.5,-10, -8, -6, -4, -2]
t = np.linspace(1,time,1000)
# set up empty matricies
DOMX = []
DOMA = []
DOMB = []
DOMC = []
DOM1 = []
DOM10 = []
DOM100 = []
RCRlist = []
Mulist = []
endvals1 = []
endvals2 = []
endvals3 = []
endvals4 = []
Burstlist = []
Adsorplist = []
count = 0
plt.rcParams["font.family"] = "sans-serif"
fig1 = plt.figure(figsize=(20,15))
fig1.tight_layout()
plt.rcParams.update({'font.size': 15})
for xx in temp_list:
temp = xx
count +=1
mu = 0.0441*np.exp(0.4991*temp)
gamma = 1
#print ("gamma is:", gamma, "and mu is:", mu)
if temp < -1:
RCR = 0.0716*temp**4 + 2.9311*temp**3 + 34.108*temp**2 + 45.826*temp + 3.5125 #Fit from Wells and Deming, 2006
BCF = -0.0106 * temp **2 - 0.519 * temp + 0.2977
sal = 32 * BCF
else:
BCF = 1
sal = 32
s0=[0.12*BCF,1e4*BCF, 1e5*BCF,0,0,0,0,0]
s = odeint(f2,s0,t, args = (0.4,0.99, temp))
xend.append(sum(s[:,3]))
y1 = s[:,4]/(0.12)
y2 = s[:,5]/(0.12)
y3 = s[:,6]/(0.12)
y4 = s[:,7]/(0.12)
plt.subplot(3, 3, count)
colors1 = ['cadetblue', '
plt.stackplot(t,y2,y3, colors = colors1,labels=['To Virus','To Lysate'])
plt.legend(loc='lower right')
plt.xlabel('Temperature: {} (˚C)'.format(temp))
plt.yscale('log')
plt.ylabel('% Initial Nutrient')
# take last value of each returned number for the temp-dependent plot
endvals1.append(y1[-1])
endvals2.append(y2[-1])
endvals3.append(y3[-1])
endvals4.append(y4[-1])
# make lists of calculated temp-dependent parameters if we want to plot against them alter
RCRlist.append(RCR)
Mulist.append(mu)
beta = 1*(0.0064 * temp**3 - 0.3047 * temp ** 2 + 0.7701 * temp + 93.605)
Burstlist.append(beta)
phi = RCR* 1 * (6e-13 * temp **5 - 2e-11 * temp ** 4 + 1e-10 * temp ** 3 + 3e-9 * temp ** 2 - 3e-8 * temp + 5e-8)
Adsorplist.append(phi)
plt.subplots_adjust(hspace = 1)
fig1.suptitle("Cumulative organic carbon recycled into Virions or Lysate ",fontsize=15)
# Plot as a funciton of temperature
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams.update({'font.size': 20})
fig2 = plt.figure(figsize=(10,5))
fig2.tight_layout()
endvals1_b = [i/max(endvals1) for i in endvals1]
endvals2_b = [i/max(endvals2) for i in endvals2]
endvals3_b = [i/max(endvals3) for i in endvals3]
endvals4_b = [i/max(endvals4) for i in endvals4]
#ax1 = plt.stackplot(temp_list, endvals2_b, endvals3, colors = colors1) #, labels=['To Virus','To Lysate', 'Cell exudate'])
#ax1 = plt.plot(temp_list, Burstlist)
plt.plot(temp_list,endvals2_b, c = 'cadetblue', marker = 'o', markeredgecolor='white', markersize=15, label='to Virions')
plt.plot(temp_list, endvals3_b, c = '
plt.xlabel('Temperature (˚C)')
plt.ylabel('Carbon Flow (Relative to Maximum)')
plt.legend(loc='lower right')
fig2.suptitle("Cumulative organic carbon recycled into \nVirions or Lysate as a function of temperature\n",fontsize=15)
# In[88]:
#fig1.savefig('CE_Grid_withRCR_runaway.jpeg', bbox_inches="tight", dpi=300,transparent=True)
#fig2.savefig('CE_Temp_noRCR_line.jpeg', bbox_inches="tight", dpi=300,transparent=True)
| true | true |
f71ba11fdfcf3709595b11c90277b8596127a219 | 3,479 | py | Python | WonderPy/components/wwCommandHead.py | avrabe/WonderPy | 60d81340bed1085c32803b32209fbbd4c291310a | [
"MIT"
] | 1 | 2019-05-25T16:55:32.000Z | 2019-05-25T16:55:32.000Z | WonderPy/components/wwCommandHead.py | avrabe/WonderPy | 60d81340bed1085c32803b32209fbbd4c291310a | [
"MIT"
] | null | null | null | WonderPy/components/wwCommandHead.py | avrabe/WonderPy | 60d81340bed1085c32803b32209fbbd4c291310a | [
"MIT"
] | null | null | null | from WonderPy.core.wwConstants import WWRobotConstants
from WonderPy.util import wwMath
from .wwCommandBase import WWCommandBase, do_not_call_within_connect_or_sensors
_rc = WWRobotConstants.RobotComponent
_rcv = WWRobotConstants.RobotComponentValues
_rp = WWRobotConstants.RobotProperties
class WWCommandHead(WWCommandBase):
_TIME_ANGLE = 0.2
_TIME_VOLTAGE = 0.6
def __init__(self, robot):
super(WWCommandHead, self).__init__(robot)
def stage_pan_angle(self, pan_degrees):
self._robot.stage_cmds(self.compose_angle(_rc.WW_COMMAND_HEAD_POSITION_PAN,
wwMath.coords_api_to_json_pan(pan_degrees)))
def stage_tilt_angle(self, tilt_degrees):
self._robot.stage_cmds(self.compose_angle(_rc.WW_COMMAND_HEAD_POSITION_TILT,
wwMath.coords_api_to_json_tilt(tilt_degrees)))
def stage_pan_tilt_angle(self, pan_degrees, tilt_degrees):
self.stage_pan_angle(pan_degrees)
self.stage_tilt_angle(tilt_degrees)
def stage_pan_voltage(self, pan_voltage_percent):
self._robot.stage_cmds(self.compose_voltage(_rc.WW_COMMAND_HEAD_PAN_VOLTAGE,
wwMath.coords_api_to_json_pan(pan_voltage_percent)))
def stage_tilt_voltage(self, tilt_voltage_percent):
self._robot.stage_cmds(self.compose_voltage(_rc.WW_COMMAND_HEAD_TILT_VOLTAGE,
wwMath.coords_api_to_json_tilt(tilt_voltage_percent)))
def stage_pan_tilt_voltage(self, pan_voltage_percent, tilt_voltage_percent):
self.stage_pan_voltage(pan_voltage_percent)
self.stage_tilt_voltage(tilt_voltage_percent)
@do_not_call_within_connect_or_sensors
def do_pan_angle(self, pan_degrees, timeout=None):
self.stage_pan_angle(pan_degrees)
self._block_for_simple_timeout(self._TIME_ANGLE, timeout)
@do_not_call_within_connect_or_sensors
def do_tilt_angle(self, tilt_degrees, timeout=None):
self.stage_tilt_angle(tilt_degrees)
self._block_for_simple_timeout(self._TIME_ANGLE, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_tilt_angle(self, pan_degrees, tilt_degrees, timeout=None):
self.stage_pan_tilt_angle(pan_degrees, tilt_degrees)
self._block_for_simple_timeout(0.2, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_voltage(self, pan_voltage_percent, timeout=None):
self.stage_pan_voltage(pan_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@do_not_call_within_connect_or_sensors
def do_tilt_voltage(self, tilt_voltage_percent, timeout=None):
self.stage_tilt_voltage(tilt_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_tilt_voltage(self, pan_voltage_percent, tilt_voltage_percent, timeout=None):
self.stage_pan_tilt_voltage(pan_voltage_percent, tilt_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@staticmethod
def compose_angle(component_id, degrees):
args = {_rcv.WW_COMMAND_VALUE_ANGLE_DEGREE: degrees}
return {component_id: args}
@staticmethod
def compose_voltage(component_id, voltage_percent):
args = {_rcv.WW_COMMAND_VALUE_PERCENTAGE: voltage_percent}
return {component_id: args}
| 43.4875 | 106 | 0.742167 | from WonderPy.core.wwConstants import WWRobotConstants
from WonderPy.util import wwMath
from .wwCommandBase import WWCommandBase, do_not_call_within_connect_or_sensors
_rc = WWRobotConstants.RobotComponent
_rcv = WWRobotConstants.RobotComponentValues
_rp = WWRobotConstants.RobotProperties
class WWCommandHead(WWCommandBase):
_TIME_ANGLE = 0.2
_TIME_VOLTAGE = 0.6
def __init__(self, robot):
super(WWCommandHead, self).__init__(robot)
def stage_pan_angle(self, pan_degrees):
self._robot.stage_cmds(self.compose_angle(_rc.WW_COMMAND_HEAD_POSITION_PAN,
wwMath.coords_api_to_json_pan(pan_degrees)))
def stage_tilt_angle(self, tilt_degrees):
self._robot.stage_cmds(self.compose_angle(_rc.WW_COMMAND_HEAD_POSITION_TILT,
wwMath.coords_api_to_json_tilt(tilt_degrees)))
def stage_pan_tilt_angle(self, pan_degrees, tilt_degrees):
self.stage_pan_angle(pan_degrees)
self.stage_tilt_angle(tilt_degrees)
def stage_pan_voltage(self, pan_voltage_percent):
self._robot.stage_cmds(self.compose_voltage(_rc.WW_COMMAND_HEAD_PAN_VOLTAGE,
wwMath.coords_api_to_json_pan(pan_voltage_percent)))
def stage_tilt_voltage(self, tilt_voltage_percent):
self._robot.stage_cmds(self.compose_voltage(_rc.WW_COMMAND_HEAD_TILT_VOLTAGE,
wwMath.coords_api_to_json_tilt(tilt_voltage_percent)))
def stage_pan_tilt_voltage(self, pan_voltage_percent, tilt_voltage_percent):
self.stage_pan_voltage(pan_voltage_percent)
self.stage_tilt_voltage(tilt_voltage_percent)
@do_not_call_within_connect_or_sensors
def do_pan_angle(self, pan_degrees, timeout=None):
self.stage_pan_angle(pan_degrees)
self._block_for_simple_timeout(self._TIME_ANGLE, timeout)
@do_not_call_within_connect_or_sensors
def do_tilt_angle(self, tilt_degrees, timeout=None):
self.stage_tilt_angle(tilt_degrees)
self._block_for_simple_timeout(self._TIME_ANGLE, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_tilt_angle(self, pan_degrees, tilt_degrees, timeout=None):
self.stage_pan_tilt_angle(pan_degrees, tilt_degrees)
self._block_for_simple_timeout(0.2, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_voltage(self, pan_voltage_percent, timeout=None):
self.stage_pan_voltage(pan_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@do_not_call_within_connect_or_sensors
def do_tilt_voltage(self, tilt_voltage_percent, timeout=None):
self.stage_tilt_voltage(tilt_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@do_not_call_within_connect_or_sensors
def do_pan_tilt_voltage(self, pan_voltage_percent, tilt_voltage_percent, timeout=None):
self.stage_pan_tilt_voltage(pan_voltage_percent, tilt_voltage_percent)
self._block_for_simple_timeout(self._TIME_VOLTAGE, timeout)
@staticmethod
def compose_angle(component_id, degrees):
args = {_rcv.WW_COMMAND_VALUE_ANGLE_DEGREE: degrees}
return {component_id: args}
@staticmethod
def compose_voltage(component_id, voltage_percent):
args = {_rcv.WW_COMMAND_VALUE_PERCENTAGE: voltage_percent}
return {component_id: args}
| true | true |
f71ba187051fb0b138a6e1bd429718edeada1fc7 | 38,002 | py | Python | src/azure-cli/azure/cli/command_modules/monitor/grammar/MetricAlertConditionParser.py | psignoret/azure-cli | 1a4a043750315f9a7f2894b4287126089978b615 | [
"MIT"
] | 1 | 2019-12-12T19:55:26.000Z | 2019-12-12T19:55:26.000Z | src/azure-cli/azure/cli/command_modules/monitor/grammar/MetricAlertConditionParser.py | psignoret/azure-cli | 1a4a043750315f9a7f2894b4287126089978b615 | [
"MIT"
] | 2 | 2021-01-15T09:24:07.000Z | 2021-01-15T09:30:10.000Z | src/azure-cli/azure/cli/command_modules/monitor/grammar/MetricAlertConditionParser.py | psignoret/azure-cli | 1a4a043750315f9a7f2894b4287126089978b615 | [
"MIT"
] | 1 | 2019-11-25T19:33:05.000Z | 2019-11-25T19:33:05.000Z | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=all
# Generated from MetricAlertCondition.g4 by ANTLR 4.7.2
# encoding: utf-8
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3")
buf.write(u"\26~\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write(u"\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4")
buf.write(u"\16\t\16\4\17\t\17\4\20\t\20\3\2\3\2\3\2\3\2\7\2%\n\2")
buf.write(u"\f\2\16\2(\13\2\3\2\3\2\3\2\3\2\3\2\3\2\5\2\60\n\2\3")
buf.write(u"\2\3\2\3\2\3\2\7\2\66\n\2\f\2\16\29\13\2\3\2\7\2<\n\2")
buf.write(u"\f\2\16\2?\13\2\3\3\3\3\3\3\3\4\6\4E\n\4\r\4\16\4F\3")
buf.write(u"\5\6\5J\n\5\r\5\16\5K\3\6\3\6\3\6\3\7\3\7\3\b\3\b\3\b")
buf.write(u"\3\t\3\t\3\t\3\t\3\t\7\t[\n\t\f\t\16\t^\13\t\3\n\3\n")
buf.write(u"\3\n\3\n\3\13\3\13\3\13\3\f\3\f\3\f\3\r\3\r\3\r\3\16")
buf.write(u"\3\16\3\16\3\17\3\17\3\17\3\17\7\17t\n\17\f\17\16\17")
buf.write(u"w\13\17\3\20\6\20z\n\20\r\20\16\20{\3\20\2\2\21\2\4\6")
buf.write(u"\b\n\f\16\20\22\24\26\30\32\34\36\2\b\4\2\3\4\26\26\5")
buf.write(u"\2\3\b\24\24\26\26\4\2\t\t\r\r\3\2\16\17\4\2\t\t\20\20")
buf.write(u"\b\2\3\3\7\7\n\13\22\22\24\24\26\26\2w\2 \3\2\2\2\4@")
buf.write(u"\3\2\2\2\6D\3\2\2\2\bI\3\2\2\2\nM\3\2\2\2\fP\3\2\2\2")
buf.write(u"\16R\3\2\2\2\20U\3\2\2\2\22_\3\2\2\2\24c\3\2\2\2\26f")
buf.write(u"\3\2\2\2\30i\3\2\2\2\32l\3\2\2\2\34o\3\2\2\2\36y\3\2")
buf.write(u"\2\2 &\5\4\3\2!\"\5\6\4\2\"#\7\3\2\2#%\3\2\2\2$!\3\2")
buf.write(u"\2\2%(\3\2\2\2&$\3\2\2\2&\'\3\2\2\2\'/\3\2\2\2(&\3\2")
buf.write(u"\2\2)*\7\23\2\2*+\5\b\5\2+,\7\23\2\2,-\7\24\2\2-\60\3")
buf.write(u"\2\2\2.\60\5\b\5\2/)\3\2\2\2/.\3\2\2\2\60\61\3\2\2\2")
buf.write(u"\61\62\5\n\6\2\62\67\5\f\7\2\63\64\7\24\2\2\64\66\5\20")
buf.write(u"\t\2\65\63\3\2\2\2\669\3\2\2\2\67\65\3\2\2\2\678\3\2")
buf.write(u"\2\28=\3\2\2\29\67\3\2\2\2:<\7\25\2\2;:\3\2\2\2<?\3\2")
buf.write(u"\2\2=;\3\2\2\2=>\3\2\2\2>\3\3\2\2\2?=\3\2\2\2@A\7\26")
buf.write(u"\2\2AB\7\24\2\2B\5\3\2\2\2CE\t\2\2\2DC\3\2\2\2EF\3\2")
buf.write(u"\2\2FD\3\2\2\2FG\3\2\2\2G\7\3\2\2\2HJ\t\3\2\2IH\3\2\2")
buf.write(u"\2JK\3\2\2\2KI\3\2\2\2KL\3\2\2\2L\t\3\2\2\2MN\7\21\2")
buf.write(u"\2NO\7\24\2\2O\13\3\2\2\2PQ\7\22\2\2Q\r\3\2\2\2RS\7\f")
buf.write(u"\2\2ST\7\24\2\2T\17\3\2\2\2UV\5\16\b\2V\\\5\22\n\2WX")
buf.write(u"\5\24\13\2XY\5\22\n\2Y[\3\2\2\2ZW\3\2\2\2[^\3\2\2\2\\")
buf.write(u"Z\3\2\2\2\\]\3\2\2\2]\21\3\2\2\2^\\\3\2\2\2_`\5\32\16")
buf.write(u"\2`a\5\26\f\2ab\5\34\17\2b\23\3\2\2\2cd\t\4\2\2de\7\24")
buf.write(u"\2\2e\25\3\2\2\2fg\t\5\2\2gh\7\24\2\2h\27\3\2\2\2ij\t")
buf.write(u"\6\2\2jk\7\24\2\2k\31\3\2\2\2lm\7\26\2\2mn\7\24\2\2n")
buf.write(u"\33\3\2\2\2ou\5\36\20\2pq\5\30\r\2qr\5\36\20\2rt\3\2")
buf.write(u"\2\2sp\3\2\2\2tw\3\2\2\2us\3\2\2\2uv\3\2\2\2v\35\3\2")
buf.write(u"\2\2wu\3\2\2\2xz\t\7\2\2yx\3\2\2\2z{\3\2\2\2{y\3\2\2")
buf.write(u"\2{|\3\2\2\2|\37\3\2\2\2\13&/\67=FK\\u{")
return buf.getvalue()
class MetricAlertConditionParser ( Parser ):
grammarFileName = "MetricAlertCondition.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ u"<INVALID>", u"'.'", u"'/'", u"'_'", u"'\\'", u"':'",
u"'%'", u"','", u"'-'", u"'*'" ]
symbolicNames = [ u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"<INVALID>", u"WHERE", u"AND", u"INCLUDES",
u"EXCLUDES", u"OR", u"OPERATOR", u"NUMBER", u"QUOTE",
u"WHITESPACE", u"NEWLINE", u"WORD" ]
RULE_expression = 0
RULE_aggregation = 1
RULE_namespace = 2
RULE_metric = 3
RULE_operator = 4
RULE_threshold = 5
RULE_where = 6
RULE_dimensions = 7
RULE_dimension = 8
RULE_dim_separator = 9
RULE_dim_operator = 10
RULE_dim_val_separator = 11
RULE_dim_name = 12
RULE_dim_values = 13
RULE_dim_value = 14
ruleNames = [ u"expression", u"aggregation", u"namespace", u"metric",
u"operator", u"threshold", u"where", u"dimensions", u"dimension",
u"dim_separator", u"dim_operator", u"dim_val_separator",
u"dim_name", u"dim_values", u"dim_value" ]
EOF = Token.EOF
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
T__5=6
T__6=7
T__7=8
T__8=9
WHERE=10
AND=11
INCLUDES=12
EXCLUDES=13
OR=14
OPERATOR=15
NUMBER=16
QUOTE=17
WHITESPACE=18
NEWLINE=19
WORD=20
def __init__(self, input, output=sys.stdout):
super(MetricAlertConditionParser, self).__init__(input, output=output)
self.checkVersion("4.7.2")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class ExpressionContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.ExpressionContext, self).__init__(parent, invokingState)
self.parser = parser
def aggregation(self):
return self.getTypedRuleContext(MetricAlertConditionParser.AggregationContext,0)
def operator(self):
return self.getTypedRuleContext(MetricAlertConditionParser.OperatorContext,0)
def threshold(self):
return self.getTypedRuleContext(MetricAlertConditionParser.ThresholdContext,0)
def QUOTE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.QUOTE)
else:
return self.getToken(MetricAlertConditionParser.QUOTE, i)
def metric(self):
return self.getTypedRuleContext(MetricAlertConditionParser.MetricContext,0)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def namespace(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.NamespaceContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.NamespaceContext,i)
def dimensions(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionsContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.DimensionsContext,i)
def NEWLINE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.NEWLINE)
else:
return self.getToken(MetricAlertConditionParser.NEWLINE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_expression
def enterRule(self, listener):
if hasattr(listener, "enterExpression"):
listener.enterExpression(self)
def exitRule(self, listener):
if hasattr(listener, "exitExpression"):
listener.exitExpression(self)
def expression(self):
localctx = MetricAlertConditionParser.ExpressionContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_expression)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 30
self.aggregation()
self.state = 36
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 31
self.namespace()
self.state = 32
self.match(MetricAlertConditionParser.T__0)
self.state = 38
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
self.state = 45
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MetricAlertConditionParser.QUOTE]:
self.state = 39
self.match(MetricAlertConditionParser.QUOTE)
self.state = 40
self.metric()
self.state = 41
self.match(MetricAlertConditionParser.QUOTE)
self.state = 42
self.match(MetricAlertConditionParser.WHITESPACE)
pass
elif token in [MetricAlertConditionParser.T__0, MetricAlertConditionParser.T__1, MetricAlertConditionParser.T__2, MetricAlertConditionParser.T__3, MetricAlertConditionParser.T__4, MetricAlertConditionParser.T__5, MetricAlertConditionParser.WHITESPACE, MetricAlertConditionParser.WORD]:
self.state = 44
self.metric()
pass
else:
raise NoViableAltException(self)
self.state = 47
self.operator()
self.state = 48
self.threshold()
self.state = 53
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.WHITESPACE:
self.state = 49
self.match(MetricAlertConditionParser.WHITESPACE)
self.state = 50
self.dimensions()
self.state = 55
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 59
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.NEWLINE:
self.state = 56
self.match(MetricAlertConditionParser.NEWLINE)
self.state = 61
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AggregationContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.AggregationContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self):
return self.getToken(MetricAlertConditionParser.WORD, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_aggregation
def enterRule(self, listener):
if hasattr(listener, "enterAggregation"):
listener.enterAggregation(self)
def exitRule(self, listener):
if hasattr(listener, "exitAggregation"):
listener.exitAggregation(self)
def aggregation(self):
localctx = MetricAlertConditionParser.AggregationContext(self, self._ctx, self.state)
self.enterRule(localctx, 2, self.RULE_aggregation)
try:
self.enterOuterAlt(localctx, 1)
self.state = 62
self.match(MetricAlertConditionParser.WORD)
self.state = 63
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class NamespaceContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.NamespaceContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_namespace
def enterRule(self, listener):
if hasattr(listener, "enterNamespace"):
listener.enterNamespace(self)
def exitRule(self, listener):
if hasattr(listener, "exitNamespace"):
listener.exitNamespace(self)
def namespace(self):
localctx = MetricAlertConditionParser.NamespaceContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_namespace)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 66
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 65
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
else:
raise NoViableAltException(self)
self.state = 68
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,4,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MetricContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.MetricContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_metric
def enterRule(self, listener):
if hasattr(listener, "enterMetric"):
listener.enterMetric(self)
def exitRule(self, listener):
if hasattr(listener, "exitMetric"):
listener.exitMetric(self)
def metric(self):
localctx = MetricAlertConditionParser.MetricContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_metric)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 71
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 70
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.T__2) | (1 << MetricAlertConditionParser.T__3) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__5) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 73
self._errHandler.sync(self)
_la = self._input.LA(1)
if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.T__2) | (1 << MetricAlertConditionParser.T__3) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__5) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class OperatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.OperatorContext, self).__init__(parent, invokingState)
self.parser = parser
def OPERATOR(self):
return self.getToken(MetricAlertConditionParser.OPERATOR, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_operator
def enterRule(self, listener):
if hasattr(listener, "enterOperator"):
listener.enterOperator(self)
def exitRule(self, listener):
if hasattr(listener, "exitOperator"):
listener.exitOperator(self)
def operator(self):
localctx = MetricAlertConditionParser.OperatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 8, self.RULE_operator)
try:
self.enterOuterAlt(localctx, 1)
self.state = 75
self.match(MetricAlertConditionParser.OPERATOR)
self.state = 76
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ThresholdContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.ThresholdContext, self).__init__(parent, invokingState)
self.parser = parser
def NUMBER(self):
return self.getToken(MetricAlertConditionParser.NUMBER, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_threshold
def enterRule(self, listener):
if hasattr(listener, "enterThreshold"):
listener.enterThreshold(self)
def exitRule(self, listener):
if hasattr(listener, "exitThreshold"):
listener.exitThreshold(self)
def threshold(self):
localctx = MetricAlertConditionParser.ThresholdContext(self, self._ctx, self.state)
self.enterRule(localctx, 10, self.RULE_threshold)
try:
self.enterOuterAlt(localctx, 1)
self.state = 78
self.match(MetricAlertConditionParser.NUMBER)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class WhereContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.WhereContext, self).__init__(parent, invokingState)
self.parser = parser
def WHERE(self):
return self.getToken(MetricAlertConditionParser.WHERE, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_where
def enterRule(self, listener):
if hasattr(listener, "enterWhere"):
listener.enterWhere(self)
def exitRule(self, listener):
if hasattr(listener, "exitWhere"):
listener.exitWhere(self)
def where(self):
localctx = MetricAlertConditionParser.WhereContext(self, self._ctx, self.state)
self.enterRule(localctx, 12, self.RULE_where)
try:
self.enterOuterAlt(localctx, 1)
self.state = 80
self.match(MetricAlertConditionParser.WHERE)
self.state = 81
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DimensionsContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.DimensionsContext, self).__init__(parent, invokingState)
self.parser = parser
def where(self):
return self.getTypedRuleContext(MetricAlertConditionParser.WhereContext,0)
def dimension(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.DimensionContext,i)
def dim_separator(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_separatorContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_separatorContext,i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dimensions
def enterRule(self, listener):
if hasattr(listener, "enterDimensions"):
listener.enterDimensions(self)
def exitRule(self, listener):
if hasattr(listener, "exitDimensions"):
listener.exitDimensions(self)
def dimensions(self):
localctx = MetricAlertConditionParser.DimensionsContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_dimensions)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 83
self.where()
self.state = 84
self.dimension()
self.state = 90
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.AND:
self.state = 85
self.dim_separator()
self.state = 86
self.dimension()
self.state = 92
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DimensionContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.DimensionContext, self).__init__(parent, invokingState)
self.parser = parser
def dim_name(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_nameContext,0)
def dim_operator(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_operatorContext,0)
def dim_values(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valuesContext,0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dimension
def enterRule(self, listener):
if hasattr(listener, "enterDimension"):
listener.enterDimension(self)
def exitRule(self, listener):
if hasattr(listener, "exitDimension"):
listener.exitDimension(self)
def dimension(self):
localctx = MetricAlertConditionParser.DimensionContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_dimension)
try:
self.enterOuterAlt(localctx, 1)
self.state = 93
self.dim_name()
self.state = 94
self.dim_operator()
self.state = 95
self.dim_values()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_separatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_separatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def AND(self):
return self.getToken(MetricAlertConditionParser.AND, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_separator
def enterRule(self, listener):
if hasattr(listener, "enterDim_separator"):
listener.enterDim_separator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_separator"):
listener.exitDim_separator(self)
def dim_separator(self):
localctx = MetricAlertConditionParser.Dim_separatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_dim_separator)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 97
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.AND):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 98
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_operatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_operatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def INCLUDES(self):
return self.getToken(MetricAlertConditionParser.INCLUDES, 0)
def EXCLUDES(self):
return self.getToken(MetricAlertConditionParser.EXCLUDES, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_operator
def enterRule(self, listener):
if hasattr(listener, "enterDim_operator"):
listener.enterDim_operator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_operator"):
listener.exitDim_operator(self)
def dim_operator(self):
localctx = MetricAlertConditionParser.Dim_operatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_dim_operator)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 100
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.INCLUDES or _la==MetricAlertConditionParser.EXCLUDES):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 101
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_val_separatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_val_separatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def OR(self):
return self.getToken(MetricAlertConditionParser.OR, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_val_separator
def enterRule(self, listener):
if hasattr(listener, "enterDim_val_separator"):
listener.enterDim_val_separator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_val_separator"):
listener.exitDim_val_separator(self)
def dim_val_separator(self):
localctx = MetricAlertConditionParser.Dim_val_separatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_dim_val_separator)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 103
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.OR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 104
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_nameContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_nameContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self):
return self.getToken(MetricAlertConditionParser.WORD, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_name
def enterRule(self, listener):
if hasattr(listener, "enterDim_name"):
listener.enterDim_name(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_name"):
listener.exitDim_name(self)
def dim_name(self):
localctx = MetricAlertConditionParser.Dim_nameContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_dim_name)
try:
self.enterOuterAlt(localctx, 1)
self.state = 106
self.match(MetricAlertConditionParser.WORD)
self.state = 107
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_valuesContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_valuesContext, self).__init__(parent, invokingState)
self.parser = parser
def dim_value(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_valueContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valueContext,i)
def dim_val_separator(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_val_separatorContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_val_separatorContext,i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_values
def enterRule(self, listener):
if hasattr(listener, "enterDim_values"):
listener.enterDim_values(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_values"):
listener.exitDim_values(self)
def dim_values(self):
localctx = MetricAlertConditionParser.Dim_valuesContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_dim_values)
try:
self.enterOuterAlt(localctx, 1)
self.state = 109
self.dim_value()
self.state = 115
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,7,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 110
self.dim_val_separator()
self.state = 111
self.dim_value()
self.state = 117
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,7,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_valueContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_valueContext, self).__init__(parent, invokingState)
self.parser = parser
def NUMBER(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.NUMBER)
else:
return self.getToken(MetricAlertConditionParser.NUMBER, i)
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_value
def enterRule(self, listener):
if hasattr(listener, "enterDim_value"):
listener.enterDim_value(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_value"):
listener.exitDim_value(self)
def dim_value(self):
localctx = MetricAlertConditionParser.Dim_valueContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_dim_value)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 119
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 118
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__7) | (1 << MetricAlertConditionParser.T__8) | (1 << MetricAlertConditionParser.NUMBER) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
else:
raise NoViableAltException(self)
self.state = 121
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
| 36.47025 | 406 | 0.599416 |
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3")
buf.write(u"\26~\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write(u"\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4")
buf.write(u"\16\t\16\4\17\t\17\4\20\t\20\3\2\3\2\3\2\3\2\7\2%\n\2")
buf.write(u"\f\2\16\2(\13\2\3\2\3\2\3\2\3\2\3\2\3\2\5\2\60\n\2\3")
buf.write(u"\2\3\2\3\2\3\2\7\2\66\n\2\f\2\16\29\13\2\3\2\7\2<\n\2")
buf.write(u"\f\2\16\2?\13\2\3\3\3\3\3\3\3\4\6\4E\n\4\r\4\16\4F\3")
buf.write(u"\5\6\5J\n\5\r\5\16\5K\3\6\3\6\3\6\3\7\3\7\3\b\3\b\3\b")
buf.write(u"\3\t\3\t\3\t\3\t\3\t\7\t[\n\t\f\t\16\t^\13\t\3\n\3\n")
buf.write(u"\3\n\3\n\3\13\3\13\3\13\3\f\3\f\3\f\3\r\3\r\3\r\3\16")
buf.write(u"\3\16\3\16\3\17\3\17\3\17\3\17\7\17t\n\17\f\17\16\17")
buf.write(u"w\13\17\3\20\6\20z\n\20\r\20\16\20{\3\20\2\2\21\2\4\6")
buf.write(u"\b\n\f\16\20\22\24\26\30\32\34\36\2\b\4\2\3\4\26\26\5")
buf.write(u"\2\3\b\24\24\26\26\4\2\t\t\r\r\3\2\16\17\4\2\t\t\20\20")
buf.write(u"\b\2\3\3\7\7\n\13\22\22\24\24\26\26\2w\2 \3\2\2\2\4@")
buf.write(u"\3\2\2\2\6D\3\2\2\2\bI\3\2\2\2\nM\3\2\2\2\fP\3\2\2\2")
buf.write(u"\16R\3\2\2\2\20U\3\2\2\2\22_\3\2\2\2\24c\3\2\2\2\26f")
buf.write(u"\3\2\2\2\30i\3\2\2\2\32l\3\2\2\2\34o\3\2\2\2\36y\3\2")
buf.write(u"\2\2 &\5\4\3\2!\"\5\6\4\2\"#\7\3\2\2#%\3\2\2\2$!\3\2")
buf.write(u"\2\2%(\3\2\2\2&$\3\2\2\2&\'\3\2\2\2\'/\3\2\2\2(&\3\2")
buf.write(u"\2\2)*\7\23\2\2*+\5\b\5\2+,\7\23\2\2,-\7\24\2\2-\60\3")
buf.write(u"\2\2\2.\60\5\b\5\2/)\3\2\2\2/.\3\2\2\2\60\61\3\2\2\2")
buf.write(u"\61\62\5\n\6\2\62\67\5\f\7\2\63\64\7\24\2\2\64\66\5\20")
buf.write(u"\t\2\65\63\3\2\2\2\669\3\2\2\2\67\65\3\2\2\2\678\3\2")
buf.write(u"\2\28=\3\2\2\29\67\3\2\2\2:<\7\25\2\2;:\3\2\2\2<?\3\2")
buf.write(u"\2\2=;\3\2\2\2=>\3\2\2\2>\3\3\2\2\2?=\3\2\2\2@A\7\26")
buf.write(u"\2\2AB\7\24\2\2B\5\3\2\2\2CE\t\2\2\2DC\3\2\2\2EF\3\2")
buf.write(u"\2\2FD\3\2\2\2FG\3\2\2\2G\7\3\2\2\2HJ\t\3\2\2IH\3\2\2")
buf.write(u"\2JK\3\2\2\2KI\3\2\2\2KL\3\2\2\2L\t\3\2\2\2MN\7\21\2")
buf.write(u"\2NO\7\24\2\2O\13\3\2\2\2PQ\7\22\2\2Q\r\3\2\2\2RS\7\f")
buf.write(u"\2\2ST\7\24\2\2T\17\3\2\2\2UV\5\16\b\2V\\\5\22\n\2WX")
buf.write(u"\5\24\13\2XY\5\22\n\2Y[\3\2\2\2ZW\3\2\2\2[^\3\2\2\2\\")
buf.write(u"Z\3\2\2\2\\]\3\2\2\2]\21\3\2\2\2^\\\3\2\2\2_`\5\32\16")
buf.write(u"\2`a\5\26\f\2ab\5\34\17\2b\23\3\2\2\2cd\t\4\2\2de\7\24")
buf.write(u"\2\2e\25\3\2\2\2fg\t\5\2\2gh\7\24\2\2h\27\3\2\2\2ij\t")
buf.write(u"\6\2\2jk\7\24\2\2k\31\3\2\2\2lm\7\26\2\2mn\7\24\2\2n")
buf.write(u"\33\3\2\2\2ou\5\36\20\2pq\5\30\r\2qr\5\36\20\2rt\3\2")
buf.write(u"\2\2sp\3\2\2\2tw\3\2\2\2us\3\2\2\2uv\3\2\2\2v\35\3\2")
buf.write(u"\2\2wu\3\2\2\2xz\t\7\2\2yx\3\2\2\2z{\3\2\2\2{y\3\2\2")
buf.write(u"\2{|\3\2\2\2|\37\3\2\2\2\13&/\67=FK\\u{")
return buf.getvalue()
class MetricAlertConditionParser ( Parser ):
grammarFileName = "MetricAlertCondition.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ u"<INVALID>", u"'.'", u"'/'", u"'_'", u"'\\'", u"':'",
u"'%'", u"','", u"'-'", u"'*'" ]
symbolicNames = [ u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>",
u"<INVALID>", u"<INVALID>", u"WHERE", u"AND", u"INCLUDES",
u"EXCLUDES", u"OR", u"OPERATOR", u"NUMBER", u"QUOTE",
u"WHITESPACE", u"NEWLINE", u"WORD" ]
RULE_expression = 0
RULE_aggregation = 1
RULE_namespace = 2
RULE_metric = 3
RULE_operator = 4
RULE_threshold = 5
RULE_where = 6
RULE_dimensions = 7
RULE_dimension = 8
RULE_dim_separator = 9
RULE_dim_operator = 10
RULE_dim_val_separator = 11
RULE_dim_name = 12
RULE_dim_values = 13
RULE_dim_value = 14
ruleNames = [ u"expression", u"aggregation", u"namespace", u"metric",
u"operator", u"threshold", u"where", u"dimensions", u"dimension",
u"dim_separator", u"dim_operator", u"dim_val_separator",
u"dim_name", u"dim_values", u"dim_value" ]
EOF = Token.EOF
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
T__5=6
T__6=7
T__7=8
T__8=9
WHERE=10
AND=11
INCLUDES=12
EXCLUDES=13
OR=14
OPERATOR=15
NUMBER=16
QUOTE=17
WHITESPACE=18
NEWLINE=19
WORD=20
def __init__(self, input, output=sys.stdout):
super(MetricAlertConditionParser, self).__init__(input, output=output)
self.checkVersion("4.7.2")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class ExpressionContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.ExpressionContext, self).__init__(parent, invokingState)
self.parser = parser
def aggregation(self):
return self.getTypedRuleContext(MetricAlertConditionParser.AggregationContext,0)
def operator(self):
return self.getTypedRuleContext(MetricAlertConditionParser.OperatorContext,0)
def threshold(self):
return self.getTypedRuleContext(MetricAlertConditionParser.ThresholdContext,0)
def QUOTE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.QUOTE)
else:
return self.getToken(MetricAlertConditionParser.QUOTE, i)
def metric(self):
return self.getTypedRuleContext(MetricAlertConditionParser.MetricContext,0)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def namespace(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.NamespaceContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.NamespaceContext,i)
def dimensions(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionsContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.DimensionsContext,i)
def NEWLINE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.NEWLINE)
else:
return self.getToken(MetricAlertConditionParser.NEWLINE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_expression
def enterRule(self, listener):
if hasattr(listener, "enterExpression"):
listener.enterExpression(self)
def exitRule(self, listener):
if hasattr(listener, "exitExpression"):
listener.exitExpression(self)
def expression(self):
localctx = MetricAlertConditionParser.ExpressionContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_expression)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 30
self.aggregation()
self.state = 36
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 31
self.namespace()
self.state = 32
self.match(MetricAlertConditionParser.T__0)
self.state = 38
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
self.state = 45
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [MetricAlertConditionParser.QUOTE]:
self.state = 39
self.match(MetricAlertConditionParser.QUOTE)
self.state = 40
self.metric()
self.state = 41
self.match(MetricAlertConditionParser.QUOTE)
self.state = 42
self.match(MetricAlertConditionParser.WHITESPACE)
pass
elif token in [MetricAlertConditionParser.T__0, MetricAlertConditionParser.T__1, MetricAlertConditionParser.T__2, MetricAlertConditionParser.T__3, MetricAlertConditionParser.T__4, MetricAlertConditionParser.T__5, MetricAlertConditionParser.WHITESPACE, MetricAlertConditionParser.WORD]:
self.state = 44
self.metric()
pass
else:
raise NoViableAltException(self)
self.state = 47
self.operator()
self.state = 48
self.threshold()
self.state = 53
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.WHITESPACE:
self.state = 49
self.match(MetricAlertConditionParser.WHITESPACE)
self.state = 50
self.dimensions()
self.state = 55
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 59
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.NEWLINE:
self.state = 56
self.match(MetricAlertConditionParser.NEWLINE)
self.state = 61
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AggregationContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.AggregationContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self):
return self.getToken(MetricAlertConditionParser.WORD, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_aggregation
def enterRule(self, listener):
if hasattr(listener, "enterAggregation"):
listener.enterAggregation(self)
def exitRule(self, listener):
if hasattr(listener, "exitAggregation"):
listener.exitAggregation(self)
def aggregation(self):
localctx = MetricAlertConditionParser.AggregationContext(self, self._ctx, self.state)
self.enterRule(localctx, 2, self.RULE_aggregation)
try:
self.enterOuterAlt(localctx, 1)
self.state = 62
self.match(MetricAlertConditionParser.WORD)
self.state = 63
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class NamespaceContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.NamespaceContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_namespace
def enterRule(self, listener):
if hasattr(listener, "enterNamespace"):
listener.enterNamespace(self)
def exitRule(self, listener):
if hasattr(listener, "exitNamespace"):
listener.exitNamespace(self)
def namespace(self):
localctx = MetricAlertConditionParser.NamespaceContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_namespace)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 66
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 65
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
else:
raise NoViableAltException(self)
self.state = 68
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,4,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MetricContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.MetricContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_metric
def enterRule(self, listener):
if hasattr(listener, "enterMetric"):
listener.enterMetric(self)
def exitRule(self, listener):
if hasattr(listener, "exitMetric"):
listener.exitMetric(self)
def metric(self):
localctx = MetricAlertConditionParser.MetricContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_metric)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 71
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 70
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.T__2) | (1 << MetricAlertConditionParser.T__3) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__5) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 73
self._errHandler.sync(self)
_la = self._input.LA(1)
if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__1) | (1 << MetricAlertConditionParser.T__2) | (1 << MetricAlertConditionParser.T__3) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__5) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class OperatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.OperatorContext, self).__init__(parent, invokingState)
self.parser = parser
def OPERATOR(self):
return self.getToken(MetricAlertConditionParser.OPERATOR, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_operator
def enterRule(self, listener):
if hasattr(listener, "enterOperator"):
listener.enterOperator(self)
def exitRule(self, listener):
if hasattr(listener, "exitOperator"):
listener.exitOperator(self)
def operator(self):
localctx = MetricAlertConditionParser.OperatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 8, self.RULE_operator)
try:
self.enterOuterAlt(localctx, 1)
self.state = 75
self.match(MetricAlertConditionParser.OPERATOR)
self.state = 76
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ThresholdContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.ThresholdContext, self).__init__(parent, invokingState)
self.parser = parser
def NUMBER(self):
return self.getToken(MetricAlertConditionParser.NUMBER, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_threshold
def enterRule(self, listener):
if hasattr(listener, "enterThreshold"):
listener.enterThreshold(self)
def exitRule(self, listener):
if hasattr(listener, "exitThreshold"):
listener.exitThreshold(self)
def threshold(self):
localctx = MetricAlertConditionParser.ThresholdContext(self, self._ctx, self.state)
self.enterRule(localctx, 10, self.RULE_threshold)
try:
self.enterOuterAlt(localctx, 1)
self.state = 78
self.match(MetricAlertConditionParser.NUMBER)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class WhereContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.WhereContext, self).__init__(parent, invokingState)
self.parser = parser
def WHERE(self):
return self.getToken(MetricAlertConditionParser.WHERE, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_where
def enterRule(self, listener):
if hasattr(listener, "enterWhere"):
listener.enterWhere(self)
def exitRule(self, listener):
if hasattr(listener, "exitWhere"):
listener.exitWhere(self)
def where(self):
localctx = MetricAlertConditionParser.WhereContext(self, self._ctx, self.state)
self.enterRule(localctx, 12, self.RULE_where)
try:
self.enterOuterAlt(localctx, 1)
self.state = 80
self.match(MetricAlertConditionParser.WHERE)
self.state = 81
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DimensionsContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.DimensionsContext, self).__init__(parent, invokingState)
self.parser = parser
def where(self):
return self.getTypedRuleContext(MetricAlertConditionParser.WhereContext,0)
def dimension(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.DimensionContext,i)
def dim_separator(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_separatorContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_separatorContext,i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dimensions
def enterRule(self, listener):
if hasattr(listener, "enterDimensions"):
listener.enterDimensions(self)
def exitRule(self, listener):
if hasattr(listener, "exitDimensions"):
listener.exitDimensions(self)
def dimensions(self):
localctx = MetricAlertConditionParser.DimensionsContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_dimensions)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 83
self.where()
self.state = 84
self.dimension()
self.state = 90
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.AND:
self.state = 85
self.dim_separator()
self.state = 86
self.dimension()
self.state = 92
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DimensionContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.DimensionContext, self).__init__(parent, invokingState)
self.parser = parser
def dim_name(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_nameContext,0)
def dim_operator(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_operatorContext,0)
def dim_values(self):
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valuesContext,0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dimension
def enterRule(self, listener):
if hasattr(listener, "enterDimension"):
listener.enterDimension(self)
def exitRule(self, listener):
if hasattr(listener, "exitDimension"):
listener.exitDimension(self)
def dimension(self):
localctx = MetricAlertConditionParser.DimensionContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_dimension)
try:
self.enterOuterAlt(localctx, 1)
self.state = 93
self.dim_name()
self.state = 94
self.dim_operator()
self.state = 95
self.dim_values()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_separatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_separatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def AND(self):
return self.getToken(MetricAlertConditionParser.AND, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_separator
def enterRule(self, listener):
if hasattr(listener, "enterDim_separator"):
listener.enterDim_separator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_separator"):
listener.exitDim_separator(self)
def dim_separator(self):
localctx = MetricAlertConditionParser.Dim_separatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_dim_separator)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 97
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.AND):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 98
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_operatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_operatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def INCLUDES(self):
return self.getToken(MetricAlertConditionParser.INCLUDES, 0)
def EXCLUDES(self):
return self.getToken(MetricAlertConditionParser.EXCLUDES, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_operator
def enterRule(self, listener):
if hasattr(listener, "enterDim_operator"):
listener.enterDim_operator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_operator"):
listener.exitDim_operator(self)
def dim_operator(self):
localctx = MetricAlertConditionParser.Dim_operatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_dim_operator)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 100
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.INCLUDES or _la==MetricAlertConditionParser.EXCLUDES):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 101
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_val_separatorContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_val_separatorContext, self).__init__(parent, invokingState)
self.parser = parser
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def OR(self):
return self.getToken(MetricAlertConditionParser.OR, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_val_separator
def enterRule(self, listener):
if hasattr(listener, "enterDim_val_separator"):
listener.enterDim_val_separator(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_val_separator"):
listener.exitDim_val_separator(self)
def dim_val_separator(self):
localctx = MetricAlertConditionParser.Dim_val_separatorContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_dim_val_separator)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 103
_la = self._input.LA(1)
if not(_la==MetricAlertConditionParser.T__6 or _la==MetricAlertConditionParser.OR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 104
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_nameContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_nameContext, self).__init__(parent, invokingState)
self.parser = parser
def WORD(self):
return self.getToken(MetricAlertConditionParser.WORD, 0)
def WHITESPACE(self):
return self.getToken(MetricAlertConditionParser.WHITESPACE, 0)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_name
def enterRule(self, listener):
if hasattr(listener, "enterDim_name"):
listener.enterDim_name(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_name"):
listener.exitDim_name(self)
def dim_name(self):
localctx = MetricAlertConditionParser.Dim_nameContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_dim_name)
try:
self.enterOuterAlt(localctx, 1)
self.state = 106
self.match(MetricAlertConditionParser.WORD)
self.state = 107
self.match(MetricAlertConditionParser.WHITESPACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_valuesContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_valuesContext, self).__init__(parent, invokingState)
self.parser = parser
def dim_value(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_valueContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valueContext,i)
def dim_val_separator(self, i=None):
if i is None:
return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_val_separatorContext)
else:
return self.getTypedRuleContext(MetricAlertConditionParser.Dim_val_separatorContext,i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_values
def enterRule(self, listener):
if hasattr(listener, "enterDim_values"):
listener.enterDim_values(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_values"):
listener.exitDim_values(self)
def dim_values(self):
localctx = MetricAlertConditionParser.Dim_valuesContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_dim_values)
try:
self.enterOuterAlt(localctx, 1)
self.state = 109
self.dim_value()
self.state = 115
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,7,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 110
self.dim_val_separator()
self.state = 111
self.dim_value()
self.state = 117
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,7,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Dim_valueContext(ParserRuleContext):
def __init__(self, parser, parent=None, invokingState=-1):
super(MetricAlertConditionParser.Dim_valueContext, self).__init__(parent, invokingState)
self.parser = parser
def NUMBER(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.NUMBER)
else:
return self.getToken(MetricAlertConditionParser.NUMBER, i)
def WORD(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WORD)
else:
return self.getToken(MetricAlertConditionParser.WORD, i)
def WHITESPACE(self, i=None):
if i is None:
return self.getTokens(MetricAlertConditionParser.WHITESPACE)
else:
return self.getToken(MetricAlertConditionParser.WHITESPACE, i)
def getRuleIndex(self):
return MetricAlertConditionParser.RULE_dim_value
def enterRule(self, listener):
if hasattr(listener, "enterDim_value"):
listener.enterDim_value(self)
def exitRule(self, listener):
if hasattr(listener, "exitDim_value"):
listener.exitDim_value(self)
def dim_value(self):
localctx = MetricAlertConditionParser.Dim_valueContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_dim_value)
self._la = 0
try:
self.enterOuterAlt(localctx, 1)
self.state = 119
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 118
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << MetricAlertConditionParser.T__0) | (1 << MetricAlertConditionParser.T__4) | (1 << MetricAlertConditionParser.T__7) | (1 << MetricAlertConditionParser.T__8) | (1 << MetricAlertConditionParser.NUMBER) | (1 << MetricAlertConditionParser.WHITESPACE) | (1 << MetricAlertConditionParser.WORD))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
else:
raise NoViableAltException(self)
self.state = 121
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
| true | true |
f71ba26bbceace7f7efc27a67352c696968b33c7 | 1,513 | py | Python | scripts/roseaa_nbr.py | AluruLab/alfred | ec1c4c634f0d332fac6acc9c113ca54ea42c3f7b | [
"Apache-2.0"
] | null | null | null | scripts/roseaa_nbr.py | AluruLab/alfred | ec1c4c634f0d332fac6acc9c113ca54ea42c3f7b | [
"Apache-2.0"
] | null | null | null | scripts/roseaa_nbr.py | AluruLab/alfred | ec1c4c634f0d332fac6acc9c113ca54ea42c3f7b | [
"Apache-2.0"
] | null | null | null | import sys
import subprocess
import os
import os.path
import glob
import tempfile
#
# run as
# python balibase_nbr.py in_dir out_dir nbr_exe_path
# how I ran :
# python balibase_nbr.py
# /Users/srirampc/work/phd/research/arakawa/data/balibase/tree
# /Users/srirampc/work/phd/research/arakawa/data/balibase/tree
# /Users/srirampc/work/phd/research/arakawa/software/bin/neighbor
in_dir = os.path.abspath(sys.argv[1])
out_dir = os.path.abspath(sys.argv[2])
nbr_exe = sys.argv[3]
# mat_pattern = os.path.join(in_dir, "rose.aa.00*.acs.k[0-6].out")
# mat_pattern = os.path.join(in_dir, "rose.aa.00*.kmacs.k1[6-8].out")
mat_pattern = os.path.join(in_dir, "rose.aa.00*.spaced.out")
mat_lst = glob.glob(mat_pattern)
tfname = tempfile.mktemp()
tfphot = tempfile.mktemp()
print len(mat_lst)
for i, mat_name in enumerate(mat_lst):
mplp_name = mat_name.replace("out", "plp")
mtree_name = mat_name.replace("out", "tree")
ostr = "\n".join([mat_name, "F", mplp_name, "Y", "F", mtree_name])
with open(tfname, "w") as tf:
tf.write(ostr)
if os.path.isfile(mplp_name):
os.remove(mplp_name)
if os.path.isfile(mtree_name):
os.remove(mtree_name)
print i, mat_name, mplp_name
with open(tfphot, "w") as tfo:
with open(tfname) as tf:
rc = subprocess.call([nbr_exe], stdin=tf, stdout=tfo)
if rc != 0:
print "ERROR!"
tfo = open(tfphot)
print "".join(tfo.readlines())
sys.exit(1)
os.remove(tfname)
os.remove(tfphot)
| 29.666667 | 70 | 0.671514 | import sys
import subprocess
import os
import os.path
import glob
import tempfile
in_dir = os.path.abspath(sys.argv[1])
out_dir = os.path.abspath(sys.argv[2])
nbr_exe = sys.argv[3]
mat_pattern = os.path.join(in_dir, "rose.aa.00*.spaced.out")
mat_lst = glob.glob(mat_pattern)
tfname = tempfile.mktemp()
tfphot = tempfile.mktemp()
print len(mat_lst)
for i, mat_name in enumerate(mat_lst):
mplp_name = mat_name.replace("out", "plp")
mtree_name = mat_name.replace("out", "tree")
ostr = "\n".join([mat_name, "F", mplp_name, "Y", "F", mtree_name])
with open(tfname, "w") as tf:
tf.write(ostr)
if os.path.isfile(mplp_name):
os.remove(mplp_name)
if os.path.isfile(mtree_name):
os.remove(mtree_name)
print i, mat_name, mplp_name
with open(tfphot, "w") as tfo:
with open(tfname) as tf:
rc = subprocess.call([nbr_exe], stdin=tf, stdout=tfo)
if rc != 0:
print "ERROR!"
tfo = open(tfphot)
print "".join(tfo.readlines())
sys.exit(1)
os.remove(tfname)
os.remove(tfphot)
| false | true |
f71ba2edf1eecc10a8e2f66fde3fb97bc55e8af1 | 6,386 | py | Python | examples/pwr_run/checkpointing/debug/ovhd_profile/job6.py | boringlee24/keras_old | 1e1176c45c4952ba1b9b9e58e9cc4df027ab111d | [
"MIT"
] | null | null | null | examples/pwr_run/checkpointing/debug/ovhd_profile/job6.py | boringlee24/keras_old | 1e1176c45c4952ba1b9b9e58e9cc4df027ab111d | [
"MIT"
] | null | null | null | examples/pwr_run/checkpointing/debug/ovhd_profile/job6.py | boringlee24/keras_old | 1e1176c45c4952ba1b9b9e58e9cc4df027ab111d | [
"MIT"
] | null | null | null | """
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras import backend as K
from keras.models import Model
from keras.datasets import cifar10
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras import models, layers, optimizers
from datetime import datetime
import tensorflow as tf
import numpy as np
import os
import pdb
import sys
import argparse
import time
import signal
import glob
import json
import send_signal
load_start = time.time()
parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')
parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')
parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')
parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')
parser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')
parser.set_defaults(resume=False)
args = parser.parse_args()
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num
# Training parameters
batch_size = 256
args_lr = 0.005
args_model = 'vgg16'
epoch_begin_time = 0
job_name = sys.argv[0].split('.')[0]
save_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'
total_epochs = 9
starting_epoch = 0
if args.resume:
save_file = glob.glob(save_files)[0]
# epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0])
starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])
data_augmentation = True
num_classes = 10
# Subtracting pixel mean improves accuracy
subtract_pixel_mean = True
n = 3
# Model name, depth and version
model_type = args.tc #'P100_resnet50_he_256_1'
# Load the CIFAR10 data.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Normalize data.
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# If subtract pixel mean is enabled
if subtract_pixel_mean:
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_train_mean
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('y_train shape:', y_train.shape)
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
if args.resume:
print('resume from checkpoint')
model = keras.models.load_model(save_file)
else:
print('train from start')
model = models.Sequential()
if '16' in args_model:
base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
elif '19' in args_model:
base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
#base_model.summary()
#pdb.set_trace()
model.add(base_model)
model.add(layers.Flatten())
model.add(layers.BatchNormalization())
model.add(layers.Dense(128, activation='relu'))#, kernel_initializer='he_uniform'))
#model.add(layers.Dropout(0.2))
model.add(layers.BatchNormalization())
model.add(layers.Dense(64, activation='relu'))#, kernel_initializer='he_uniform'))
#model.add(layers.Dropout(0.2))
model.add(layers.BatchNormalization())
model.add(layers.Dense(10, activation='softmax'))#, kernel_initializer='he_uniform'))
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=args_lr),
metrics=['accuracy'])
#model.summary()
print(model_type)
#pdb.set_trace()
current_epoch = 0
################### connects interrupt signal to the process #####################
def terminateProcess():
save_start = time.time()
# first record the wasted epoch time
global epoch_begin_time
if epoch_begin_time == 0:
epoch_waste_time = 0
else:
epoch_waste_time = int(time.time() - epoch_begin_time)
print('checkpointing the model triggered by kill -15 signal')
# delete whatever checkpoint that already exists
for f in glob.glob(save_files):
os.remove(f)
model.save('/scratch/li.baol/checkpoint_test/' + job_name + '_' + str(current_epoch) + '.h5')
print ('(SIGTERM) terminating the process')
save_time = int(time.time() - save_start)
message = job_name + ' save ' + str(save_time)
send_signal.send(args.node, 10002, message)
sys.exit()
signal.signal(signal.SIGTERM, terminateProcess)
#################################################################################
logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name
tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='batch')
class PrintEpoch(keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
global current_epoch
#remaining_epochs = epochs - epoch
current_epoch = epoch
print('current epoch ' + str(current_epoch))
global epoch_begin_time
epoch_begin_time = time.time()
my_callback = PrintEpoch()
callbacks = [tensorboard_callback, my_callback]
load_time = int(time.time() - load_start)
if args.resume:
message = job_name + ' load ' + str(load_time)
send_signal.send(args.node, 10002, message)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
# send signal to indicate job has finished
message = job_name + ' finish'
send_signal.send(args.node, 10002, message)
sys.exit()
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=1,
validation_data=(x_test, y_test),
shuffle=True,
callbacks=callbacks,
initial_epoch=starting_epoch,
verbose=1
)
if not args.resume:
terminateProcess()
| 31 | 118 | 0.699812 |
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import ReduceLROnPlateau, TensorBoard
from keras.preprocessing.image import ImageDataGenerator
from keras.regularizers import l2
from keras import backend as K
from keras.models import Model
from keras.datasets import cifar10
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras import models, layers, optimizers
from datetime import datetime
import tensorflow as tf
import numpy as np
import os
import pdb
import sys
import argparse
import time
import signal
import glob
import json
import send_signal
load_start = time.time()
parser = argparse.ArgumentParser(description='Tensorflow Cifar10 Training')
parser.add_argument('--tc', metavar='TESTCASE', type=str, help='specific testcase name')
parser.add_argument('--resume', dest='resume', action='store_true', help='if True, resume training from a checkpoint')
parser.add_argument('--gpu_num', metavar='GPU_NUMBER', type=str, help='select which gpu to use')
parser.add_argument('--node', metavar='HOST_NODE', type=str, help='node of the host (scheduler)')
parser.set_defaults(resume=False)
args = parser.parse_args()
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_num
batch_size = 256
args_lr = 0.005
args_model = 'vgg16'
epoch_begin_time = 0
job_name = sys.argv[0].split('.')[0]
save_files = '/scratch/li.baol/checkpoint_test/' + job_name + '*'
total_epochs = 9
starting_epoch = 0
if args.resume:
save_file = glob.glob(save_files)[0]
starting_epoch = int(save_file.split('/')[4].split('.')[0].split('_')[-1])
data_augmentation = True
num_classes = 10
subtract_pixel_mean = True
n = 3
model_type = args.tc
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
if subtract_pixel_mean:
x_train_mean = np.mean(x_train, axis=0)
x_train -= x_train_mean
x_test -= x_train_mean
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print('y_train shape:', y_train.shape)
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
if args.resume:
print('resume from checkpoint')
model = keras.models.load_model(save_file)
else:
print('train from start')
model = models.Sequential()
if '16' in args_model:
base_model = VGG16(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
elif '19' in args_model:
base_model = VGG19(weights=None, include_top=False, input_shape=(32, 32, 3), pooling=None)
model.add(base_model)
model.add(layers.Flatten())
model.add(layers.BatchNormalization())
model.add(layers.Dense(128, activation='relu'))
model.add(layers.BatchNormalization())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.BatchNormalization())
model.add(layers.Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=args_lr),
metrics=['accuracy'])
print(model_type)
current_epoch = 0
| true | true |
f71ba41051966044cb90f99889d007761687b585 | 1,003 | py | Python | bldr/cmd/init.py | bldr-cmd/bldr-cmd | 300750fbccc2987efd23f69b7b2d76d8563e2995 | [
"Apache-2.0"
] | null | null | null | bldr/cmd/init.py | bldr-cmd/bldr-cmd | 300750fbccc2987efd23f69b7b2d76d8563e2995 | [
"Apache-2.0"
] | null | null | null | bldr/cmd/init.py | bldr-cmd/bldr-cmd | 300750fbccc2987efd23f69b7b2d76d8563e2995 | [
"Apache-2.0"
] | null | null | null | """
`init` Command
"""
import os
import click
import bldr
import bldr.dep
import bldr.gen.render
from bldr.environment import Environment
from bldr.gen.render import CopyTemplatesRender
from bldr.cli import pass_environment, run_cmd
dotbldr_path = os.path.join(os.path.abspath(os.path.dirname(bldr.__file__)), "dotbldr")
@click.command("init", short_help="Initializes a project.")
@click.argument("path", required=False, type=click.Path(resolve_path=True))
@pass_environment
def cli(ctx : Environment, path):
"""Initializes a project."""
if path is None:
path = ctx.cwd
ctx.log(f"Initialized the project in {click.format_filename(path)}")
new_dir = os.path.join(os.path.curdir, ".bldr")
ctx.vlog(f" {click.format_filename(dotbldr_path)} -> {new_dir}")
copy_render = CopyTemplatesRender(ctx, True)
copy_render.walk(dotbldr_path, new_dir)
# NOTE: ctx cannot be used prior to this point!!
run_cmd(ctx, 'gen.up')
| 29.5 | 88 | 0.694915 | import os
import click
import bldr
import bldr.dep
import bldr.gen.render
from bldr.environment import Environment
from bldr.gen.render import CopyTemplatesRender
from bldr.cli import pass_environment, run_cmd
dotbldr_path = os.path.join(os.path.abspath(os.path.dirname(bldr.__file__)), "dotbldr")
@click.command("init", short_help="Initializes a project.")
@click.argument("path", required=False, type=click.Path(resolve_path=True))
@pass_environment
def cli(ctx : Environment, path):
if path is None:
path = ctx.cwd
ctx.log(f"Initialized the project in {click.format_filename(path)}")
new_dir = os.path.join(os.path.curdir, ".bldr")
ctx.vlog(f" {click.format_filename(dotbldr_path)} -> {new_dir}")
copy_render = CopyTemplatesRender(ctx, True)
copy_render.walk(dotbldr_path, new_dir)
run_cmd(ctx, 'gen.up')
| true | true |
f71ba50a7212de1e86d1518d29a3a1762b8ef020 | 1,709 | py | Python | ooobuild/lo/datatransfer/x_transferable_ex.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/lo/datatransfer/x_transferable_ex.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/lo/datatransfer/x_transferable_ex.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Interface Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.datatransfer
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from .data_flavor import DataFlavor as DataFlavor_ffd30deb
class XTransferableEx(XInterface_8f010a43):
"""
Interface to be implemented by objects used to provide data for a transfer operation.
See Also:
`API XTransferableEx <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1datatransfer_1_1XTransferableEx.html>`_
"""
__ooo_ns__: str = 'com.sun.star.datatransfer'
__ooo_full_ns__: str = 'com.sun.star.datatransfer.XTransferableEx'
__ooo_type_name__: str = 'interface'
__pyunointerface__: str = 'com.sun.star.datatransfer.XTransferableEx'
@abstractmethod
def queryTransferDataFlavors(self, requestedFlavors: 'typing.Tuple[DataFlavor_ffd30deb, ...]') -> 'typing.Tuple[DataFlavor_ffd30deb, ...]':
"""
"""
__all__ = ['XTransferableEx']
| 37.152174 | 143 | 0.752487 |
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from .data_flavor import DataFlavor as DataFlavor_ffd30deb
class XTransferableEx(XInterface_8f010a43):
__ooo_ns__: str = 'com.sun.star.datatransfer'
__ooo_full_ns__: str = 'com.sun.star.datatransfer.XTransferableEx'
__ooo_type_name__: str = 'interface'
__pyunointerface__: str = 'com.sun.star.datatransfer.XTransferableEx'
@abstractmethod
def queryTransferDataFlavors(self, requestedFlavors: 'typing.Tuple[DataFlavor_ffd30deb, ...]') -> 'typing.Tuple[DataFlavor_ffd30deb, ...]':
__all__ = ['XTransferableEx']
| true | true |
f71ba695de947ffa31af9c54c82d879f96136684 | 20,681 | py | Python | sdk/cdn/azure-mgmt-cdn/tests/test_cli_mgmt_cdn.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 2,728 | 2015-01-09T10:19:32.000Z | 2022-03-31T14:50:33.000Z | sdk/cdn/azure-mgmt-cdn/tests/test_cli_mgmt_cdn.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 17,773 | 2015-01-05T15:57:17.000Z | 2022-03-31T23:50:25.000Z | sdk/cdn/azure-mgmt-cdn/tests/test_cli_mgmt_cdn.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1,916 | 2015-01-19T05:05:41.000Z | 2022-03-31T19:36:44.000Z | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# TEST SCENARIO COVERAGE
# ----------------------
# Methods Total : 41
# Methods Covered : 41
# Examples Total : 42
# Examples Tested : 42
# Coverage % : 100
# ----------------------
import os
import unittest
import azure.mgmt.cdn
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
AZURE_LOCATION = 'eastus'
class MgmtCdnTest(AzureMgmtTestCase):
def setUp(self):
super(MgmtCdnTest, self).setUp()
self.mgmt_client = self.create_mgmt_client(
azure.mgmt.cdn.CdnManagementClient
)
@ResourceGroupPreparer(location=AZURE_LOCATION)
def test_cdn(self, resource_group):
SUBSCRIPTION_ID = None
if self.is_live:
SUBSCRIPTION_ID = os.environ.get("AZURE_SUBSCRIPTION_ID", None)
if not SUBSCRIPTION_ID:
SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
RESOURCE_GROUP = resource_group.name
PROFILE_NAME = "profilename"
CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME = "policyname"
ENDPOINT_NAME = "endpoint9527x"
CUSTOM_DOMAIN_NAME = "someDomain"
ORIGIN_NAME = "origin1"
# Profiles_Create[put]
BODY = {
"location": "WestUs",
"sku": {
"name": "Standard_Verizon"
}
}
result = self.mgmt_client.profiles.begin_create(resource_group.name, PROFILE_NAME, BODY)
result = result.result()
"""
# Creates specific policy[put]
BODY = {
"location": "global",
"sku": {
"name": "Standard_Microsoft"
},
"policy_settings": {
"default_redirect_url": "http://www.bing.com",
"default_custom_block_response_status_code": "499",
"default_custom_block_response_body": "PGh0bWw+CjxoZWFkZXI+PHRpdGxlPkhlbGxvPC90aXRsZT48L2hlYWRlcj4KPGJvZHk+CkhlbGxvIHdvcmxkCjwvYm9keT4KPC9odG1sPg=="
},
"rate_limit_rules": {
"rules": [
{
"name": "RateLimitRule1",
"priority": "1",
"enabled_state": "Enabled",
"rate_limit_duration_in_minutes": "0",
"rate_limit_threshold": "1000",
"match_conditions": [
{
"match_variable": "RemoteAddr",
"operator": "IPMatch",
"negate_condition": False,
"transforms": [],
"match_value": [
"192.168.1.0/24",
"10.0.0.0/24"
]
}
],
"action": "Block"
}
]
},
"custom_rules": {
"rules": [
{
"name": "CustomRule1",
"priority": "2",
"enabled_state": "Enabled",
"match_conditions": [
{
"match_variable": "RemoteAddr",
"operator": "GeoMatch",
"negate_condition": False,
"transforms": [],
"match_value": [
"CH"
]
},
{
"match_variable": "RequestHeader",
"selector": "UserAgent",
"operator": "Contains",
"negate_condition": False,
"transforms": [],
"match_value": [
"windows"
]
},
{
"match_variable": "QueryString",
"selector": "search",
"operator": "Contains",
"negate_condition": False,
"transforms": [
"UrlDecode",
"Lowercase"
],
"match_value": [
"<?php",
"?>"
]
}
],
"action": "Block"
}
]
},
"managed_rules": {
"managed_rule_sets": [
{
"rule_set_type": "DefaultRuleSet",
"rule_set_version": "preview-1.0",
"rule_group_overrides": [
{
"rule_group_name": "Group1",
"rules": [
{
"rule_id": "GROUP1-0001",
"enabled_state": "Enabled",
"action": "Redirect"
},
{
"rule_id": "GROUP1-0002",
"enabled_state": "Disabled"
}
]
}
]
}
]
}
}
result = self.mgmt_client.policies.create_or_update(resource_group.name, CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME, BODY)
result = result.result()
"""
# Endpoints_Create[put]
BODY = {
"origin_host_header": "www.bing.com",
"origin_path": "/image",
"content_types_to_compress": [
"text/html",
"application/octet-stream"
],
"is_compression_enabled": True,
"is_http_allowed": True,
"is_https_allowed": True,
"query_string_caching_behavior": "BypassCaching",
# "delivery_policy": {
# "description": "Test description for a policy.",
# "rules": [
# {
# "name": "rule1",
# "order": "1",
# "conditions": [
# {
# "name": "RemoteAddress",
# "parameters": {
# "operator": "IPMatch",
# "negate_condition": True,
# "match_values": [
# "192.168.1.0/24",
# "10.0.0.0/24"
# ],
# "@odata.type": "#Microsoft.Azure.Cdn.Models.DeliveryRuleRemoteAddressConditionParameters"
# }
# }
# ],
# "actions": [
# {
# "name": "CacheExpiration",
# "parameters": {
# "cache_behavior": "Override",
# "cache_duration": "10:10:09",
# "@odata.type": "#Microsoft.Azure.Cdn.Models.DeliveryRuleCacheExpirationActionParameters",
# "cache_type": "All"
# }
# },
# {
# "name": "ModifyResponseHeader",
# "parameters": {
# "header_action": "Overwrite",
# "header_name": "Access-Control-Allow-Origin",
# "value": "*",
# "@odata.type": "#Microsoft.Azure.Cdn.Models.DeliveryRuleHeaderActionParameters"
# }
# },
# {
# "name": "ModifyRequestHeader",
# "parameters": {
# "header_action": "Overwrite",
# "header_name": "Accept-Encoding",
# "value": "gzip",
# "@odata.type": "#Microsoft.Azure.Cdn.Models.DeliveryRuleHeaderActionParameters"
# }
# }
# ]
# }
# ]
# },
"origins": [
{
"name": "origin1",
"host_name": "host1.hello.com"
}
],
# "web_application_firewall_policy_link": {
# "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/" + CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME + ""
# },
"location": "WestUs",
"tags": {
"kay1": "value1"
}
}
result = self.mgmt_client.endpoints.begin_create(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
"""
# CustomDomains_Create[put]
# BODY = {
# "host_name": "www.someDomain.net"
# }
HOST_NAME = "www.someDomain.net"
result = self.mgmt_client.custom_domains.create(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME, HOST_NAME)
result = result.result()
# CustomDomains_Get[get]
result = self.mgmt_client.custom_domains.get(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME)
"""
# Origins_Get[get]
result = self.mgmt_client.origins.get(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, ORIGIN_NAME)
"""
# Get Policy[get]
result = self.mgmt_client.policies.get(resource_group.name, CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME)
"""
# CustomDomains_ListByEndpoint[get]
result = self.mgmt_client.custom_domains.list_by_endpoint(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
# Origins_ListByEndpoint[get]
result = self.mgmt_client.origins.list_by_endpoint(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
# Endpoints_Get[get]
result = self.mgmt_client.endpoints.get(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
# Endpoints_ListByProfile[get]
result = self.mgmt_client.endpoints.list_by_profile(resource_group.name, PROFILE_NAME)
# List Policies in a Resource Group[get]
result = self.mgmt_client.policies.list(resource_group.name)
# Profiles_Get[get]
result = self.mgmt_client.profiles.get(resource_group.name, PROFILE_NAME)
# Profiles_ListByResourceGroup[get]
result = self.mgmt_client.profiles.list_by_resource_group(resource_group.name)
# List Policies in a Resource Group[get]
result = self.mgmt_client.policies.list(resource_group.name)
# Profiles_List[get]
result = self.mgmt_client.profiles.list()
# Operations_List[get]
result = self.mgmt_client.operations.list()
# EdgeNodes_List[get]
result = self.mgmt_client.edge_nodes.list()
"""
# CustomDomains_DisableCustomHttps[post]
result = self.mgmt_client.custom_domains.disable_custom_https(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME)
# CustomDomains_EnableCustomHttpsUsingYourOwnCertificate[post]
BODY = {
"certificate_source": "AzureKeyVault",
"protocol_type": "ServerNameIndication",
"certificate_source_parameters": {
"odata.type": "#Microsoft.Azure.Cdn.Models.KeyVaultCertificateSourceParameters",
"subscription_id": "subid",
"resource_group_name": "RG",
"vault_name": "kv",
"secret_name": "secret1",
"secret_version": "00000000-0000-0000-0000-000000000000",
"update_rule": "NoAction",
"delete_rule": "NoAction"
}
}
result = self.mgmt_client.custom_domains.enable_custom_https(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME, BODY)
# CustomDomains_EnableCustomHttpsUsingCDNManagedCertificate[post]
BODY = {
"certificate_source": "Cdn",
"protocol_type": "ServerNameIndication",
"certificate_source_parameters": {
"odata.type": "#Microsoft.Azure.Cdn.Models.CdnCertificateSourceParameters",
"certificate_type": "Shared"
}
}
result = self.mgmt_client.custom_domains.enable_custom_https(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME, BODY)
"""
# Origins_Update[patch]
BODY = {
"http_port": "42",
"https_port": "43"
}
result = self.mgmt_client.origins.begin_update(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, ORIGIN_NAME, BODY)
result = result.result()
"""
# Creates specific policy[put]
BODY = {
"location": "WestUs",
"sku": {
"name": "Standard_Microsoft"
},
"policy_settings": {
"default_redirect_url": "http://www.bing.com",
"default_custom_block_response_status_code": "499",
"default_custom_block_response_body": "PGh0bWw+CjxoZWFkZXI+PHRpdGxlPkhlbGxvPC90aXRsZT48L2hlYWRlcj4KPGJvZHk+CkhlbGxvIHdvcmxkCjwvYm9keT4KPC9odG1sPg=="
},
"rate_limit_rules": {
"rules": [
{
"name": "RateLimitRule1",
"priority": "1",
"enabled_state": "Enabled",
"rate_limit_duration_in_minutes": "0",
"rate_limit_threshold": "1000",
"match_conditions": [
{
"match_variable": "RemoteAddr",
"operator": "IPMatch",
"negate_condition": False,
"transforms": [],
"match_value": [
"192.168.1.0/24",
"10.0.0.0/24"
]
}
],
"action": "Block"
}
]
},
"custom_rules": {
"rules": [
{
"name": "CustomRule1",
"priority": "2",
"enabled_state": "Enabled",
"match_conditions": [
{
"match_variable": "RemoteAddr",
"operator": "GeoMatch",
"negate_condition": False,
"transforms": [],
"match_value": [
"CH"
]
},
{
"match_variable": "RequestHeader",
"selector": "UserAgent",
"operator": "Contains",
"negate_condition": False,
"transforms": [],
"match_value": [
"windows"
]
},
{
"match_variable": "QueryString",
"selector": "search",
"operator": "Contains",
"negate_condition": False,
"transforms": [
"UrlDecode",
"Lowercase"
],
"match_value": [
"<?php",
"?>"
]
}
],
"action": "Block"
}
]
},
"managed_rules": {
"managed_rule_sets": [
{
"rule_set_type": "DefaultRuleSet",
"rule_set_version": "preview-1.0",
"rule_group_overrides": [
{
"rule_group_name": "Group1",
"rules": [
{
"rule_id": "GROUP1-0001",
"enabled_state": "Enabled",
"action": "Redirect"
},
{
"rule_id": "GROUP1-0002",
"enabled_state": "Disabled"
}
]
}
]
}
]
}
}
result = self.mgmt_client.policies.create_or_update(resource_group.name, CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME, BODY)
result = result.result()
"""
# Endpoints_ValidateCustomDomain[post]
BODY = {
"host_name": "www.someDomain.com"
}
# HOST_NAME = "www.someDomain.com"
result = self.mgmt_client.endpoints.validate_custom_domain(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
# Endpoints_ListResourceUsage[post]
result = self.mgmt_client.endpoints.list_resource_usage(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
# Endpoints_PurgeContent[post]
BODY = {
"content_paths": [
"/folder1"
]
}
# CONTENT_PATHS = ["/folder1"]
result = self.mgmt_client.endpoints.begin_purge_content(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
# Endpoints_Stop[post]
result = self.mgmt_client.endpoints.begin_stop(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
# Endpoints_Start[post]
result = self.mgmt_client.endpoints.begin_start(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
# Endpoints_LoadContent[post]
BODY = {
"content_paths": [
"/folder1"
]
}
# CONTENT_PATHS = ["/folder1"]
result = self.mgmt_client.endpoints.begin_load_content(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
# Profiles_ListSupportedOptimizationTypes[post]
result = self.mgmt_client.profiles.list_supported_optimization_types(resource_group.name, PROFILE_NAME)
# Endpoints_Update[patch]
BODY = {
"tags": {
"additional_properties": "Tag1"
},
# "web_application_firewall_policy_link": {
# "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Cdn/CdnWebApplicationFirewallPolicies/" + CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME + ""
# }
}
result = self.mgmt_client.endpoints.begin_update(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
# Profiles_ListResourceUsage[post]
result = self.mgmt_client.profiles.list_resource_usage(resource_group.name, PROFILE_NAME)
# Profiles_GenerateSsoUri[post]
result = self.mgmt_client.profiles.generate_sso_uri(resource_group.name, PROFILE_NAME)
# Profiles_Update[patch]
BODY = {
"tags": {
"additional_properties": "Tag1"
}
}
result = self.mgmt_client.profiles.begin_update(resource_group.name, PROFILE_NAME, BODY)
result = result.result()
# CheckNameAvailabilityWithSubscription[post]
BODY = {
"name": "sampleName",
"type": "Microsoft.Cdn/Profiles/Endpoints"
}
# CHECK_NAME = "sampleName"
result = self.mgmt_client.check_name_availability_with_subscription(BODY)
# ResourceUsage_List[post]
result = self.mgmt_client.resource_usage.list()
# ValidateProbe[post]
BODY = {
"probe_url": "https://www.bing.com/image"
}
# PROBEURL = "https://www.bing.com/image"
result = self.mgmt_client.validate_probe(BODY)
# CheckNameAvailability[post]
BODY = {
"name": "sampleName",
"type": "Microsoft.Cdn/Profiles/Endpoints"
}
# CHECKNAME = "sampleName"
result = self.mgmt_client.check_name_availability(BODY)
# CustomDomains_Delete[delete]
result = self.mgmt_client.custom_domains.begin_delete(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME)
result = result.result()
"""
# Delete protection policy[delete]
result = self.mgmt_client.policies.delete(resource_group.name, CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME)
"""
# Endpoints_Delete[delete]
result = self.mgmt_client.endpoints.begin_delete(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
# Profiles_Delete[delete]
result = self.mgmt_client.profiles.begin_delete(resource_group.name, PROFILE_NAME)
result = result.result()
#------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
| 36.218914 | 205 | 0.499782 |
import os
import unittest
import azure.mgmt.cdn
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
AZURE_LOCATION = 'eastus'
class MgmtCdnTest(AzureMgmtTestCase):
def setUp(self):
super(MgmtCdnTest, self).setUp()
self.mgmt_client = self.create_mgmt_client(
azure.mgmt.cdn.CdnManagementClient
)
@ResourceGroupPreparer(location=AZURE_LOCATION)
def test_cdn(self, resource_group):
SUBSCRIPTION_ID = None
if self.is_live:
SUBSCRIPTION_ID = os.environ.get("AZURE_SUBSCRIPTION_ID", None)
if not SUBSCRIPTION_ID:
SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
RESOURCE_GROUP = resource_group.name
PROFILE_NAME = "profilename"
CDN_WEB_APPLICATION_FIREWALL_POLICY_NAME = "policyname"
ENDPOINT_NAME = "endpoint9527x"
CUSTOM_DOMAIN_NAME = "someDomain"
ORIGIN_NAME = "origin1"
BODY = {
"location": "WestUs",
"sku": {
"name": "Standard_Verizon"
}
}
result = self.mgmt_client.profiles.begin_create(resource_group.name, PROFILE_NAME, BODY)
result = result.result()
BODY = {
"origin_host_header": "www.bing.com",
"origin_path": "/image",
"content_types_to_compress": [
"text/html",
"application/octet-stream"
],
"is_compression_enabled": True,
"is_http_allowed": True,
"is_https_allowed": True,
"query_string_caching_behavior": "BypassCaching",
"origins": [
{
"name": "origin1",
"host_name": "host1.hello.com"
}
],
"location": "WestUs",
"tags": {
"kay1": "value1"
}
}
result = self.mgmt_client.endpoints.begin_create(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
result = self.mgmt_client.origins.get(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, ORIGIN_NAME)
result = self.mgmt_client.custom_domains.list_by_endpoint(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = self.mgmt_client.origins.list_by_endpoint(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = self.mgmt_client.endpoints.get(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = self.mgmt_client.endpoints.list_by_profile(resource_group.name, PROFILE_NAME)
result = self.mgmt_client.policies.list(resource_group.name)
result = self.mgmt_client.profiles.get(resource_group.name, PROFILE_NAME)
result = self.mgmt_client.profiles.list_by_resource_group(resource_group.name)
result = self.mgmt_client.policies.list(resource_group.name)
result = self.mgmt_client.profiles.list()
result = self.mgmt_client.operations.list()
result = self.mgmt_client.edge_nodes.list()
BODY = {
"http_port": "42",
"https_port": "43"
}
result = self.mgmt_client.origins.begin_update(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, ORIGIN_NAME, BODY)
result = result.result()
BODY = {
"host_name": "www.someDomain.com"
}
result = self.mgmt_client.endpoints.validate_custom_domain(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = self.mgmt_client.endpoints.list_resource_usage(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
BODY = {
"content_paths": [
"/folder1"
]
}
result = self.mgmt_client.endpoints.begin_purge_content(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
result = self.mgmt_client.endpoints.begin_stop(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
result = self.mgmt_client.endpoints.begin_start(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
BODY = {
"content_paths": [
"/folder1"
]
}
result = self.mgmt_client.endpoints.begin_load_content(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
result = self.mgmt_client.profiles.list_supported_optimization_types(resource_group.name, PROFILE_NAME)
BODY = {
"tags": {
"additional_properties": "Tag1"
},
}
result = self.mgmt_client.endpoints.begin_update(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, BODY)
result = result.result()
result = self.mgmt_client.profiles.list_resource_usage(resource_group.name, PROFILE_NAME)
result = self.mgmt_client.profiles.generate_sso_uri(resource_group.name, PROFILE_NAME)
BODY = {
"tags": {
"additional_properties": "Tag1"
}
}
result = self.mgmt_client.profiles.begin_update(resource_group.name, PROFILE_NAME, BODY)
result = result.result()
BODY = {
"name": "sampleName",
"type": "Microsoft.Cdn/Profiles/Endpoints"
}
result = self.mgmt_client.check_name_availability_with_subscription(BODY)
result = self.mgmt_client.resource_usage.list()
BODY = {
"probe_url": "https://www.bing.com/image"
}
result = self.mgmt_client.validate_probe(BODY)
BODY = {
"name": "sampleName",
"type": "Microsoft.Cdn/Profiles/Endpoints"
}
result = self.mgmt_client.check_name_availability(BODY)
result = self.mgmt_client.custom_domains.begin_delete(resource_group.name, PROFILE_NAME, ENDPOINT_NAME, CUSTOM_DOMAIN_NAME)
result = result.result()
result = self.mgmt_client.endpoints.begin_delete(resource_group.name, PROFILE_NAME, ENDPOINT_NAME)
result = result.result()
result = self.mgmt_client.profiles.begin_delete(resource_group.name, PROFILE_NAME)
result = result.result()
if __name__ == '__main__':
unittest.main()
| true | true |
f71ba71e6fe75b165544ce78ca9d1518a8b10f31 | 142 | py | Python | anoi/tests/test_anoitypes.py | jriehl/anoi | 1a7b1759824cd4615731e8d053a4bb04d4f3fea3 | [
"MIT"
] | null | null | null | anoi/tests/test_anoitypes.py | jriehl/anoi | 1a7b1759824cd4615731e8d053a4bb04d4f3fea3 | [
"MIT"
] | null | null | null | anoi/tests/test_anoitypes.py | jriehl/anoi | 1a7b1759824cd4615731e8d053a4bb04d4f3fea3 | [
"MIT"
] | null | null | null | import unittest
from .. import anoitypes
class TestANOITypes(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
| 11.833333 | 39 | 0.711268 | import unittest
from .. import anoitypes
class TestANOITypes(unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main()
| true | true |
f71ba7b251e9bf8b98ca35f68d542663d3b132e2 | 2,286 | py | Python | src/main/resources/de/mpg/biochem/mars/fx/dashboard/xychart.py | imagejan/mars-fx | 8e493c3c9e02aba20747598827b503c3172f949b | [
"BSD-2-Clause"
] | 3 | 2020-03-10T18:02:09.000Z | 2021-09-21T16:52:58.000Z | src/main/resources/de/mpg/biochem/mars/fx/dashboard/xychart.py | imagejan/mars-fx | 8e493c3c9e02aba20747598827b503c3172f949b | [
"BSD-2-Clause"
] | 51 | 2020-03-30T11:42:44.000Z | 2022-03-16T07:09:16.000Z | src/main/resources/de/mpg/biochem/mars/fx/dashboard/xychart.py | imagejan/mars-fx | 8e493c3c9e02aba20747598827b503c3172f949b | [
"BSD-2-Clause"
] | 2 | 2021-04-20T11:51:38.000Z | 2021-09-21T16:39:12.000Z | #@OUTPUT String xlabel
#@OUTPUT String ylabel
#@OUTPUT String title
# OUTPUT Double xmin
# OUTPUT Double xmax
# OUTPUT Double ymin
# OUTPUT Double ymax
# xmin = -2.0
# xmax = 2.0
# ymin = -2.0
# ymax = 2.0
# Set global outputs
xlabel = "X"
ylabel = "Y"
title = "XY Chart"
import math
from java.util import Random
from java.lang import Double
r = Random()
# Series 1 Outputs
#@OUTPUT Double[] series1_xvalues
#@OUTPUT Double[] series1_yvalues
#@OUTPUT Double[] series1_error
#@OUTPUT String series1_fillColor
#@OUTPUT String series1_strokeColor
#@OUTPUT Integer series1_strokeWidth
series1_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series1_fillColor = series1_strokeColor
series1_strokeWidth = 1
series1_xvalues = []
series1_yvalues = []
series1_error = []
currentY = 0
for i in range(29):
series1_xvalues.append(i)
series1_yvalues.append(currentY)
currentY += r.nextGaussian()
series1_error.append(abs(r.nextGaussian()))
r = Random()
# Series 2 Outputs
#@OUTPUT Double[] series2_xvalues
#@OUTPUT Double[] series2_yvalues
#@OUTPUT Double[] series2_error
#@OUTPUT String series2_fillColor
#@OUTPUT String series2_strokeColor
#@OUTPUT Integer series2_strokeWidth
series2_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series2_fillColor = series1_strokeColor
series2_strokeWidth = 1
series2_xvalues = []
series2_yvalues = []
series2_error = []
currentY = 0
for i in range(29):
series2_xvalues.append(i)
series2_yvalues.append(currentY)
currentY += r.nextGaussian()
series2_error.append(abs(r.nextGaussian()))
# Series 3 Outputs
#@OUTPUT Double[] series3_xvalues
#@OUTPUT Double[] series3_yvalues
#@OUTPUT Double[] series3_error
#@OUTPUT String series3_fillColor
#@OUTPUT String series3_strokeColor
#@OUTPUT Integer series3_strokeWidth
series3_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series3_fillColor = series1_strokeColor
series3_strokeWidth = 1
series3_xvalues = []
series3_yvalues = []
series3_error = []
currentY = 0
for i in range(29):
series3_xvalues.append(i)
series3_yvalues.append(currentY)
currentY += r.nextGaussian()
series3_error.append(abs(r.nextGaussian())) | 24.319149 | 112 | 0.737533 |
xlabel = "X"
ylabel = "Y"
title = "XY Chart"
import math
from java.util import Random
from java.lang import Double
r = Random()
series1_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series1_fillColor = series1_strokeColor
series1_strokeWidth = 1
series1_xvalues = []
series1_yvalues = []
series1_error = []
currentY = 0
for i in range(29):
series1_xvalues.append(i)
series1_yvalues.append(currentY)
currentY += r.nextGaussian()
series1_error.append(abs(r.nextGaussian()))
r = Random()
series2_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series2_fillColor = series1_strokeColor
series2_strokeWidth = 1
series2_xvalues = []
series2_yvalues = []
series2_error = []
currentY = 0
for i in range(29):
series2_xvalues.append(i)
series2_yvalues.append(currentY)
currentY += r.nextGaussian()
series2_error.append(abs(r.nextGaussian()))
series3_strokeColor = "rgb(" + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + "," + str(r.nextInt(255)) + ")"
series3_fillColor = series1_strokeColor
series3_strokeWidth = 1
series3_xvalues = []
series3_yvalues = []
series3_error = []
currentY = 0
for i in range(29):
series3_xvalues.append(i)
series3_yvalues.append(currentY)
currentY += r.nextGaussian()
series3_error.append(abs(r.nextGaussian())) | true | true |
f71ba974fcdaec851af4d51a7fedeed1954c2992 | 418 | py | Python | homework/第 2 课/Aimee/1-Aimee.py | xrandx/-Dating-with-python-this-winter | d242faeda1598d50c3b371deeccfbbe3bbc8fb51 | [
"Apache-2.0"
] | 3 | 2021-01-03T10:10:25.000Z | 2021-01-11T06:13:40.000Z | homework/第 2 课/Aimee/1-Aimee.py | xrandx/-Dating-with-python-this-winter | d242faeda1598d50c3b371deeccfbbe3bbc8fb51 | [
"Apache-2.0"
] | null | null | null | homework/第 2 课/Aimee/1-Aimee.py | xrandx/-Dating-with-python-this-winter | d242faeda1598d50c3b371deeccfbbe3bbc8fb51 | [
"Apache-2.0"
] | 2 | 2021-01-08T10:12:17.000Z | 2021-01-19T02:03:32.000Z | array=[2,5,8,9,3,6]
a=[1,3,6]
matrix=[a,[2,5,7]]
array.append(1)
print(matrix)
print(array)
new_list=array+matrix
print(new_list)
new_list.pop(-3)
print(new_list)
new_list[0]="T"
print(new_list)
# new_list.clear()
# print(new_list)
print(new_list.index(5))
table=tuple(["Monday","Tuesday"])
print(table[1])
string="123456789"
print(string[1:-3])
f=open("test.txt", "w", encoding="utf-8")
f.write(string*10)
f.close()
| 17.416667 | 41 | 0.69378 | array=[2,5,8,9,3,6]
a=[1,3,6]
matrix=[a,[2,5,7]]
array.append(1)
print(matrix)
print(array)
new_list=array+matrix
print(new_list)
new_list.pop(-3)
print(new_list)
new_list[0]="T"
print(new_list)
print(new_list.index(5))
table=tuple(["Monday","Tuesday"])
print(table[1])
string="123456789"
print(string[1:-3])
f=open("test.txt", "w", encoding="utf-8")
f.write(string*10)
f.close()
| true | true |
f71ba98a374e556c7c9d0359e89bdb1f986ca8f0 | 43,300 | py | Python | bin/api_connector_splunk/solnlib/packages/simpleyaml/emitter.py | CyberGRX/api-connector-splunk | 7f1db1cecb7ae367c1882c3188dc9f8bcb6bc4c6 | [
"MIT"
] | 106 | 2018-03-09T13:03:05.000Z | 2022-03-10T11:01:48.000Z | bin/api_connector_splunk/solnlib/packages/simpleyaml/emitter.py | CyberGRX/api-connector-splunk | 7f1db1cecb7ae367c1882c3188dc9f8bcb6bc4c6 | [
"MIT"
] | 54 | 2016-08-11T14:22:30.000Z | 2020-08-07T22:14:55.000Z | bin/api_connector_splunk/solnlib/packages/simpleyaml/emitter.py | CyberGRX/api-connector-splunk | 7f1db1cecb7ae367c1882c3188dc9f8bcb6bc4c6 | [
"MIT"
] | 33 | 2018-04-23T20:18:11.000Z | 2022-03-27T16:41:03.000Z |
# Emitter expects events obeying the following grammar:
# stream ::= STREAM-START document* STREAM-END
# document ::= DOCUMENT-START node DOCUMENT-END
# node ::= SCALAR | sequence | mapping
# sequence ::= SEQUENCE-START node* SEQUENCE-END
# mapping ::= MAPPING-START (node node)* MAPPING-END
__all__ = ['Emitter', 'EmitterError']
from .error import YAMLError
from .events import *
class EmitterError(YAMLError):
pass
class ScalarAnalysis(object):
def __init__(self, scalar, empty, multiline,
allow_flow_plain, allow_block_plain,
allow_single_quoted, allow_double_quoted,
allow_block):
self.scalar = scalar
self.empty = empty
self.multiline = multiline
self.allow_flow_plain = allow_flow_plain
self.allow_block_plain = allow_block_plain
self.allow_single_quoted = allow_single_quoted
self.allow_double_quoted = allow_double_quoted
self.allow_block = allow_block
class Emitter(object):
DEFAULT_TAG_PREFIXES = {
u'!' : u'!',
u'tag:yaml.org,2002:' : u'!!',
}
def __init__(self, stream, canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
# The stream should have the methods `write` and possibly `flush`.
self.stream = stream
# Encoding can be overriden by STREAM-START.
self.encoding = None
# Emitter is a state machine with a stack of states to handle nested
# structures.
self.states = []
self.state = self.expect_stream_start
# Current event and the event queue.
self.events = []
self.event = None
# The current indentation level and the stack of previous indents.
self.indents = []
self.indent = None
# Flow level.
self.flow_level = 0
# Contexts.
self.root_context = False
self.sequence_context = False
self.mapping_context = False
self.simple_key_context = False
# Characteristics of the last emitted character:
# - current position.
# - is it a whitespace?
# - is it an indention character
# (indentation space, '-', '?', or ':')?
self.line = 0
self.column = 0
self.whitespace = True
self.indention = True
# Whether the document requires an explicit document indicator
self.open_ended = False
# Formatting details.
self.canonical = canonical
self.allow_unicode = allow_unicode
self.best_indent = 2
if indent and 1 < indent < 10:
self.best_indent = indent
self.best_width = 80
if width and width > self.best_indent*2:
self.best_width = width
self.best_line_break = u'\n'
if line_break in [u'\r', u'\n', u'\r\n']:
self.best_line_break = line_break
# Tag prefixes.
self.tag_prefixes = None
# Prepared anchor and tag.
self.prepared_anchor = None
self.prepared_tag = None
# Scalar analysis and style.
self.analysis = None
self.style = None
def dispose(self):
# Reset the state attributes (to clear self-references)
self.states = []
self.state = None
def emit(self, event):
self.events.append(event)
while not self.need_more_events():
self.event = self.events.pop(0)
self.state()
self.event = None
# In some cases, we wait for a few next events before emitting.
def need_more_events(self):
if not self.events:
return True
event = self.events[0]
if isinstance(event, DocumentStartEvent):
return self.need_events(1)
elif isinstance(event, SequenceStartEvent):
return self.need_events(2)
elif isinstance(event, MappingStartEvent):
return self.need_events(3)
else:
return False
def need_events(self, count):
level = 0
for event in self.events[1:]:
if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
level += 1
elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
level -= 1
elif isinstance(event, StreamEndEvent):
level = -1
if level < 0:
return False
return (len(self.events) < count+1)
def increase_indent(self, flow=False, indentless=False):
self.indents.append(self.indent)
if self.indent is None:
if flow:
self.indent = self.best_indent
else:
self.indent = 0
elif not indentless:
self.indent += self.best_indent
# States.
# Stream handlers.
def expect_stream_start(self):
if isinstance(self.event, StreamStartEvent):
if self.event.encoding and not getattr(self.stream, 'encoding', None):
self.encoding = self.event.encoding
self.write_stream_start()
self.state = self.expect_first_document_start
else:
raise EmitterError("expected StreamStartEvent, but got %s"
% self.event)
def expect_nothing(self):
raise EmitterError("expected nothing, but got %s" % self.event)
# Document handlers.
def expect_first_document_start(self):
return self.expect_document_start(first=True)
def expect_document_start(self, first=False):
if isinstance(self.event, DocumentStartEvent):
if (self.event.version or self.event.tags) and self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
if self.event.version:
version_text = self.prepare_version(self.event.version)
self.write_version_directive(version_text)
self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
if self.event.tags:
handles = self.event.tags.keys()
handles.sort()
for handle in handles:
prefix = self.event.tags[handle]
self.tag_prefixes[prefix] = handle
handle_text = self.prepare_tag_handle(handle)
prefix_text = self.prepare_tag_prefix(prefix)
self.write_tag_directive(handle_text, prefix_text)
implicit = (first and not self.event.explicit and not self.canonical
and not self.event.version and not self.event.tags
and not self.check_empty_document())
if not implicit:
self.write_indent()
self.write_indicator(u'---', True)
if self.canonical:
self.write_indent()
self.state = self.expect_document_root
elif isinstance(self.event, StreamEndEvent):
if self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
self.write_stream_end()
self.state = self.expect_nothing
else:
raise EmitterError("expected DocumentStartEvent, but got %s"
% self.event)
def expect_document_end(self):
if isinstance(self.event, DocumentEndEvent):
self.write_indent()
if self.event.explicit:
self.write_indicator(u'...', True)
self.write_indent()
self.flush_stream()
self.state = self.expect_document_start
else:
raise EmitterError("expected DocumentEndEvent, but got %s"
% self.event)
def expect_document_root(self):
self.states.append(self.expect_document_end)
self.expect_node(root=True)
# Node handlers.
def expect_node(self, root=False, sequence=False, mapping=False,
simple_key=False):
self.root_context = root
self.sequence_context = sequence
self.mapping_context = mapping
self.simple_key_context = simple_key
if isinstance(self.event, AliasEvent):
self.expect_alias()
elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
self.process_anchor(u'&')
self.process_tag()
if isinstance(self.event, ScalarEvent):
self.expect_scalar()
elif isinstance(self.event, SequenceStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_sequence():
self.expect_flow_sequence()
else:
self.expect_block_sequence()
elif isinstance(self.event, MappingStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_mapping():
self.expect_flow_mapping()
else:
self.expect_block_mapping()
else:
raise EmitterError("expected NodeEvent, but got %s" % self.event)
def expect_alias(self):
if self.event.anchor is None:
raise EmitterError("anchor is not specified for alias")
self.process_anchor(u'*')
self.state = self.states.pop()
def expect_scalar(self):
self.increase_indent(flow=True)
self.process_scalar()
self.indent = self.indents.pop()
self.state = self.states.pop()
# Flow sequence handlers.
def expect_flow_sequence(self):
self.write_indicator(u'[', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_sequence_item
def expect_first_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
def expect_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
# Flow mapping handlers.
def expect_flow_mapping(self):
self.write_indicator(u'{', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_mapping_key
def expect_first_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
def expect_flow_mapping_value(self):
if self.canonical or self.column > self.best_width:
self.write_indent()
self.write_indicator(u':', True)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
# Block sequence handlers.
def expect_block_sequence(self):
indentless = (self.mapping_context and not self.indention)
self.increase_indent(flow=False, indentless=indentless)
self.state = self.expect_first_block_sequence_item
def expect_first_block_sequence_item(self):
return self.expect_block_sequence_item(first=True)
def expect_block_sequence_item(self, first=False):
if not first and isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
self.write_indicator(u'-', True, indention=True)
self.states.append(self.expect_block_sequence_item)
self.expect_node(sequence=True)
# Block mapping handlers.
def expect_block_mapping(self):
self.increase_indent(flow=False)
self.state = self.expect_first_block_mapping_key
def expect_first_block_mapping_key(self):
return self.expect_block_mapping_key(first=True)
def expect_block_mapping_key(self, first=False):
if not first and isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
if self.check_simple_key():
self.states.append(self.expect_block_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True, indention=True)
self.states.append(self.expect_block_mapping_value)
self.expect_node(mapping=True)
def expect_block_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
def expect_block_mapping_value(self):
self.write_indent()
self.write_indicator(u':', True, indention=True)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
# Checkers.
def check_empty_sequence(self):
return (isinstance(self.event, SequenceStartEvent) and self.events
and isinstance(self.events[0], SequenceEndEvent))
def check_empty_mapping(self):
return (isinstance(self.event, MappingStartEvent) and self.events
and isinstance(self.events[0], MappingEndEvent))
def check_empty_document(self):
if not isinstance(self.event, DocumentStartEvent) or not self.events:
return False
event = self.events[0]
return (isinstance(event, ScalarEvent) and event.anchor is None
and event.tag is None and event.implicit and event.value == u'')
def check_simple_key(self):
length = 0
if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
length += len(self.prepared_anchor)
if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
and self.event.tag is not None:
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(self.event.tag)
length += len(self.prepared_tag)
if isinstance(self.event, ScalarEvent):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
length += len(self.analysis.scalar)
return (length < 128 and (isinstance(self.event, AliasEvent)
or (isinstance(self.event, ScalarEvent)
and not self.analysis.empty and not self.analysis.multiline)
or self.check_empty_sequence() or self.check_empty_mapping()))
# Anchor, Tag, and Scalar processors.
def process_anchor(self, indicator):
if self.event.anchor is None:
self.prepared_anchor = None
return
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
if self.prepared_anchor:
self.write_indicator(indicator+self.prepared_anchor, True)
self.prepared_anchor = None
def process_tag(self):
tag = self.event.tag
if isinstance(self.event, ScalarEvent):
if self.style is None:
self.style = self.choose_scalar_style()
if ((not self.canonical or tag is None) and
((self.style == '' and self.event.implicit[0])
or (self.style != '' and self.event.implicit[1]))):
self.prepared_tag = None
return
if self.event.implicit[0] and tag is None:
tag = u'!'
self.prepared_tag = None
else:
if (not self.canonical or tag is None) and self.event.implicit:
self.prepared_tag = None
return
if tag is None:
raise EmitterError("tag is not specified")
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(tag)
if self.prepared_tag:
self.write_indicator(self.prepared_tag, True)
self.prepared_tag = None
def choose_scalar_style(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.event.style == '"' or self.canonical:
return '"'
if not self.event.style and self.event.implicit[0]:
if (not (self.simple_key_context and
(self.analysis.empty or self.analysis.multiline))
and (self.flow_level and self.analysis.allow_flow_plain
or (not self.flow_level and self.analysis.allow_block_plain))):
return ''
if self.event.style and self.event.style in '|>':
if (not self.flow_level and not self.simple_key_context
and self.analysis.allow_block):
return self.event.style
if not self.event.style or self.event.style == '\'':
if (self.analysis.allow_single_quoted and
not (self.simple_key_context and self.analysis.multiline)):
return '\''
return '"'
def process_scalar(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.style is None:
self.style = self.choose_scalar_style()
split = (not self.simple_key_context)
#if self.analysis.multiline and split \
# and (not self.style or self.style in '\'\"'):
# self.write_indent()
if self.style == '"':
self.write_double_quoted(self.analysis.scalar, split)
elif self.style == '\'':
self.write_single_quoted(self.analysis.scalar, split)
elif self.style == '>':
self.write_folded(self.analysis.scalar)
elif self.style == '|':
self.write_literal(self.analysis.scalar)
else:
self.write_plain(self.analysis.scalar, split)
self.analysis = None
self.style = None
# Analyzers.
def prepare_version(self, version):
major, minor = version
if major != 1:
raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
return u'%d.%d' % (major, minor)
def prepare_tag_handle(self, handle):
if not handle:
raise EmitterError("tag handle must not be empty")
if handle[0] != u'!' or handle[-1] != u'!':
raise EmitterError("tag handle must start and end with '!': %r"
% (handle.encode('utf-8')))
for ch in handle[1:-1]:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the tag handle: %r"
% (ch.encode('utf-8'), handle.encode('utf-8')))
return handle
def prepare_tag_prefix(self, prefix):
if not prefix:
raise EmitterError("tag prefix must not be empty")
chunks = []
start = end = 0
if prefix[0] == u'!':
end = 1
while end < len(prefix):
ch = prefix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?!:@&=+$,_.~*\'()[]':
end += 1
else:
if start < end:
chunks.append(prefix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(prefix[start:end])
return u''.join(chunks)
def prepare_tag(self, tag):
if not tag:
raise EmitterError("tag must not be empty")
if tag == u'!':
return tag
handle = None
suffix = tag
prefixes = self.tag_prefixes.keys()
prefixes.sort()
for prefix in prefixes:
if tag.startswith(prefix) \
and (prefix == u'!' or len(prefix) < len(tag)):
handle = self.tag_prefixes[prefix]
suffix = tag[len(prefix):]
chunks = []
start = end = 0
while end < len(suffix):
ch = suffix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?:@&=+$,_.~*\'()[]' \
or (ch == u'!' and handle != u'!'):
end += 1
else:
if start < end:
chunks.append(suffix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(suffix[start:end])
suffix_text = u''.join(chunks)
if handle:
return u'%s%s' % (handle, suffix_text)
else:
return u'!<%s>' % suffix_text
def prepare_anchor(self, anchor):
if not anchor:
raise EmitterError("anchor must not be empty")
for ch in anchor:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the anchor: %r"
% (ch.encode('utf-8'), anchor.encode('utf-8')))
return anchor
def analyze_scalar(self, scalar):
# Empty scalar is a special case.
if not scalar:
return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
allow_flow_plain=False, allow_block_plain=True,
allow_single_quoted=True, allow_double_quoted=True,
allow_block=False)
# Indicators and special characters.
block_indicators = False
flow_indicators = False
line_breaks = False
special_characters = False
# Important whitespace combinations.
leading_space = False
leading_break = False
trailing_space = False
trailing_break = False
break_space = False
space_break = False
# Check document indicators.
if scalar.startswith(u'---') or scalar.startswith(u'...'):
block_indicators = True
flow_indicators = True
# First character or preceded by a whitespace.
preceeded_by_whitespace = True
# Last character or followed by a whitespace.
followed_by_whitespace = (len(scalar) == 1 or
scalar[1] in u'\0 \t\r\n\x85\u2028\u2029')
# The previous character is a space.
previous_space = False
# The previous character is a break.
previous_break = False
index = 0
while index < len(scalar):
ch = scalar[index]
# Check for indicators.
if index == 0:
# Leading indicators are special characters.
if ch in u'#,[]{}&*!|>\'\"%@`':
flow_indicators = True
block_indicators = True
if ch in u'?:':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'-' and followed_by_whitespace:
flow_indicators = True
block_indicators = True
else:
# Some indicators cannot appear within a scalar as well.
if ch in u',?[]{}':
flow_indicators = True
if ch == u':':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'#' and preceeded_by_whitespace:
flow_indicators = True
block_indicators = True
# Check for line breaks, special, and unicode characters.
if ch in u'\n\x85\u2028\u2029':
line_breaks = True
if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'):
if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF':
unicode_characters = True
if not self.allow_unicode:
special_characters = True
else:
special_characters = True
# Detect important whitespace combinations.
if ch == u' ':
if index == 0:
leading_space = True
if index == len(scalar)-1:
trailing_space = True
if previous_break:
break_space = True
previous_space = True
previous_break = False
elif ch in u'\n\x85\u2028\u2029':
if index == 0:
leading_break = True
if index == len(scalar)-1:
trailing_break = True
if previous_space:
space_break = True
previous_space = False
previous_break = True
else:
previous_space = False
previous_break = False
# Prepare for the next character.
index += 1
preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029')
followed_by_whitespace = (index+1 >= len(scalar) or
scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029')
# Let's decide what styles are allowed.
allow_flow_plain = True
allow_block_plain = True
allow_single_quoted = True
allow_double_quoted = True
allow_block = True
# Leading and trailing whitespaces are bad for plain scalars.
if (leading_space or leading_break
or trailing_space or trailing_break):
allow_flow_plain = allow_block_plain = False
# We do not permit trailing spaces for block scalars.
if trailing_space:
allow_block = False
# Spaces at the beginning of a new line are only acceptable for block
# scalars.
if break_space:
allow_flow_plain = allow_block_plain = allow_single_quoted = False
# Spaces followed by breaks, as well as special character are only
# allowed for double quoted scalars.
if space_break or special_characters:
allow_flow_plain = allow_block_plain = \
allow_single_quoted = allow_block = False
# Although the plain scalar writer supports breaks, we never emit
# multiline plain scalars.
if line_breaks:
allow_flow_plain = allow_block_plain = False
# Flow indicators are forbidden for flow plain scalars.
if flow_indicators:
allow_flow_plain = False
# Block indicators are forbidden for block plain scalars.
if block_indicators:
allow_block_plain = False
return ScalarAnalysis(scalar=scalar,
empty=False, multiline=line_breaks,
allow_flow_plain=allow_flow_plain,
allow_block_plain=allow_block_plain,
allow_single_quoted=allow_single_quoted,
allow_double_quoted=allow_double_quoted,
allow_block=allow_block)
# Writers.
def flush_stream(self):
if hasattr(self.stream, 'flush'):
self.stream.flush()
def write_stream_start(self):
# Write BOM if needed.
if self.encoding and self.encoding.startswith('utf-16'):
self.stream.write(u'\uFEFF'.encode(self.encoding))
def write_stream_end(self):
self.flush_stream()
def write_indicator(self, indicator, need_whitespace,
whitespace=False, indention=False):
if self.whitespace or not need_whitespace:
data = indicator
else:
data = u' '+indicator
self.whitespace = whitespace
self.indention = self.indention and indention
self.column += len(data)
self.open_ended = False
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_indent(self):
indent = self.indent or 0
if not self.indention or self.column > indent \
or (self.column == indent and not self.whitespace):
self.write_line_break()
if self.column < indent:
self.whitespace = True
data = u' '*(indent-self.column)
self.column = indent
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_line_break(self, data=None):
if data is None:
data = self.best_line_break
self.whitespace = True
self.indention = True
self.line += 1
self.column = 0
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_version_directive(self, version_text):
data = u'%%YAML %s' % version_text
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
def write_tag_directive(self, handle_text, prefix_text):
data = u'%%TAG %s %s' % (handle_text, prefix_text)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
# Scalar streams.
def write_single_quoted(self, text, split=True):
self.write_indicator(u'\'', True)
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch is None or ch != u' ':
if start+1 == end and self.column > self.best_width and split \
and start != 0 and end != len(text):
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'':
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch == u'\'':
data = u'\'\''
self.column += 2
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end + 1
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
self.write_indicator(u'\'', False)
ESCAPE_REPLACEMENTS = {
u'\0': u'0',
u'\x07': u'a',
u'\x08': u'b',
u'\x09': u't',
u'\x0A': u'n',
u'\x0B': u'v',
u'\x0C': u'f',
u'\x0D': u'r',
u'\x1B': u'e',
u'\"': u'\"',
u'\\': u'\\',
u'\x85': u'N',
u'\xA0': u'_',
u'\u2028': u'L',
u'\u2029': u'P',
}
def write_double_quoted(self, text, split=True):
self.write_indicator(u'"', True)
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \
or not (u'\x20' <= ch <= u'\x7E'
or (self.allow_unicode
and (u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD'))):
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
if ch in self.ESCAPE_REPLACEMENTS:
data = u'\\'+self.ESCAPE_REPLACEMENTS[ch]
elif ch <= u'\xFF':
data = u'\\x%02X' % ord(ch)
elif ch <= u'\uFFFF':
data = u'\\u%04X' % ord(ch)
else:
data = u'\\U%08X' % ord(ch)
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end+1
if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \
and self.column+(end-start) > self.best_width and split:
data = text[start:end]+u'\\'
if start < end:
start = end
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_indent()
self.whitespace = False
self.indention = False
if text[start] == u' ':
data = u'\\'
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
end += 1
self.write_indicator(u'"', False)
def determine_block_hints(self, text):
hints = u''
if text:
if text[0] in u' \n\x85\u2028\u2029':
hints += unicode(self.best_indent)
if text[-1] not in u'\n\x85\u2028\u2029':
hints += u'-'
elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029':
hints += u'+'
return hints
def write_folded(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'>'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
leading_space = True
spaces = False
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if not leading_space and ch is not None and ch != u' ' \
and text[start] == u'\n':
self.write_line_break()
leading_space = (ch == u' ')
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
elif spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width:
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
spaces = (ch == u' ')
end += 1
def write_literal(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'|'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
else:
if ch is None or ch in u'\n\x85\u2028\u2029':
data = text[start:end]
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
def write_plain(self, text, split=True):
if self.root_context:
self.open_ended = True
if not text:
return
if not self.whitespace:
data = u' '
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.whitespace = False
self.indention = False
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width and split:
self.write_indent()
self.whitespace = False
self.indention = False
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
self.whitespace = False
self.indention = False
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
| 37.949167 | 85 | 0.527737 |
__all__ = ['Emitter', 'EmitterError']
from .error import YAMLError
from .events import *
class EmitterError(YAMLError):
pass
class ScalarAnalysis(object):
def __init__(self, scalar, empty, multiline,
allow_flow_plain, allow_block_plain,
allow_single_quoted, allow_double_quoted,
allow_block):
self.scalar = scalar
self.empty = empty
self.multiline = multiline
self.allow_flow_plain = allow_flow_plain
self.allow_block_plain = allow_block_plain
self.allow_single_quoted = allow_single_quoted
self.allow_double_quoted = allow_double_quoted
self.allow_block = allow_block
class Emitter(object):
DEFAULT_TAG_PREFIXES = {
u'!' : u'!',
u'tag:yaml.org,2002:' : u'!!',
}
def __init__(self, stream, canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
self.stream = stream
self.encoding = None
self.states = []
self.state = self.expect_stream_start
self.events = []
self.event = None
self.indents = []
self.indent = None
self.flow_level = 0
self.root_context = False
self.sequence_context = False
self.mapping_context = False
self.simple_key_context = False
self.line = 0
self.column = 0
self.whitespace = True
self.indention = True
self.open_ended = False
self.canonical = canonical
self.allow_unicode = allow_unicode
self.best_indent = 2
if indent and 1 < indent < 10:
self.best_indent = indent
self.best_width = 80
if width and width > self.best_indent*2:
self.best_width = width
self.best_line_break = u'\n'
if line_break in [u'\r', u'\n', u'\r\n']:
self.best_line_break = line_break
self.tag_prefixes = None
self.prepared_anchor = None
self.prepared_tag = None
self.analysis = None
self.style = None
def dispose(self):
self.states = []
self.state = None
def emit(self, event):
self.events.append(event)
while not self.need_more_events():
self.event = self.events.pop(0)
self.state()
self.event = None
def need_more_events(self):
if not self.events:
return True
event = self.events[0]
if isinstance(event, DocumentStartEvent):
return self.need_events(1)
elif isinstance(event, SequenceStartEvent):
return self.need_events(2)
elif isinstance(event, MappingStartEvent):
return self.need_events(3)
else:
return False
def need_events(self, count):
level = 0
for event in self.events[1:]:
if isinstance(event, (DocumentStartEvent, CollectionStartEvent)):
level += 1
elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)):
level -= 1
elif isinstance(event, StreamEndEvent):
level = -1
if level < 0:
return False
return (len(self.events) < count+1)
def increase_indent(self, flow=False, indentless=False):
self.indents.append(self.indent)
if self.indent is None:
if flow:
self.indent = self.best_indent
else:
self.indent = 0
elif not indentless:
self.indent += self.best_indent
def expect_stream_start(self):
if isinstance(self.event, StreamStartEvent):
if self.event.encoding and not getattr(self.stream, 'encoding', None):
self.encoding = self.event.encoding
self.write_stream_start()
self.state = self.expect_first_document_start
else:
raise EmitterError("expected StreamStartEvent, but got %s"
% self.event)
def expect_nothing(self):
raise EmitterError("expected nothing, but got %s" % self.event)
def expect_first_document_start(self):
return self.expect_document_start(first=True)
def expect_document_start(self, first=False):
if isinstance(self.event, DocumentStartEvent):
if (self.event.version or self.event.tags) and self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
if self.event.version:
version_text = self.prepare_version(self.event.version)
self.write_version_directive(version_text)
self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy()
if self.event.tags:
handles = self.event.tags.keys()
handles.sort()
for handle in handles:
prefix = self.event.tags[handle]
self.tag_prefixes[prefix] = handle
handle_text = self.prepare_tag_handle(handle)
prefix_text = self.prepare_tag_prefix(prefix)
self.write_tag_directive(handle_text, prefix_text)
implicit = (first and not self.event.explicit and not self.canonical
and not self.event.version and not self.event.tags
and not self.check_empty_document())
if not implicit:
self.write_indent()
self.write_indicator(u'---', True)
if self.canonical:
self.write_indent()
self.state = self.expect_document_root
elif isinstance(self.event, StreamEndEvent):
if self.open_ended:
self.write_indicator(u'...', True)
self.write_indent()
self.write_stream_end()
self.state = self.expect_nothing
else:
raise EmitterError("expected DocumentStartEvent, but got %s"
% self.event)
def expect_document_end(self):
if isinstance(self.event, DocumentEndEvent):
self.write_indent()
if self.event.explicit:
self.write_indicator(u'...', True)
self.write_indent()
self.flush_stream()
self.state = self.expect_document_start
else:
raise EmitterError("expected DocumentEndEvent, but got %s"
% self.event)
def expect_document_root(self):
self.states.append(self.expect_document_end)
self.expect_node(root=True)
def expect_node(self, root=False, sequence=False, mapping=False,
simple_key=False):
self.root_context = root
self.sequence_context = sequence
self.mapping_context = mapping
self.simple_key_context = simple_key
if isinstance(self.event, AliasEvent):
self.expect_alias()
elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)):
self.process_anchor(u'&')
self.process_tag()
if isinstance(self.event, ScalarEvent):
self.expect_scalar()
elif isinstance(self.event, SequenceStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_sequence():
self.expect_flow_sequence()
else:
self.expect_block_sequence()
elif isinstance(self.event, MappingStartEvent):
if self.flow_level or self.canonical or self.event.flow_style \
or self.check_empty_mapping():
self.expect_flow_mapping()
else:
self.expect_block_mapping()
else:
raise EmitterError("expected NodeEvent, but got %s" % self.event)
def expect_alias(self):
if self.event.anchor is None:
raise EmitterError("anchor is not specified for alias")
self.process_anchor(u'*')
self.state = self.states.pop()
def expect_scalar(self):
self.increase_indent(flow=True)
self.process_scalar()
self.indent = self.indents.pop()
self.state = self.states.pop()
def expect_flow_sequence(self):
self.write_indicator(u'[', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_sequence_item
def expect_first_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
def expect_flow_sequence_item(self):
if isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u']', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
self.states.append(self.expect_flow_sequence_item)
self.expect_node(sequence=True)
def expect_flow_mapping(self):
self.write_indicator(u'{', True, whitespace=True)
self.flow_level += 1
self.increase_indent(flow=True)
self.state = self.expect_first_flow_mapping_key
def expect_first_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_key(self):
if isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.flow_level -= 1
if self.canonical:
self.write_indicator(u',', False)
self.write_indent()
self.write_indicator(u'}', False)
self.state = self.states.pop()
else:
self.write_indicator(u',', False)
if self.canonical or self.column > self.best_width:
self.write_indent()
if not self.canonical and self.check_simple_key():
self.states.append(self.expect_flow_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True)
self.states.append(self.expect_flow_mapping_value)
self.expect_node(mapping=True)
def expect_flow_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
def expect_flow_mapping_value(self):
if self.canonical or self.column > self.best_width:
self.write_indent()
self.write_indicator(u':', True)
self.states.append(self.expect_flow_mapping_key)
self.expect_node(mapping=True)
def expect_block_sequence(self):
indentless = (self.mapping_context and not self.indention)
self.increase_indent(flow=False, indentless=indentless)
self.state = self.expect_first_block_sequence_item
def expect_first_block_sequence_item(self):
return self.expect_block_sequence_item(first=True)
def expect_block_sequence_item(self, first=False):
if not first and isinstance(self.event, SequenceEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
self.write_indicator(u'-', True, indention=True)
self.states.append(self.expect_block_sequence_item)
self.expect_node(sequence=True)
def expect_block_mapping(self):
self.increase_indent(flow=False)
self.state = self.expect_first_block_mapping_key
def expect_first_block_mapping_key(self):
return self.expect_block_mapping_key(first=True)
def expect_block_mapping_key(self, first=False):
if not first and isinstance(self.event, MappingEndEvent):
self.indent = self.indents.pop()
self.state = self.states.pop()
else:
self.write_indent()
if self.check_simple_key():
self.states.append(self.expect_block_mapping_simple_value)
self.expect_node(mapping=True, simple_key=True)
else:
self.write_indicator(u'?', True, indention=True)
self.states.append(self.expect_block_mapping_value)
self.expect_node(mapping=True)
def expect_block_mapping_simple_value(self):
self.write_indicator(u':', False)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
def expect_block_mapping_value(self):
self.write_indent()
self.write_indicator(u':', True, indention=True)
self.states.append(self.expect_block_mapping_key)
self.expect_node(mapping=True)
def check_empty_sequence(self):
return (isinstance(self.event, SequenceStartEvent) and self.events
and isinstance(self.events[0], SequenceEndEvent))
def check_empty_mapping(self):
return (isinstance(self.event, MappingStartEvent) and self.events
and isinstance(self.events[0], MappingEndEvent))
def check_empty_document(self):
if not isinstance(self.event, DocumentStartEvent) or not self.events:
return False
event = self.events[0]
return (isinstance(event, ScalarEvent) and event.anchor is None
and event.tag is None and event.implicit and event.value == u'')
def check_simple_key(self):
length = 0
if isinstance(self.event, NodeEvent) and self.event.anchor is not None:
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
length += len(self.prepared_anchor)
if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \
and self.event.tag is not None:
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(self.event.tag)
length += len(self.prepared_tag)
if isinstance(self.event, ScalarEvent):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
length += len(self.analysis.scalar)
return (length < 128 and (isinstance(self.event, AliasEvent)
or (isinstance(self.event, ScalarEvent)
and not self.analysis.empty and not self.analysis.multiline)
or self.check_empty_sequence() or self.check_empty_mapping()))
def process_anchor(self, indicator):
if self.event.anchor is None:
self.prepared_anchor = None
return
if self.prepared_anchor is None:
self.prepared_anchor = self.prepare_anchor(self.event.anchor)
if self.prepared_anchor:
self.write_indicator(indicator+self.prepared_anchor, True)
self.prepared_anchor = None
def process_tag(self):
tag = self.event.tag
if isinstance(self.event, ScalarEvent):
if self.style is None:
self.style = self.choose_scalar_style()
if ((not self.canonical or tag is None) and
((self.style == '' and self.event.implicit[0])
or (self.style != '' and self.event.implicit[1]))):
self.prepared_tag = None
return
if self.event.implicit[0] and tag is None:
tag = u'!'
self.prepared_tag = None
else:
if (not self.canonical or tag is None) and self.event.implicit:
self.prepared_tag = None
return
if tag is None:
raise EmitterError("tag is not specified")
if self.prepared_tag is None:
self.prepared_tag = self.prepare_tag(tag)
if self.prepared_tag:
self.write_indicator(self.prepared_tag, True)
self.prepared_tag = None
def choose_scalar_style(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.event.style == '"' or self.canonical:
return '"'
if not self.event.style and self.event.implicit[0]:
if (not (self.simple_key_context and
(self.analysis.empty or self.analysis.multiline))
and (self.flow_level and self.analysis.allow_flow_plain
or (not self.flow_level and self.analysis.allow_block_plain))):
return ''
if self.event.style and self.event.style in '|>':
if (not self.flow_level and not self.simple_key_context
and self.analysis.allow_block):
return self.event.style
if not self.event.style or self.event.style == '\'':
if (self.analysis.allow_single_quoted and
not (self.simple_key_context and self.analysis.multiline)):
return '\''
return '"'
def process_scalar(self):
if self.analysis is None:
self.analysis = self.analyze_scalar(self.event.value)
if self.style is None:
self.style = self.choose_scalar_style()
split = (not self.simple_key_context)
#if self.analysis.multiline and split \
# and (not self.style or self.style in '\'\"'):
# self.write_indent()
if self.style == '"':
self.write_double_quoted(self.analysis.scalar, split)
elif self.style == '\'':
self.write_single_quoted(self.analysis.scalar, split)
elif self.style == '>':
self.write_folded(self.analysis.scalar)
elif self.style == '|':
self.write_literal(self.analysis.scalar)
else:
self.write_plain(self.analysis.scalar, split)
self.analysis = None
self.style = None
# Analyzers.
def prepare_version(self, version):
major, minor = version
if major != 1:
raise EmitterError("unsupported YAML version: %d.%d" % (major, minor))
return u'%d.%d' % (major, minor)
def prepare_tag_handle(self, handle):
if not handle:
raise EmitterError("tag handle must not be empty")
if handle[0] != u'!' or handle[-1] != u'!':
raise EmitterError("tag handle must start and end with '!': %r"
% (handle.encode('utf-8')))
for ch in handle[1:-1]:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the tag handle: %r"
% (ch.encode('utf-8'), handle.encode('utf-8')))
return handle
def prepare_tag_prefix(self, prefix):
if not prefix:
raise EmitterError("tag prefix must not be empty")
chunks = []
start = end = 0
if prefix[0] == u'!':
end = 1
while end < len(prefix):
ch = prefix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?!:@&=+$,_.~*\'()[]':
end += 1
else:
if start < end:
chunks.append(prefix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(prefix[start:end])
return u''.join(chunks)
def prepare_tag(self, tag):
if not tag:
raise EmitterError("tag must not be empty")
if tag == u'!':
return tag
handle = None
suffix = tag
prefixes = self.tag_prefixes.keys()
prefixes.sort()
for prefix in prefixes:
if tag.startswith(prefix) \
and (prefix == u'!' or len(prefix) < len(tag)):
handle = self.tag_prefixes[prefix]
suffix = tag[len(prefix):]
chunks = []
start = end = 0
while end < len(suffix):
ch = suffix[end]
if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-;/?:@&=+$,_.~*\'()[]' \
or (ch == u'!' and handle != u'!'):
end += 1
else:
if start < end:
chunks.append(suffix[start:end])
start = end = end+1
data = ch.encode('utf-8')
for ch in data:
chunks.append(u'%%%02X' % ord(ch))
if start < end:
chunks.append(suffix[start:end])
suffix_text = u''.join(chunks)
if handle:
return u'%s%s' % (handle, suffix_text)
else:
return u'!<%s>' % suffix_text
def prepare_anchor(self, anchor):
if not anchor:
raise EmitterError("anchor must not be empty")
for ch in anchor:
if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \
or ch in u'-_'):
raise EmitterError("invalid character %r in the anchor: %r"
% (ch.encode('utf-8'), anchor.encode('utf-8')))
return anchor
def analyze_scalar(self, scalar):
# Empty scalar is a special case.
if not scalar:
return ScalarAnalysis(scalar=scalar, empty=True, multiline=False,
allow_flow_plain=False, allow_block_plain=True,
allow_single_quoted=True, allow_double_quoted=True,
allow_block=False)
# Indicators and special characters.
block_indicators = False
flow_indicators = False
line_breaks = False
special_characters = False
# Important whitespace combinations.
leading_space = False
leading_break = False
trailing_space = False
trailing_break = False
break_space = False
space_break = False
# Check document indicators.
if scalar.startswith(u'---') or scalar.startswith(u'...'):
block_indicators = True
flow_indicators = True
# First character or preceded by a whitespace.
preceeded_by_whitespace = True
# Last character or followed by a whitespace.
followed_by_whitespace = (len(scalar) == 1 or
scalar[1] in u'\0 \t\r\n\x85\u2028\u2029')
# The previous character is a space.
previous_space = False
# The previous character is a break.
previous_break = False
index = 0
while index < len(scalar):
ch = scalar[index]
# Check for indicators.
if index == 0:
# Leading indicators are special characters.
if ch in u'#,[]{}&*!|>\'\"%@`':
flow_indicators = True
block_indicators = True
if ch in u'?:':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'-' and followed_by_whitespace:
flow_indicators = True
block_indicators = True
else:
# Some indicators cannot appear within a scalar as well.
if ch in u',?[]{}':
flow_indicators = True
if ch == u':':
flow_indicators = True
if followed_by_whitespace:
block_indicators = True
if ch == u'
flow_indicators = True
block_indicators = True
# Check for line breaks, special, and unicode characters.
if ch in u'\n\x85\u2028\u2029':
line_breaks = True
if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'):
if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF':
unicode_characters = True
if not self.allow_unicode:
special_characters = True
else:
special_characters = True
# Detect important whitespace combinations.
if ch == u' ':
if index == 0:
leading_space = True
if index == len(scalar)-1:
trailing_space = True
if previous_break:
break_space = True
previous_space = True
previous_break = False
elif ch in u'\n\x85\u2028\u2029':
if index == 0:
leading_break = True
if index == len(scalar)-1:
trailing_break = True
if previous_space:
space_break = True
previous_space = False
previous_break = True
else:
previous_space = False
previous_break = False
# Prepare for the next character.
index += 1
preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029')
followed_by_whitespace = (index+1 >= len(scalar) or
scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029')
# Let's decide what styles are allowed.
allow_flow_plain = True
allow_block_plain = True
allow_single_quoted = True
allow_double_quoted = True
allow_block = True
if (leading_space or leading_break
or trailing_space or trailing_break):
allow_flow_plain = allow_block_plain = False
if trailing_space:
allow_block = False
if break_space:
allow_flow_plain = allow_block_plain = allow_single_quoted = False
if space_break or special_characters:
allow_flow_plain = allow_block_plain = \
allow_single_quoted = allow_block = False
if line_breaks:
allow_flow_plain = allow_block_plain = False
if flow_indicators:
allow_flow_plain = False
if block_indicators:
allow_block_plain = False
return ScalarAnalysis(scalar=scalar,
empty=False, multiline=line_breaks,
allow_flow_plain=allow_flow_plain,
allow_block_plain=allow_block_plain,
allow_single_quoted=allow_single_quoted,
allow_double_quoted=allow_double_quoted,
allow_block=allow_block)
def flush_stream(self):
if hasattr(self.stream, 'flush'):
self.stream.flush()
def write_stream_start(self):
if self.encoding and self.encoding.startswith('utf-16'):
self.stream.write(u'\uFEFF'.encode(self.encoding))
def write_stream_end(self):
self.flush_stream()
def write_indicator(self, indicator, need_whitespace,
whitespace=False, indention=False):
if self.whitespace or not need_whitespace:
data = indicator
else:
data = u' '+indicator
self.whitespace = whitespace
self.indention = self.indention and indention
self.column += len(data)
self.open_ended = False
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_indent(self):
indent = self.indent or 0
if not self.indention or self.column > indent \
or (self.column == indent and not self.whitespace):
self.write_line_break()
if self.column < indent:
self.whitespace = True
data = u' '*(indent-self.column)
self.column = indent
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_line_break(self, data=None):
if data is None:
data = self.best_line_break
self.whitespace = True
self.indention = True
self.line += 1
self.column = 0
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
def write_version_directive(self, version_text):
data = u'%%YAML %s' % version_text
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
def write_tag_directive(self, handle_text, prefix_text):
data = u'%%TAG %s %s' % (handle_text, prefix_text)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_line_break()
def write_single_quoted(self, text, split=True):
self.write_indicator(u'\'', True)
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch is None or ch != u' ':
if start+1 == end and self.column > self.best_width and split \
and start != 0 and end != len(text):
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'':
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch == u'\'':
data = u'\'\''
self.column += 2
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end + 1
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
self.write_indicator(u'\'', False)
ESCAPE_REPLACEMENTS = {
u'\0': u'0',
u'\x07': u'a',
u'\x08': u'b',
u'\x09': u't',
u'\x0A': u'n',
u'\x0B': u'v',
u'\x0C': u'f',
u'\x0D': u'r',
u'\x1B': u'e',
u'\"': u'\"',
u'\\': u'\\',
u'\x85': u'N',
u'\xA0': u'_',
u'\u2028': u'L',
u'\u2029': u'P',
}
def write_double_quoted(self, text, split=True):
self.write_indicator(u'"', True)
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \
or not (u'\x20' <= ch <= u'\x7E'
or (self.allow_unicode
and (u'\xA0' <= ch <= u'\uD7FF'
or u'\uE000' <= ch <= u'\uFFFD'))):
if start < end:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
if ch in self.ESCAPE_REPLACEMENTS:
data = u'\\'+self.ESCAPE_REPLACEMENTS[ch]
elif ch <= u'\xFF':
data = u'\\x%02X' % ord(ch)
elif ch <= u'\uFFFF':
data = u'\\u%04X' % ord(ch)
else:
data = u'\\U%08X' % ord(ch)
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end+1
if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \
and self.column+(end-start) > self.best_width and split:
data = text[start:end]+u'\\'
if start < end:
start = end
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.write_indent()
self.whitespace = False
self.indention = False
if text[start] == u' ':
data = u'\\'
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
end += 1
self.write_indicator(u'"', False)
def determine_block_hints(self, text):
hints = u''
if text:
if text[0] in u' \n\x85\u2028\u2029':
hints += unicode(self.best_indent)
if text[-1] not in u'\n\x85\u2028\u2029':
hints += u'-'
elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029':
hints += u'+'
return hints
def write_folded(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'>'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
leading_space = True
spaces = False
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
if not leading_space and ch is not None and ch != u' ' \
and text[start] == u'\n':
self.write_line_break()
leading_space = (ch == u' ')
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
elif spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width:
self.write_indent()
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
spaces = (ch == u' ')
end += 1
def write_literal(self, text):
hints = self.determine_block_hints(text)
self.write_indicator(u'|'+hints, True)
if hints[-1:] == u'+':
self.open_ended = True
self.write_line_break()
breaks = True
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if breaks:
if ch is None or ch not in u'\n\x85\u2028\u2029':
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
if ch is not None:
self.write_indent()
start = end
else:
if ch is None or ch in u'\n\x85\u2028\u2029':
data = text[start:end]
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
if ch is None:
self.write_line_break()
start = end
if ch is not None:
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
def write_plain(self, text, split=True):
if self.root_context:
self.open_ended = True
if not text:
return
if not self.whitespace:
data = u' '
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
self.whitespace = False
self.indention = False
spaces = False
breaks = False
start = end = 0
while end <= len(text):
ch = None
if end < len(text):
ch = text[end]
if spaces:
if ch != u' ':
if start+1 == end and self.column > self.best_width and split:
self.write_indent()
self.whitespace = False
self.indention = False
else:
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
elif breaks:
if ch not in u'\n\x85\u2028\u2029':
if text[start] == u'\n':
self.write_line_break()
for br in text[start:end]:
if br == u'\n':
self.write_line_break()
else:
self.write_line_break(br)
self.write_indent()
self.whitespace = False
self.indention = False
start = end
else:
if ch is None or ch in u' \n\x85\u2028\u2029':
data = text[start:end]
self.column += len(data)
if self.encoding:
data = data.encode(self.encoding)
self.stream.write(data)
start = end
if ch is not None:
spaces = (ch == u' ')
breaks = (ch in u'\n\x85\u2028\u2029')
end += 1
| true | true |
f71ba9b43ab52be7a53f49e34a65c47882d5164b | 5,808 | py | Python | check_bandwidth.py | 3t8/check_bandwidth | 5b2123d2e09c130ef903a63e28925058b5c35e79 | [
"MIT"
] | null | null | null | check_bandwidth.py | 3t8/check_bandwidth | 5b2123d2e09c130ef903a63e28925058b5c35e79 | [
"MIT"
] | null | null | null | check_bandwidth.py | 3t8/check_bandwidth | 5b2123d2e09c130ef903a63e28925058b5c35e79 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Puru
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
'''
Nagios (NRPE) plugin for checking bandwidth speed limit.
'''
from argparse import ArgumentParser
from time import sleep
from sys import exit
from os.path import isdir
import re
__description__ = 'Nagios (NRPE) plugin for checking bandwidth speed limit.'
__author__ = "Puru Tuladhar <tuladharpuru@gmail.com>"
__github__ = "https://github.com/tuladhar/check_bandwidth"
__version__ = "%(prog)s v1.0 by {0} ({1})".format(__author__, __github__)
# See: /usr/lib64/nagios/plugins/utils.sh
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4
PLUGIN_NAME="BANDWIDTH"
THRESHOLD_REGEX=re.compile('(\d+)([K|M|G])$')
def exit_ok(msg):
print "{0} OK - {1}".format(PLUGIN_NAME, msg)
exit(STATE_OK)
def exit_warning(msg):
print "{0} WARNING - {1}".format(PLUGIN_NAME, msg)
exit(STATE_WARNING)
def exit_critical(msg):
print "{0} CRITICAL - {1}".format(PLUGIN_NAME, msg)
exit(STATE_CRITICAL)
def exit_unknown(msg):
print "{0} UNKNOWN - {1}".format(PLUGIN_NAME, msg)
exit(STATE_UNKNOWN)
def get_network_bytes(interface):
dev_path = '/sys/class/net/'+interface
if not isdir(dev_path):
msg = "no such interface: "+interface
exit_unknown(msg)
rx_bytes_path = dev_path+"/statistics/rx_bytes"
tx_bytes_path = dev_path+"/statistics/tx_bytes"
rx_bytes = open(rx_bytes_path, 'r').read()
tx_bytes = open(tx_bytes_path, 'r').read()
return int(rx_bytes), int(tx_bytes)
def convert_unit(value, unit):
if unit == 'K':
v = int(value) * 10**3
if unit == 'M':
v = int(value) * 10**6
if unit == 'G':
v = int(value) * 10**9
return v
def main():
ap = ArgumentParser(description=__description__)
ap.add_argument('-v', '--version', action='version', version=__version__)
ap.add_argument('-i', '--interface', metavar='name', dest='interface', help='interface to use (default: eth0)', default='eth0')
ap.add_argument('-w', '--warning', metavar='threshold', dest='warning', help="threshold in bits. Appending 'K' will count the number as Kilobits, 'M' as Megabits, 'G' as Gigabits. Examples: 200K, 3M and 1G")
ap.add_argument('-c', '--critical', metavar='threshold', dest='critical', help="threshold in bits. Appending 'K' will count the number as Kilobits, 'M' as Megabits and 'G' as Gigabits. Examples: 200K, 3M and 1G")
args = ap.parse_args()
interface = args.interface
if not args.warning or not args.critical:
ap.error('required options: --warning, --critical')
# parse and convert to bits
m1, m2 = THRESHOLD_REGEX.match(args.warning), THRESHOLD_REGEX.match(args.critical)
if not m1 or not m2:
ap.error("supported threshold units: K, M, G")
warning_bits = convert_unit(*m1.groups())
critical_bits = convert_unit(*m2.groups())
warning_rx_bits = warning_tx_bits = warning_bits
critical_rx_bits = critical_tx_bits = critical_bits
# get network transfer bytes and convert to bits
o_rx_bytes, o_tx_bytes = get_network_bytes(interface); sleep(1.0)
n_rx_bytes, n_tx_bytes = get_network_bytes(interface)
rx_bits, tx_bits = (n_rx_bytes - o_rx_bytes)*8, (n_tx_bytes - o_tx_bytes)*8
# convert bandwidth bits back to unit
down = up = None
kbits, mbits, gbits = float(10**3), float(10**6), float(10**9)
if rx_bits < kbits:
down = "{0:.2f} bps".format(rx_bits)
if rx_bits >= kbits:
down = "{0:.2f} Kbps".format(rx_bits / kbits)
if rx_bits >= mbits:
down = "{0:.2f} Mbps".format(rx_bits / mbits)
if rx_bits >= gbits:
down = "{0:.2f} Gbps".format(rx_bits / gbits)
if tx_bits < kbits:
up = "{0:.2f} bps".format(tx_bits)
if tx_bits >= kbits:
up = "{0:.2f} Kbps".format(tx_bits / kbits)
if tx_bits >= mbits:
up = "{0:.2f} Mbps".format(tx_bits / mbits)
if tx_bits >= gbits:
up = "{0:.2f} Gbps".format(tx_bits / gbits)
# check threshold and exit appropriately
msg = "{0}: DOWN: {1}, UP: {2}".format(interface, down, up)
if rx_bits > critical_rx_bits or tx_bits > critical_tx_bits:
exit_critical(msg)
elif rx_bits > warning_rx_bits or tx_bits > warning_tx_bits:
exit_warning(msg)
else:
exit_ok(msg)
if __name__ == '__main__':
main()
| 40.055172 | 220 | 0.640668 |
'''
Nagios (NRPE) plugin for checking bandwidth speed limit.
'''
from argparse import ArgumentParser
from time import sleep
from sys import exit
from os.path import isdir
import re
__description__ = 'Nagios (NRPE) plugin for checking bandwidth speed limit.'
__author__ = "Puru Tuladhar <tuladharpuru@gmail.com>"
__github__ = "https://github.com/tuladhar/check_bandwidth"
__version__ = "%(prog)s v1.0 by {0} ({1})".format(__author__, __github__)
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4
PLUGIN_NAME="BANDWIDTH"
THRESHOLD_REGEX=re.compile('(\d+)([K|M|G])$')
def exit_ok(msg):
print "{0} OK - {1}".format(PLUGIN_NAME, msg)
exit(STATE_OK)
def exit_warning(msg):
print "{0} WARNING - {1}".format(PLUGIN_NAME, msg)
exit(STATE_WARNING)
def exit_critical(msg):
print "{0} CRITICAL - {1}".format(PLUGIN_NAME, msg)
exit(STATE_CRITICAL)
def exit_unknown(msg):
print "{0} UNKNOWN - {1}".format(PLUGIN_NAME, msg)
exit(STATE_UNKNOWN)
def get_network_bytes(interface):
dev_path = '/sys/class/net/'+interface
if not isdir(dev_path):
msg = "no such interface: "+interface
exit_unknown(msg)
rx_bytes_path = dev_path+"/statistics/rx_bytes"
tx_bytes_path = dev_path+"/statistics/tx_bytes"
rx_bytes = open(rx_bytes_path, 'r').read()
tx_bytes = open(tx_bytes_path, 'r').read()
return int(rx_bytes), int(tx_bytes)
def convert_unit(value, unit):
if unit == 'K':
v = int(value) * 10**3
if unit == 'M':
v = int(value) * 10**6
if unit == 'G':
v = int(value) * 10**9
return v
def main():
ap = ArgumentParser(description=__description__)
ap.add_argument('-v', '--version', action='version', version=__version__)
ap.add_argument('-i', '--interface', metavar='name', dest='interface', help='interface to use (default: eth0)', default='eth0')
ap.add_argument('-w', '--warning', metavar='threshold', dest='warning', help="threshold in bits. Appending 'K' will count the number as Kilobits, 'M' as Megabits, 'G' as Gigabits. Examples: 200K, 3M and 1G")
ap.add_argument('-c', '--critical', metavar='threshold', dest='critical', help="threshold in bits. Appending 'K' will count the number as Kilobits, 'M' as Megabits and 'G' as Gigabits. Examples: 200K, 3M and 1G")
args = ap.parse_args()
interface = args.interface
if not args.warning or not args.critical:
ap.error('required options: --warning, --critical')
m1, m2 = THRESHOLD_REGEX.match(args.warning), THRESHOLD_REGEX.match(args.critical)
if not m1 or not m2:
ap.error("supported threshold units: K, M, G")
warning_bits = convert_unit(*m1.groups())
critical_bits = convert_unit(*m2.groups())
warning_rx_bits = warning_tx_bits = warning_bits
critical_rx_bits = critical_tx_bits = critical_bits
o_rx_bytes, o_tx_bytes = get_network_bytes(interface); sleep(1.0)
n_rx_bytes, n_tx_bytes = get_network_bytes(interface)
rx_bits, tx_bits = (n_rx_bytes - o_rx_bytes)*8, (n_tx_bytes - o_tx_bytes)*8
down = up = None
kbits, mbits, gbits = float(10**3), float(10**6), float(10**9)
if rx_bits < kbits:
down = "{0:.2f} bps".format(rx_bits)
if rx_bits >= kbits:
down = "{0:.2f} Kbps".format(rx_bits / kbits)
if rx_bits >= mbits:
down = "{0:.2f} Mbps".format(rx_bits / mbits)
if rx_bits >= gbits:
down = "{0:.2f} Gbps".format(rx_bits / gbits)
if tx_bits < kbits:
up = "{0:.2f} bps".format(tx_bits)
if tx_bits >= kbits:
up = "{0:.2f} Kbps".format(tx_bits / kbits)
if tx_bits >= mbits:
up = "{0:.2f} Mbps".format(tx_bits / mbits)
if tx_bits >= gbits:
up = "{0:.2f} Gbps".format(tx_bits / gbits)
msg = "{0}: DOWN: {1}, UP: {2}".format(interface, down, up)
if rx_bits > critical_rx_bits or tx_bits > critical_tx_bits:
exit_critical(msg)
elif rx_bits > warning_rx_bits or tx_bits > warning_tx_bits:
exit_warning(msg)
else:
exit_ok(msg)
if __name__ == '__main__':
main()
| false | true |
f71baa78a75aac20e49dcb9ac6b3ae5910b61a00 | 13,930 | py | Python | vendor/istio.io/api/python/istio_api/mixer/v1/config/client/api_spec_pb2.py | PinZhang/istio | dce455456d77ca5af34ba5848f9704577349c6bd | [
"Apache-2.0"
] | 40 | 2018-10-24T18:56:01.000Z | 2021-12-30T22:05:33.000Z | vendor/istio.io/api/python/istio_api/mixer/v1/config/client/api_spec_pb2.py | PinZhang/istio | dce455456d77ca5af34ba5848f9704577349c6bd | [
"Apache-2.0"
] | 17 | 2019-01-11T05:57:35.000Z | 2019-08-29T05:33:38.000Z | vendor/istio.io/api/python/istio_api/mixer/v1/config/client/api_spec_pb2.py | PinZhang/istio | dce455456d77ca5af34ba5848f9704577349c6bd | [
"Apache-2.0"
] | 14 | 2018-11-09T19:17:26.000Z | 2021-12-16T16:36:24.000Z | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mixer/v1/config/client/api_spec.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from gogoproto import gogo_pb2 as gogoproto_dot_gogo__pb2
from mixer.v1 import attributes_pb2 as mixer_dot_v1_dot_attributes__pb2
from mixer.v1.config.client import service_pb2 as mixer_dot_v1_dot_config_dot_client_dot_service__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='mixer/v1/config/client/api_spec.proto',
package='istio.mixer.v1.config.client',
syntax='proto3',
serialized_pb=_b('\n%mixer/v1/config/client/api_spec.proto\x12\x1cistio.mixer.v1.config.client\x1a\x14gogoproto/gogo.proto\x1a\x19mixer/v1/attributes.proto\x1a$mixer/v1/config/client/service.proto\"\xb9\x01\n\x0bHTTPAPISpec\x12.\n\nattributes\x18\x01 \x01(\x0b\x32\x1a.istio.mixer.v1.Attributes\x12\x42\n\x08patterns\x18\x02 \x03(\x0b\x32\x30.istio.mixer.v1.config.client.HTTPAPISpecPattern\x12\x36\n\x08\x61pi_keys\x18\x03 \x03(\x0b\x32$.istio.mixer.v1.config.client.APIKey\"\x8d\x01\n\x12HTTPAPISpecPattern\x12.\n\nattributes\x18\x01 \x01(\x0b\x32\x1a.istio.mixer.v1.Attributes\x12\x13\n\x0bhttp_method\x18\x02 \x01(\t\x12\x16\n\x0curi_template\x18\x03 \x01(\tH\x00\x12\x0f\n\x05regex\x18\x04 \x01(\tH\x00\x42\t\n\x07pattern\"D\n\x06\x41PIKey\x12\x0f\n\x05query\x18\x01 \x01(\tH\x00\x12\x10\n\x06header\x18\x02 \x01(\tH\x00\x12\x10\n\x06\x63ookie\x18\x03 \x01(\tH\x00\x42\x05\n\x03key\"7\n\x14HTTPAPISpecReference\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"\x99\x01\n\x12HTTPAPISpecBinding\x12<\n\x08services\x18\x01 \x03(\x0b\x32*.istio.mixer.v1.config.client.IstioService\x12\x45\n\tapi_specs\x18\x02 \x03(\x0b\x32\x32.istio.mixer.v1.config.client.HTTPAPISpecReferenceB1Z#istio.io/api/mixer/v1/config/client\xc8\xe1\x1e\x00\xa8\xe2\x1e\x00\xf0\xe1\x1e\x00\x62\x06proto3')
,
dependencies=[gogoproto_dot_gogo__pb2.DESCRIPTOR,mixer_dot_v1_dot_attributes__pb2.DESCRIPTOR,mixer_dot_v1_dot_config_dot_client_dot_service__pb2.DESCRIPTOR,])
_HTTPAPISPEC = _descriptor.Descriptor(
name='HTTPAPISpec',
full_name='istio.mixer.v1.config.client.HTTPAPISpec',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='attributes', full_name='istio.mixer.v1.config.client.HTTPAPISpec.attributes', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='patterns', full_name='istio.mixer.v1.config.client.HTTPAPISpec.patterns', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='api_keys', full_name='istio.mixer.v1.config.client.HTTPAPISpec.api_keys', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=159,
serialized_end=344,
)
_HTTPAPISPECPATTERN = _descriptor.Descriptor(
name='HTTPAPISpecPattern',
full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='attributes', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.attributes', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='http_method', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.http_method', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='uri_template', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.uri_template', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='regex', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.regex', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='pattern', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.pattern',
index=0, containing_type=None, fields=[]),
],
serialized_start=347,
serialized_end=488,
)
_APIKEY = _descriptor.Descriptor(
name='APIKey',
full_name='istio.mixer.v1.config.client.APIKey',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='query', full_name='istio.mixer.v1.config.client.APIKey.query', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='header', full_name='istio.mixer.v1.config.client.APIKey.header', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cookie', full_name='istio.mixer.v1.config.client.APIKey.cookie', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='key', full_name='istio.mixer.v1.config.client.APIKey.key',
index=0, containing_type=None, fields=[]),
],
serialized_start=490,
serialized_end=558,
)
_HTTPAPISPECREFERENCE = _descriptor.Descriptor(
name='HTTPAPISpecReference',
full_name='istio.mixer.v1.config.client.HTTPAPISpecReference',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='istio.mixer.v1.config.client.HTTPAPISpecReference.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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='namespace', full_name='istio.mixer.v1.config.client.HTTPAPISpecReference.namespace', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=560,
serialized_end=615,
)
_HTTPAPISPECBINDING = _descriptor.Descriptor(
name='HTTPAPISpecBinding',
full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='services', full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding.services', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='api_specs', full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding.api_specs', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=618,
serialized_end=771,
)
_HTTPAPISPEC.fields_by_name['attributes'].message_type = mixer_dot_v1_dot_attributes__pb2._ATTRIBUTES
_HTTPAPISPEC.fields_by_name['patterns'].message_type = _HTTPAPISPECPATTERN
_HTTPAPISPEC.fields_by_name['api_keys'].message_type = _APIKEY
_HTTPAPISPECPATTERN.fields_by_name['attributes'].message_type = mixer_dot_v1_dot_attributes__pb2._ATTRIBUTES
_HTTPAPISPECPATTERN.oneofs_by_name['pattern'].fields.append(
_HTTPAPISPECPATTERN.fields_by_name['uri_template'])
_HTTPAPISPECPATTERN.fields_by_name['uri_template'].containing_oneof = _HTTPAPISPECPATTERN.oneofs_by_name['pattern']
_HTTPAPISPECPATTERN.oneofs_by_name['pattern'].fields.append(
_HTTPAPISPECPATTERN.fields_by_name['regex'])
_HTTPAPISPECPATTERN.fields_by_name['regex'].containing_oneof = _HTTPAPISPECPATTERN.oneofs_by_name['pattern']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['query'])
_APIKEY.fields_by_name['query'].containing_oneof = _APIKEY.oneofs_by_name['key']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['header'])
_APIKEY.fields_by_name['header'].containing_oneof = _APIKEY.oneofs_by_name['key']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['cookie'])
_APIKEY.fields_by_name['cookie'].containing_oneof = _APIKEY.oneofs_by_name['key']
_HTTPAPISPECBINDING.fields_by_name['services'].message_type = mixer_dot_v1_dot_config_dot_client_dot_service__pb2._ISTIOSERVICE
_HTTPAPISPECBINDING.fields_by_name['api_specs'].message_type = _HTTPAPISPECREFERENCE
DESCRIPTOR.message_types_by_name['HTTPAPISpec'] = _HTTPAPISPEC
DESCRIPTOR.message_types_by_name['HTTPAPISpecPattern'] = _HTTPAPISPECPATTERN
DESCRIPTOR.message_types_by_name['APIKey'] = _APIKEY
DESCRIPTOR.message_types_by_name['HTTPAPISpecReference'] = _HTTPAPISPECREFERENCE
DESCRIPTOR.message_types_by_name['HTTPAPISpecBinding'] = _HTTPAPISPECBINDING
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
HTTPAPISpec = _reflection.GeneratedProtocolMessageType('HTTPAPISpec', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPEC,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpec)
))
_sym_db.RegisterMessage(HTTPAPISpec)
HTTPAPISpecPattern = _reflection.GeneratedProtocolMessageType('HTTPAPISpecPattern', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECPATTERN,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecPattern)
))
_sym_db.RegisterMessage(HTTPAPISpecPattern)
APIKey = _reflection.GeneratedProtocolMessageType('APIKey', (_message.Message,), dict(
DESCRIPTOR = _APIKEY,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.APIKey)
))
_sym_db.RegisterMessage(APIKey)
HTTPAPISpecReference = _reflection.GeneratedProtocolMessageType('HTTPAPISpecReference', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECREFERENCE,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecReference)
))
_sym_db.RegisterMessage(HTTPAPISpecReference)
HTTPAPISpecBinding = _reflection.GeneratedProtocolMessageType('HTTPAPISpecBinding', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECBINDING,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecBinding)
))
_sym_db.RegisterMessage(HTTPAPISpecBinding)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('Z#istio.io/api/mixer/v1/config/client\310\341\036\000\250\342\036\000\360\341\036\000'))
# @@protoc_insertion_point(module_scope)
| 43.26087 | 1,306 | 0.760876 |
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
_sym_db = _symbol_database.Default()
from gogoproto import gogo_pb2 as gogoproto_dot_gogo__pb2
from mixer.v1 import attributes_pb2 as mixer_dot_v1_dot_attributes__pb2
from mixer.v1.config.client import service_pb2 as mixer_dot_v1_dot_config_dot_client_dot_service__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='mixer/v1/config/client/api_spec.proto',
package='istio.mixer.v1.config.client',
syntax='proto3',
serialized_pb=_b('\n%mixer/v1/config/client/api_spec.proto\x12\x1cistio.mixer.v1.config.client\x1a\x14gogoproto/gogo.proto\x1a\x19mixer/v1/attributes.proto\x1a$mixer/v1/config/client/service.proto\"\xb9\x01\n\x0bHTTPAPISpec\x12.\n\nattributes\x18\x01 \x01(\x0b\x32\x1a.istio.mixer.v1.Attributes\x12\x42\n\x08patterns\x18\x02 \x03(\x0b\x32\x30.istio.mixer.v1.config.client.HTTPAPISpecPattern\x12\x36\n\x08\x61pi_keys\x18\x03 \x03(\x0b\x32$.istio.mixer.v1.config.client.APIKey\"\x8d\x01\n\x12HTTPAPISpecPattern\x12.\n\nattributes\x18\x01 \x01(\x0b\x32\x1a.istio.mixer.v1.Attributes\x12\x13\n\x0bhttp_method\x18\x02 \x01(\t\x12\x16\n\x0curi_template\x18\x03 \x01(\tH\x00\x12\x0f\n\x05regex\x18\x04 \x01(\tH\x00\x42\t\n\x07pattern\"D\n\x06\x41PIKey\x12\x0f\n\x05query\x18\x01 \x01(\tH\x00\x12\x10\n\x06header\x18\x02 \x01(\tH\x00\x12\x10\n\x06\x63ookie\x18\x03 \x01(\tH\x00\x42\x05\n\x03key\"7\n\x14HTTPAPISpecReference\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tnamespace\x18\x02 \x01(\t\"\x99\x01\n\x12HTTPAPISpecBinding\x12<\n\x08services\x18\x01 \x03(\x0b\x32*.istio.mixer.v1.config.client.IstioService\x12\x45\n\tapi_specs\x18\x02 \x03(\x0b\x32\x32.istio.mixer.v1.config.client.HTTPAPISpecReferenceB1Z#istio.io/api/mixer/v1/config/client\xc8\xe1\x1e\x00\xa8\xe2\x1e\x00\xf0\xe1\x1e\x00\x62\x06proto3')
,
dependencies=[gogoproto_dot_gogo__pb2.DESCRIPTOR,mixer_dot_v1_dot_attributes__pb2.DESCRIPTOR,mixer_dot_v1_dot_config_dot_client_dot_service__pb2.DESCRIPTOR,])
_HTTPAPISPEC = _descriptor.Descriptor(
name='HTTPAPISpec',
full_name='istio.mixer.v1.config.client.HTTPAPISpec',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='attributes', full_name='istio.mixer.v1.config.client.HTTPAPISpec.attributes', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='patterns', full_name='istio.mixer.v1.config.client.HTTPAPISpec.patterns', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='api_keys', full_name='istio.mixer.v1.config.client.HTTPAPISpec.api_keys', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=159,
serialized_end=344,
)
_HTTPAPISPECPATTERN = _descriptor.Descriptor(
name='HTTPAPISpecPattern',
full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='attributes', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.attributes', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='http_method', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.http_method', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='uri_template', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.uri_template', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='regex', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.regex', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='pattern', full_name='istio.mixer.v1.config.client.HTTPAPISpecPattern.pattern',
index=0, containing_type=None, fields=[]),
],
serialized_start=347,
serialized_end=488,
)
_APIKEY = _descriptor.Descriptor(
name='APIKey',
full_name='istio.mixer.v1.config.client.APIKey',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='query', full_name='istio.mixer.v1.config.client.APIKey.query', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='header', full_name='istio.mixer.v1.config.client.APIKey.header', 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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='cookie', full_name='istio.mixer.v1.config.client.APIKey.cookie', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='key', full_name='istio.mixer.v1.config.client.APIKey.key',
index=0, containing_type=None, fields=[]),
],
serialized_start=490,
serialized_end=558,
)
_HTTPAPISPECREFERENCE = _descriptor.Descriptor(
name='HTTPAPISpecReference',
full_name='istio.mixer.v1.config.client.HTTPAPISpecReference',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='istio.mixer.v1.config.client.HTTPAPISpecReference.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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='namespace', full_name='istio.mixer.v1.config.client.HTTPAPISpecReference.namespace', 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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=560,
serialized_end=615,
)
_HTTPAPISPECBINDING = _descriptor.Descriptor(
name='HTTPAPISpecBinding',
full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='services', full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding.services', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='api_specs', full_name='istio.mixer.v1.config.client.HTTPAPISpecBinding.api_specs', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=618,
serialized_end=771,
)
_HTTPAPISPEC.fields_by_name['attributes'].message_type = mixer_dot_v1_dot_attributes__pb2._ATTRIBUTES
_HTTPAPISPEC.fields_by_name['patterns'].message_type = _HTTPAPISPECPATTERN
_HTTPAPISPEC.fields_by_name['api_keys'].message_type = _APIKEY
_HTTPAPISPECPATTERN.fields_by_name['attributes'].message_type = mixer_dot_v1_dot_attributes__pb2._ATTRIBUTES
_HTTPAPISPECPATTERN.oneofs_by_name['pattern'].fields.append(
_HTTPAPISPECPATTERN.fields_by_name['uri_template'])
_HTTPAPISPECPATTERN.fields_by_name['uri_template'].containing_oneof = _HTTPAPISPECPATTERN.oneofs_by_name['pattern']
_HTTPAPISPECPATTERN.oneofs_by_name['pattern'].fields.append(
_HTTPAPISPECPATTERN.fields_by_name['regex'])
_HTTPAPISPECPATTERN.fields_by_name['regex'].containing_oneof = _HTTPAPISPECPATTERN.oneofs_by_name['pattern']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['query'])
_APIKEY.fields_by_name['query'].containing_oneof = _APIKEY.oneofs_by_name['key']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['header'])
_APIKEY.fields_by_name['header'].containing_oneof = _APIKEY.oneofs_by_name['key']
_APIKEY.oneofs_by_name['key'].fields.append(
_APIKEY.fields_by_name['cookie'])
_APIKEY.fields_by_name['cookie'].containing_oneof = _APIKEY.oneofs_by_name['key']
_HTTPAPISPECBINDING.fields_by_name['services'].message_type = mixer_dot_v1_dot_config_dot_client_dot_service__pb2._ISTIOSERVICE
_HTTPAPISPECBINDING.fields_by_name['api_specs'].message_type = _HTTPAPISPECREFERENCE
DESCRIPTOR.message_types_by_name['HTTPAPISpec'] = _HTTPAPISPEC
DESCRIPTOR.message_types_by_name['HTTPAPISpecPattern'] = _HTTPAPISPECPATTERN
DESCRIPTOR.message_types_by_name['APIKey'] = _APIKEY
DESCRIPTOR.message_types_by_name['HTTPAPISpecReference'] = _HTTPAPISPECREFERENCE
DESCRIPTOR.message_types_by_name['HTTPAPISpecBinding'] = _HTTPAPISPECBINDING
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
HTTPAPISpec = _reflection.GeneratedProtocolMessageType('HTTPAPISpec', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPEC,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpec)
))
_sym_db.RegisterMessage(HTTPAPISpec)
HTTPAPISpecPattern = _reflection.GeneratedProtocolMessageType('HTTPAPISpecPattern', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECPATTERN,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecPattern)
))
_sym_db.RegisterMessage(HTTPAPISpecPattern)
APIKey = _reflection.GeneratedProtocolMessageType('APIKey', (_message.Message,), dict(
DESCRIPTOR = _APIKEY,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.APIKey)
))
_sym_db.RegisterMessage(APIKey)
HTTPAPISpecReference = _reflection.GeneratedProtocolMessageType('HTTPAPISpecReference', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECREFERENCE,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecReference)
))
_sym_db.RegisterMessage(HTTPAPISpecReference)
HTTPAPISpecBinding = _reflection.GeneratedProtocolMessageType('HTTPAPISpecBinding', (_message.Message,), dict(
DESCRIPTOR = _HTTPAPISPECBINDING,
__module__ = 'mixer.v1.config.client.api_spec_pb2'
# @@protoc_insertion_point(class_scope:istio.mixer.v1.config.client.HTTPAPISpecBinding)
))
_sym_db.RegisterMessage(HTTPAPISpecBinding)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('Z#istio.io/api/mixer/v1/config/client\310\341\036\000\250\342\036\000\360\341\036\000'))
# @@protoc_insertion_point(module_scope)
| true | true |
f71baa8f160f4d36be63fb40e4502ee2b84f9a05 | 4,141 | py | Python | pextant/solvers/SEXTANTsolver.py | norheim/pextant | f4235719279c0e6f178ae1e0f8b1ea3346533915 | [
"MIT"
] | null | null | null | pextant/solvers/SEXTANTsolver.py | norheim/pextant | f4235719279c0e6f178ae1e0f8b1ea3346533915 | [
"MIT"
] | 1 | 2019-12-03T03:52:41.000Z | 2019-12-04T14:50:36.000Z | pextant/solvers/SEXTANTsolver.py | norheim/pextant | f4235719279c0e6f178ae1e0f8b1ea3346533915 | [
"MIT"
] | 1 | 2019-12-03T02:37:57.000Z | 2019-12-03T02:37:57.000Z | from pextant.lib.geoshapely import GeoPolygon, LONG_LAT
import numpy as np
import csv
class SEXTANTSolver(object):
def __init__(self, environmental_model, cost_function, viz):
self.env_model = environmental_model
self.cost_function = cost_function
self.viz = viz
self.searches = []
def solve(self, start_point, end_point):
pass
def solvemultipoint(self, waypoints):
search_list = sextantSearchList(waypoints)
for i in range(len(waypoints) - 1):
search_result = self.solve(waypoints[i], waypoints[i + 1])
search_list.append(search_result)
return search_list, search_list.raw(), search_list.itemssrchd()
class sextantSearchList(object):
def __init__(self, points):
self.startpoint = points[0]
self.endpoint = points[-1]
self.waypoints = points
self.list = []
self.rawpoints = []
def addresult(self, raw, nodes, coordinates, expanded_items):
self.list.append(sextantSearch(raw, nodes, coordinates, expanded_items))
def append(self, sextantsearch):
self.list.append(sextantsearch)
def raw(self):
result = []
for search in self.list:
if search == False:
return None
result += search.raw
return np.array(result)
def coordinates(self):
result = []
for search in self.list:
if type(search) == bool:
return None
result += search.coordinates.to(LONG_LAT).transpose().tolist()
return GeoPolygon(LONG_LAT, *np.array(result).transpose())
def itemssrchd(self):
result = []
for search in self.list:
if type(search) == bool:
return None
result += search.expanded_items
return np.array(result)
def tojson(self, save=False):
return [elt.tojson() for elt in self.list]
def tocsv(self, filepath=None):
csvlist = [elt.tocsv() for elt in self.list]
rows = [['isStation', 'x', 'y', 'z', 'distanceMeters', 'energyJoules', 'timeSeconds']]
for row in csvlist:
rows += row
if filepath:
with open(filepath, 'wb') as csvfile:
writer = csv.writer(csvfile)
for row in rows:
writer.writerow(row)
return csvlist
class sextantSearch(object):
def __init__(self, raw, nodes, coordinates, expanded_items):
self.namemap = {
'time': ['timeList','totalTime'],
'pathlength': ['distanceList','totalDistance'],
'energy': ['energyList','totalEnergy']
}
#self.searches = []
self.nodes = nodes
self.raw = raw
self.npraw = np.array(raw).transpose()
self.coordinates = coordinates
self.expanded_items = expanded_items
def tojson(self):
out = {}
coordinates = self.coordinates.to(LONG_LAT).transpose().tolist()
out["geometry"] = {
'type': 'LineString',
'coordinates': coordinates
}
results = {}
for k, v in self.namemap.items():
results.update({v[0]:[],v[1]:0})
for i, mesh_srch_elt in enumerate(self.nodes):
derived = mesh_srch_elt.derived
for k, v in derived.items():
results[self.namemap[k][0]].append(v)
for k, v in self.namemap.items():
results[v[1]] = sum(results[v[0]])
out["derivedInfo"] = results
return out
def tocsv(self, coordstype=LONG_LAT):
sequence = []
coords = self.coordinates.to(coordstype).transpose().tolist()
for i, mesh_srch_elt in enumerate(self.nodes):
if i != 0:
row_entry = [i==1 or i==len(coords)-1] #True if it's the first or last entry
row_entry += coords[i] + [mesh_srch_elt.mesh_element.z]
derived = mesh_srch_elt.derived
row_entry += [derived['pathlength'], derived['time'], derived['energy']]
sequence += [row_entry]
return sequence
| 34.508333 | 94 | 0.576914 | from pextant.lib.geoshapely import GeoPolygon, LONG_LAT
import numpy as np
import csv
class SEXTANTSolver(object):
def __init__(self, environmental_model, cost_function, viz):
self.env_model = environmental_model
self.cost_function = cost_function
self.viz = viz
self.searches = []
def solve(self, start_point, end_point):
pass
def solvemultipoint(self, waypoints):
search_list = sextantSearchList(waypoints)
for i in range(len(waypoints) - 1):
search_result = self.solve(waypoints[i], waypoints[i + 1])
search_list.append(search_result)
return search_list, search_list.raw(), search_list.itemssrchd()
class sextantSearchList(object):
def __init__(self, points):
self.startpoint = points[0]
self.endpoint = points[-1]
self.waypoints = points
self.list = []
self.rawpoints = []
def addresult(self, raw, nodes, coordinates, expanded_items):
self.list.append(sextantSearch(raw, nodes, coordinates, expanded_items))
def append(self, sextantsearch):
self.list.append(sextantsearch)
def raw(self):
result = []
for search in self.list:
if search == False:
return None
result += search.raw
return np.array(result)
def coordinates(self):
result = []
for search in self.list:
if type(search) == bool:
return None
result += search.coordinates.to(LONG_LAT).transpose().tolist()
return GeoPolygon(LONG_LAT, *np.array(result).transpose())
def itemssrchd(self):
result = []
for search in self.list:
if type(search) == bool:
return None
result += search.expanded_items
return np.array(result)
def tojson(self, save=False):
return [elt.tojson() for elt in self.list]
def tocsv(self, filepath=None):
csvlist = [elt.tocsv() for elt in self.list]
rows = [['isStation', 'x', 'y', 'z', 'distanceMeters', 'energyJoules', 'timeSeconds']]
for row in csvlist:
rows += row
if filepath:
with open(filepath, 'wb') as csvfile:
writer = csv.writer(csvfile)
for row in rows:
writer.writerow(row)
return csvlist
class sextantSearch(object):
def __init__(self, raw, nodes, coordinates, expanded_items):
self.namemap = {
'time': ['timeList','totalTime'],
'pathlength': ['distanceList','totalDistance'],
'energy': ['energyList','totalEnergy']
}
self.nodes = nodes
self.raw = raw
self.npraw = np.array(raw).transpose()
self.coordinates = coordinates
self.expanded_items = expanded_items
def tojson(self):
out = {}
coordinates = self.coordinates.to(LONG_LAT).transpose().tolist()
out["geometry"] = {
'type': 'LineString',
'coordinates': coordinates
}
results = {}
for k, v in self.namemap.items():
results.update({v[0]:[],v[1]:0})
for i, mesh_srch_elt in enumerate(self.nodes):
derived = mesh_srch_elt.derived
for k, v in derived.items():
results[self.namemap[k][0]].append(v)
for k, v in self.namemap.items():
results[v[1]] = sum(results[v[0]])
out["derivedInfo"] = results
return out
def tocsv(self, coordstype=LONG_LAT):
sequence = []
coords = self.coordinates.to(coordstype).transpose().tolist()
for i, mesh_srch_elt in enumerate(self.nodes):
if i != 0:
row_entry = [i==1 or i==len(coords)-1]
row_entry += coords[i] + [mesh_srch_elt.mesh_element.z]
derived = mesh_srch_elt.derived
row_entry += [derived['pathlength'], derived['time'], derived['energy']]
sequence += [row_entry]
return sequence
| true | true |
f71baa9da47252c881d3e4b3537037ac3e200836 | 3,658 | py | Python | models/client.py | dssaenzml/federated_learning_nlp | b48fbeb3e78af5971885337203504c017ef1553b | [
"BSD-2-Clause"
] | 2 | 2021-05-17T05:30:50.000Z | 2021-05-18T16:20:10.000Z | models/client.py | dssaenzml/federated_learning_nlp | b48fbeb3e78af5971885337203504c017ef1553b | [
"BSD-2-Clause"
] | null | null | null | models/client.py | dssaenzml/federated_learning_nlp | b48fbeb3e78af5971885337203504c017ef1553b | [
"BSD-2-Clause"
] | 1 | 2021-07-10T21:07:01.000Z | 2021-07-10T21:07:01.000Z | import random
import warnings
class Client:
def __init__(self, client_id, group=None, train_data={'x' : [],'y' : []}, eval_data={'x' : [],'y' : []}, model=None):
self._model = model
self.id = client_id
self.group = group
self.train_data = train_data
self.eval_data = eval_data
def train(self, num_epochs=1, batch_size=10, minibatch=None):
"""Trains on self.model using the client's train_data.
Args:
num_epochs: Number of epochs to train. Unsupported if minibatch is provided (minibatch has only 1 epoch)
batch_size: Size of training batches.
minibatch: fraction of client's data to apply minibatch sgd,
None to use FedAvg
Return:
comp: number of FLOPs executed in training process
num_samples: number of samples used in training
update: set of weights
update_size: number of bytes in update
"""
if minibatch is None:
data = self.train_data
comp, update = self.model.train(data, num_epochs, batch_size)
else:
frac = min(1.0, minibatch)
num_data = max(1, int(frac*len(self.train_data["x"])))
xs, ys = zip(*random.sample(list(zip(self.train_data["x"], self.train_data["y"])), num_data))
data = {'x': xs, 'y': ys}
# Minibatch trains for only 1 epoch - multiple local epochs don't make sense!
num_epochs = 1
comp, update = self.model.train(data, num_epochs, num_data)
num_train_samples = len(data['y'])
return comp, num_train_samples, update
def test(self, set_to_use='test'):
"""Tests self.model on self.test_data.
Args:
set_to_use. Set to test on. Should be in ['train', 'test'].
Return:
dict of metrics returned by the model.
"""
assert set_to_use in ['train', 'test', 'val']
if set_to_use == 'train':
data = self.train_data
elif set_to_use == 'test' or set_to_use == 'val':
data = self.eval_data
return self.model.test(data)
@property
def num_test_samples(self):
"""Number of test samples for this client.
Return:
int: Number of test samples for this client
"""
if self.eval_data is None:
return 0
return len(self.eval_data['y'])
@property
def num_train_samples(self):
"""Number of train samples for this client.
Return:
int: Number of train samples for this client
"""
if self.train_data is None:
return 0
return len(self.train_data['y'])
@property
def num_samples(self):
"""Number samples for this client.
Return:
int: Number of samples for this client
"""
train_size = 0
if self.train_data is not None:
train_size = len(self.train_data['y'])
test_size = 0
if self.eval_data is not None:
test_size = len(self.eval_data['y'])
return train_size + test_size
@property
def model(self):
"""Returns this client reference to model being trained"""
return self._model
@model.setter
def model(self, model):
warnings.warn('The current implementation shares the model among all clients.'
'Setting it on one client will effectively modify all clients.')
self._model = model
| 34.509434 | 122 | 0.563423 | import random
import warnings
class Client:
def __init__(self, client_id, group=None, train_data={'x' : [],'y' : []}, eval_data={'x' : [],'y' : []}, model=None):
self._model = model
self.id = client_id
self.group = group
self.train_data = train_data
self.eval_data = eval_data
def train(self, num_epochs=1, batch_size=10, minibatch=None):
if minibatch is None:
data = self.train_data
comp, update = self.model.train(data, num_epochs, batch_size)
else:
frac = min(1.0, minibatch)
num_data = max(1, int(frac*len(self.train_data["x"])))
xs, ys = zip(*random.sample(list(zip(self.train_data["x"], self.train_data["y"])), num_data))
data = {'x': xs, 'y': ys}
num_epochs = 1
comp, update = self.model.train(data, num_epochs, num_data)
num_train_samples = len(data['y'])
return comp, num_train_samples, update
def test(self, set_to_use='test'):
assert set_to_use in ['train', 'test', 'val']
if set_to_use == 'train':
data = self.train_data
elif set_to_use == 'test' or set_to_use == 'val':
data = self.eval_data
return self.model.test(data)
@property
def num_test_samples(self):
if self.eval_data is None:
return 0
return len(self.eval_data['y'])
@property
def num_train_samples(self):
if self.train_data is None:
return 0
return len(self.train_data['y'])
@property
def num_samples(self):
train_size = 0
if self.train_data is not None:
train_size = len(self.train_data['y'])
test_size = 0
if self.eval_data is not None:
test_size = len(self.eval_data['y'])
return train_size + test_size
@property
def model(self):
return self._model
@model.setter
def model(self, model):
warnings.warn('The current implementation shares the model among all clients.'
'Setting it on one client will effectively modify all clients.')
self._model = model
| true | true |
f71bab718e68dcdd90ff7a41d77e7394ed89c45b | 1,236 | py | Python | tests/test_views.py | kingsdigitallab/django-geonames-place | 2484abaee6896bafe2f86e93bffca634073a6d3b | [
"MIT"
] | 3 | 2019-06-30T08:13:38.000Z | 2020-06-09T22:30:17.000Z | tests/test_views.py | kingsdigitallab/django-geonames-place | 2484abaee6896bafe2f86e93bffca634073a6d3b | [
"MIT"
] | null | null | null | tests/test_views.py | kingsdigitallab/django-geonames-place | 2484abaee6896bafe2f86e93bffca634073a6d3b | [
"MIT"
] | null | null | null | """
test_django-geonames-place
------------
Tests for `django-geonames-place` views module.
"""
import unittest
from django.conf import settings
from django.test import Client, TestCase
from django.urls import reverse
from geonames_place.models import Place
@unittest.skipUnless(
settings.GEONAMES_KEY, 'No GEONAMES_KEY environment variable set')
class TestGeonamesPlaceViews(TestCase):
def setUp(self):
self.geonames_id = 2635167
self.geonames_address = 'United Kingdom'
self.address = 'London'
def test_autocomplete_view(self):
self.assertEqual(Place.objects.count(), 0)
url = reverse('place_autocomplete')
c = Client()
response = c.get(url, {'term': 'Lo'})
self.assertEqual(response.json()['results'], [])
p = Place(geonames_id=self.geonames_id)
p.save()
self.assertEqual(Place.objects.count(), 1)
response = c.get(url, {'term': 'London'})
self.assertNotEqual(len(response.json()['results']), 0)
# There are many places with London in the name, and they
# should now be stored in the Place model, having been fetched
# from Geonames.
self.assertTrue(Place.objects.count() > 1)
| 30.146341 | 70 | 0.661812 |
import unittest
from django.conf import settings
from django.test import Client, TestCase
from django.urls import reverse
from geonames_place.models import Place
@unittest.skipUnless(
settings.GEONAMES_KEY, 'No GEONAMES_KEY environment variable set')
class TestGeonamesPlaceViews(TestCase):
def setUp(self):
self.geonames_id = 2635167
self.geonames_address = 'United Kingdom'
self.address = 'London'
def test_autocomplete_view(self):
self.assertEqual(Place.objects.count(), 0)
url = reverse('place_autocomplete')
c = Client()
response = c.get(url, {'term': 'Lo'})
self.assertEqual(response.json()['results'], [])
p = Place(geonames_id=self.geonames_id)
p.save()
self.assertEqual(Place.objects.count(), 1)
response = c.get(url, {'term': 'London'})
self.assertNotEqual(len(response.json()['results']), 0)
self.assertTrue(Place.objects.count() > 1)
| true | true |
f71bac9cf6ccf566ff63cc6598f04ef5c0efd656 | 1,978 | py | Python | tests/test_security_api_key_header_optional.py | jfunez/fastapi | 7372f6ba11abb515a7f11814dba52a1d1c0925f0 | [
"MIT"
] | 2 | 2020-04-09T07:11:28.000Z | 2020-12-12T14:04:35.000Z | tests/test_security_api_key_header_optional.py | jfunez/fastapi | 7372f6ba11abb515a7f11814dba52a1d1c0925f0 | [
"MIT"
] | 1 | 2021-03-27T18:37:32.000Z | 2021-05-25T15:08:24.000Z | tests/test_security_api_key_header_optional.py | jfunez/fastapi | 7372f6ba11abb515a7f11814dba52a1d1c0925f0 | [
"MIT"
] | 1 | 2021-02-03T00:43:04.000Z | 2021-02-03T00:43:04.000Z | from typing import Optional
from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyHeader(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"APIKeyHeader": []}],
}
}
},
"components": {
"securitySchemes": {
"APIKeyHeader": {"type": "apiKey", "name": "key", "in": "header"}
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", headers={"key": "secret"})
assert response.status_code == 200
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
assert response.status_code == 200
assert response.json() == {"msg": "Create an account first"}
| 26.373333 | 80 | 0.592518 | from typing import Optional
from fastapi import Depends, FastAPI, Security
from fastapi.security import APIKeyHeader
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
api_key = APIKeyHeader(name="key", auto_error=False)
class User(BaseModel):
username: str
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
if oauth_header is None:
return None
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
if current_user is None:
return {"msg": "Create an account first"}
return current_user
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/users/me": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
"summary": "Read Current User",
"operationId": "read_current_user_users_me_get",
"security": [{"APIKeyHeader": []}],
}
}
},
"components": {
"securitySchemes": {
"APIKeyHeader": {"type": "apiKey", "name": "key", "in": "header"}
}
},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", headers={"key": "secret"})
assert response.status_code == 200
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
assert response.status_code == 200
assert response.json() == {"msg": "Create an account first"}
| true | true |
f71bacf6ae00989a3846b6e65f0871f7161f845d | 5,427 | py | Python | docqa/elmo/ablate_elmo_sub_filter.py | Willyoung2017/doc-qa | 7ee02218952b0b9db63bc82b3895f743cdbd8f22 | [
"Apache-2.0"
] | null | null | null | docqa/elmo/ablate_elmo_sub_filter.py | Willyoung2017/doc-qa | 7ee02218952b0b9db63bc82b3895f743cdbd8f22 | [
"Apache-2.0"
] | null | null | null | docqa/elmo/ablate_elmo_sub_filter.py | Willyoung2017/doc-qa | 7ee02218952b0b9db63bc82b3895f743cdbd8f22 | [
"Apache-2.0"
] | null | null | null | import argparse
from datetime import datetime
from tensorflow.contrib.keras.python.keras.initializers import TruncatedNormal
from docqa import trainer
from docqa.data_processing.qa_training_data import ContextLenKey
from docqa.dataset import ClusteredBatcher
from docqa.encoder import DocumentAndQuestionEncoder, SingleSpanAnswerEncoder, DocumentAndQuestionEncoderWithSubstring
from docqa.evaluator import LossEvaluator, SpanEvaluator
from docqa.elmo.elmo import ElmoLayer
from docqa.elmo.lm_qa_models import AttentionWithElmo, SquadContextConcatSkip
from docqa.model_dir import ModelDir
from docqa.nn.attention import BiAttention, StaticAttentionSelf
from docqa.nn.embedder import FixedWordEmbedder, CharWordEmbedder, LearnedCharEmbedder, LearnedSubstringEmbedder, \
FilteredFixedWordEmbedder
from docqa.nn.layers import FullyConnected, ChainBiMapper, NullBiMapper, MaxPool, Conv1d, SequenceMapperSeq, \
VariationalDropoutLayer, ResidualLayer, ConcatWithProduct, MapperSeq, DropoutLayer
from docqa.nn.recurrent_layers import CudnnGru
from docqa.nn.similarity_layers import TriLinear
from docqa.nn.span_prediction import BoundsPredictor
from docqa.squad.squad_data import SquadCorpus, DocumentQaTrainingData
def main():
parser = argparse.ArgumentParser("Train our ELMo model on SQuAD")
parser.add_argument("output_dir")
parser.add_argument("--dim", type=int, default=90)
parser.add_argument("--l2", type=float, default=0)
parser.add_argument("--mode", choices=["input", "output", "both", "none"], default="both")
parser.add_argument("--top_layer_only", action="store_true")
#parser.add_argument("--combination", choices=["x, y", "x * y", "x, y, x * y"], default="x, y")
parser.add_argument("--use_substring", type=str, default="None")
parser.add_argument("--sub_dim", type=int, default=50)
args = parser.parse_args()
print(args)
out = args.output_dir + "-" + datetime.now().strftime("%m%d-%H%M%S")
dim = args.dim
recurrent_layer = CudnnGru(dim, w_init=TruncatedNormal(stddev=0.05))
params = trainer.TrainParams(trainer.SerializableOptimizer("Adadelta", dict(learning_rate=1.0)),
ema=0.999, max_checkpoints_to_keep=2, async_encoding=10,
num_epochs=24, log_period=30, eval_period=1200, save_period=1200,
best_weights=("dev", "b17/text-f1"),
eval_samples=dict(dev=None, train=8000))
lm_reduce = MapperSeq(
ElmoLayer(args.l2, layer_norm=False, top_layer_only=args.top_layer_only),
DropoutLayer(0.5),
)
CharEmbedderCls, EncoderCls = (LearnedCharEmbedder, DocumentAndQuestionEncoder) if args.use_substring == "None" \
else (LearnedSubstringEmbedder, DocumentAndQuestionEncoderWithSubstring)
charEmbedder = CharEmbedderCls(word_size_th=14, char_th=20, char_dim=args.sub_dim, init_scale=0.05, force_cpu=True)
if args.use_substring != None:
charEmbedder._load_substring_vocab(args.use_substring)
final_sub_dim = 100 #if args.combination == "x, y" else 300
model = AttentionWithElmo(
#combination=args.combination,
encoder=EncoderCls(SingleSpanAnswerEncoder()),
lm_model=SquadContextConcatSkip(),
append_before_atten=(args.mode == "both" or args.mode == "output"),
append_embed=(args.mode == "both" or args.mode == "input"),
max_batch_size=128,
word_embed=FilteredFixedWordEmbedder(vec_name="glove.840B.300d", word_vec_init_scale=0, learn_unk=True, cpu=True),
char_embed=CharWordEmbedder(
charEmbedder,
MaxPool(Conv1d(final_sub_dim, 5, 0.8)),
shared_parameters=True
),
embed_mapper=SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
),
lm_reduce=None,
lm_reduce_shared=lm_reduce,
per_sentence=False,
memory_builder=NullBiMapper(),
attention=BiAttention(TriLinear(bias=True), True),
match_encoder=SequenceMapperSeq(FullyConnected(dim * 2, activation="relu"),
ResidualLayer(SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
StaticAttentionSelf(TriLinear(bias=True), ConcatWithProduct()),
FullyConnected(dim * 2, activation="relu"),
)),
VariationalDropoutLayer(0.8)),
predictor = BoundsPredictor(ChainBiMapper(
first_layer=recurrent_layer,
second_layer=recurrent_layer
))
)
batcher = ClusteredBatcher(45, ContextLenKey(), False, False)
data = DocumentQaTrainingData(SquadCorpus(), None, batcher, batcher)
with open(__file__, "r") as f:
notes = f.read()
notes = str(sorted(args.__dict__.items(), key=lambda x:x[0])) + "\n" + notes
trainer.start_training(data, model, params,
[LossEvaluator(), SpanEvaluator(bound=[17], text_eval="squad")],
ModelDir(out), notes)
if __name__ == "__main__":
main() | 49.336364 | 122 | 0.66206 | import argparse
from datetime import datetime
from tensorflow.contrib.keras.python.keras.initializers import TruncatedNormal
from docqa import trainer
from docqa.data_processing.qa_training_data import ContextLenKey
from docqa.dataset import ClusteredBatcher
from docqa.encoder import DocumentAndQuestionEncoder, SingleSpanAnswerEncoder, DocumentAndQuestionEncoderWithSubstring
from docqa.evaluator import LossEvaluator, SpanEvaluator
from docqa.elmo.elmo import ElmoLayer
from docqa.elmo.lm_qa_models import AttentionWithElmo, SquadContextConcatSkip
from docqa.model_dir import ModelDir
from docqa.nn.attention import BiAttention, StaticAttentionSelf
from docqa.nn.embedder import FixedWordEmbedder, CharWordEmbedder, LearnedCharEmbedder, LearnedSubstringEmbedder, \
FilteredFixedWordEmbedder
from docqa.nn.layers import FullyConnected, ChainBiMapper, NullBiMapper, MaxPool, Conv1d, SequenceMapperSeq, \
VariationalDropoutLayer, ResidualLayer, ConcatWithProduct, MapperSeq, DropoutLayer
from docqa.nn.recurrent_layers import CudnnGru
from docqa.nn.similarity_layers import TriLinear
from docqa.nn.span_prediction import BoundsPredictor
from docqa.squad.squad_data import SquadCorpus, DocumentQaTrainingData
def main():
parser = argparse.ArgumentParser("Train our ELMo model on SQuAD")
parser.add_argument("output_dir")
parser.add_argument("--dim", type=int, default=90)
parser.add_argument("--l2", type=float, default=0)
parser.add_argument("--mode", choices=["input", "output", "both", "none"], default="both")
parser.add_argument("--top_layer_only", action="store_true")
parser.add_argument("--use_substring", type=str, default="None")
parser.add_argument("--sub_dim", type=int, default=50)
args = parser.parse_args()
print(args)
out = args.output_dir + "-" + datetime.now().strftime("%m%d-%H%M%S")
dim = args.dim
recurrent_layer = CudnnGru(dim, w_init=TruncatedNormal(stddev=0.05))
params = trainer.TrainParams(trainer.SerializableOptimizer("Adadelta", dict(learning_rate=1.0)),
ema=0.999, max_checkpoints_to_keep=2, async_encoding=10,
num_epochs=24, log_period=30, eval_period=1200, save_period=1200,
best_weights=("dev", "b17/text-f1"),
eval_samples=dict(dev=None, train=8000))
lm_reduce = MapperSeq(
ElmoLayer(args.l2, layer_norm=False, top_layer_only=args.top_layer_only),
DropoutLayer(0.5),
)
CharEmbedderCls, EncoderCls = (LearnedCharEmbedder, DocumentAndQuestionEncoder) if args.use_substring == "None" \
else (LearnedSubstringEmbedder, DocumentAndQuestionEncoderWithSubstring)
charEmbedder = CharEmbedderCls(word_size_th=14, char_th=20, char_dim=args.sub_dim, init_scale=0.05, force_cpu=True)
if args.use_substring != None:
charEmbedder._load_substring_vocab(args.use_substring)
final_sub_dim = 100
model = AttentionWithElmo(
encoder=EncoderCls(SingleSpanAnswerEncoder()),
lm_model=SquadContextConcatSkip(),
append_before_atten=(args.mode == "both" or args.mode == "output"),
append_embed=(args.mode == "both" or args.mode == "input"),
max_batch_size=128,
word_embed=FilteredFixedWordEmbedder(vec_name="glove.840B.300d", word_vec_init_scale=0, learn_unk=True, cpu=True),
char_embed=CharWordEmbedder(
charEmbedder,
MaxPool(Conv1d(final_sub_dim, 5, 0.8)),
shared_parameters=True
),
embed_mapper=SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
),
lm_reduce=None,
lm_reduce_shared=lm_reduce,
per_sentence=False,
memory_builder=NullBiMapper(),
attention=BiAttention(TriLinear(bias=True), True),
match_encoder=SequenceMapperSeq(FullyConnected(dim * 2, activation="relu"),
ResidualLayer(SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
StaticAttentionSelf(TriLinear(bias=True), ConcatWithProduct()),
FullyConnected(dim * 2, activation="relu"),
)),
VariationalDropoutLayer(0.8)),
predictor = BoundsPredictor(ChainBiMapper(
first_layer=recurrent_layer,
second_layer=recurrent_layer
))
)
batcher = ClusteredBatcher(45, ContextLenKey(), False, False)
data = DocumentQaTrainingData(SquadCorpus(), None, batcher, batcher)
with open(__file__, "r") as f:
notes = f.read()
notes = str(sorted(args.__dict__.items(), key=lambda x:x[0])) + "\n" + notes
trainer.start_training(data, model, params,
[LossEvaluator(), SpanEvaluator(bound=[17], text_eval="squad")],
ModelDir(out), notes)
if __name__ == "__main__":
main() | true | true |
f71bad585be1228c36c8e571afcf7ee1c2112342 | 37,542 | py | Python | ckan/controllers/group.py | smth/ckan | 89d52c1dfc7880f7dd020d87b862870c07005dd2 | [
"Apache-2.0"
] | 3 | 2019-07-20T14:05:48.000Z | 2019-08-04T18:08:45.000Z | ckan/controllers/group.py | smth/ckan | 89d52c1dfc7880f7dd020d87b862870c07005dd2 | [
"Apache-2.0"
] | 29 | 2015-10-30T23:39:14.000Z | 2018-04-05T06:35:01.000Z | ckan/controllers/group.py | eawag-rdm/eawag-ckan | 4016bacb3d311478211428f3c71be2582627f273 | [
"Apache-2.0"
] | 5 | 2017-04-06T21:18:38.000Z | 2020-03-30T17:05:23.000Z | # encoding: utf-8
import logging
import datetime
from urllib import urlencode
from pylons.i18n import get_lang
import ckan.lib.base as base
import ckan.lib.helpers as h
import ckan.lib.navl.dictization_functions as dict_fns
import ckan.logic as logic
import ckan.lib.search as search
import ckan.model as model
import ckan.authz as authz
import ckan.lib.plugins
import ckan.plugins as plugins
from ckan.common import OrderedDict, c, config, request, _
log = logging.getLogger(__name__)
render = base.render
abort = base.abort
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
check_access = logic.check_access
get_action = logic.get_action
tuplize_dict = logic.tuplize_dict
clean_dict = logic.clean_dict
parse_params = logic.parse_params
lookup_group_plugin = ckan.lib.plugins.lookup_group_plugin
lookup_group_controller = ckan.lib.plugins.lookup_group_controller
class GroupController(base.BaseController):
group_types = ['group']
# hooks for subclasses
def _group_form(self, group_type=None):
return lookup_group_plugin(group_type).group_form()
def _form_to_db_schema(self, group_type=None):
return lookup_group_plugin(group_type).form_to_db_schema()
def _db_to_form_schema(self, group_type=None):
'''This is an interface to manipulate data from the database
into a format suitable for the form (optional)'''
return lookup_group_plugin(group_type).db_to_form_schema()
def _setup_template_variables(self, context, data_dict, group_type=None):
return lookup_group_plugin(group_type).\
setup_template_variables(context, data_dict)
def _new_template(self, group_type):
return lookup_group_plugin(group_type).new_template()
def _index_template(self, group_type):
return lookup_group_plugin(group_type).index_template()
def _about_template(self, group_type):
return lookup_group_plugin(group_type).about_template()
def _read_template(self, group_type):
return lookup_group_plugin(group_type).read_template()
def _history_template(self, group_type):
return lookup_group_plugin(group_type).history_template()
def _edit_template(self, group_type):
return lookup_group_plugin(group_type).edit_template()
def _activity_template(self, group_type):
return lookup_group_plugin(group_type).activity_template()
def _admins_template(self, group_type):
return lookup_group_plugin(group_type).admins_template()
def _bulk_process_template(self, group_type):
return lookup_group_plugin(group_type).bulk_process_template()
# end hooks
def _replace_group_org(self, string):
''' substitute organization for group if this is an org'''
return string
def _action(self, action_name):
''' select the correct group/org action '''
return get_action(self._replace_group_org(action_name))
def _check_access(self, action_name, *args, **kw):
''' select the correct group/org check_access '''
return check_access(self._replace_group_org(action_name), *args, **kw)
def _render_template(self, template_name, group_type):
''' render the correct group/org template '''
return render(self._replace_group_org(template_name),
extra_vars={'group_type': group_type})
def _redirect_to_this_controller(self, *args, **kw):
''' wrapper around redirect_to but it adds in this request's controller
(so that it works for Organization or other derived controllers)'''
kw['controller'] = request.environ['pylons.routes_dict']['controller']
return h.redirect_to(*args, **kw)
def _url_for_this_controller(self, *args, **kw):
''' wrapper around url_for but it adds in this request's controller
(so that it works for Organization or other derived controllers)'''
kw['controller'] = request.environ['pylons.routes_dict']['controller']
return h.url_for(*args, **kw)
def _guess_group_type(self, expecting_name=False):
"""
Guess the type of group from the URL.
* The default url '/group/xyz' returns None
* group_type is unicode
* this handles the case where there is a prefix on the URL
(such as /data/organization)
"""
parts = [x for x in request.path.split('/') if x]
idx = -1
if expecting_name:
idx = -2
gt = parts[idx]
return gt
def _ensure_controller_matches_group_type(self, id):
group = model.Group.get(id)
if group is None:
abort(404, _('Group not found'))
if group.type not in self.group_types:
abort(404, _('Incorrect group type'))
return group.type
@classmethod
def add_group_type(cls, group_type):
''' Notify this controller that it is to be used for a particular
group_type. (Called on plugin registration.)
'''
cls.group_types.append(group_type)
def index(self):
group_type = self._guess_group_type()
page = h.get_page_number(request.params) or 1
items_per_page = 21
context = {'model': model, 'session': model.Session,
'user': c.user, 'for_view': True,
'with_private': False}
q = c.q = request.params.get('q', '')
sort_by = c.sort_by_selected = request.params.get('sort')
try:
self._check_access('site_read', context)
self._check_access('group_list', context)
except NotAuthorized:
abort(403, _('Not authorized to see this page'))
# pass user info to context as needed to view private datasets of
# orgs correctly
if c.userobj:
context['user_id'] = c.userobj.id
context['user_is_admin'] = c.userobj.sysadmin
try:
data_dict_global_results = {
'all_fields': False,
'q': q,
'sort': sort_by,
'type': group_type or 'group',
}
global_results = self._action('group_list')(
context, data_dict_global_results)
except ValidationError as e:
if e.error_dict and e.error_dict.get('message'):
msg = e.error_dict['message']
else:
msg = str(e)
h.flash_error(msg)
c.page = h.Page([], 0)
return render(self._index_template(group_type),
extra_vars={'group_type': group_type})
data_dict_page_results = {
'all_fields': True,
'q': q,
'sort': sort_by,
'type': group_type or 'group',
'limit': items_per_page,
'offset': items_per_page * (page - 1),
'include_extras': True
}
page_results = self._action('group_list')(context,
data_dict_page_results)
c.page = h.Page(
collection=global_results,
page=page,
url=h.pager_url,
items_per_page=items_per_page,
)
c.page.items = page_results
return render(self._index_template(group_type),
extra_vars={'group_type': group_type})
def read(self, id, limit=20):
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True}
data_dict = {'id': id, 'type': group_type}
# unicode format (decoded from utf8)
c.q = request.params.get('q', '')
try:
# Do not query for the group datasets when dictizing, as they will
# be ignored and get requested on the controller anyway
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.group = context['group']
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
self._read(id, limit, group_type)
return render(self._read_template(c.group_dict['type']),
extra_vars={'group_type': group_type})
def _read(self, id, limit, group_type):
''' This is common code used by both read and bulk_process'''
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True, 'extras_as_string': True}
q = c.q = request.params.get('q', '')
# Search within group
if c.group_dict.get('is_organization'):
q += ' owner_org:"%s"' % c.group_dict.get('id')
else:
q += ' groups:"%s"' % c.group_dict.get('name')
c.description_formatted = \
h.render_markdown(c.group_dict.get('description'))
context['return_query'] = True
page = h.get_page_number(request.params)
# most search operations should reset the page counter:
params_nopage = [(k, v) for k, v in request.params.items()
if k != 'page']
sort_by = request.params.get('sort', None)
def search_url(params):
controller = lookup_group_controller(group_type)
action = 'bulk_process' if c.action == 'bulk_process' else 'read'
url = h.url_for(controller=controller, action=action, id=id)
params = [(k, v.encode('utf-8') if isinstance(v, basestring)
else str(v)) for k, v in params]
return url + u'?' + urlencode(params)
def drill_down_url(**by):
return h.add_url_param(alternative_url=None,
controller='group', action='read',
extras=dict(id=c.group_dict.get('name')),
new_params=by)
c.drill_down_url = drill_down_url
def remove_field(key, value=None, replace=None):
controller = lookup_group_controller(group_type)
return h.remove_url_param(key, value=value, replace=replace,
controller=controller, action='read',
extras=dict(id=c.group_dict.get('name')))
c.remove_field = remove_field
def pager_url(q=None, page=None):
params = list(params_nopage)
params.append(('page', page))
return search_url(params)
try:
c.fields = []
c.fields_grouped = {}
search_extras = {}
for (param, value) in request.params.items():
if param not in ['q', 'page', 'sort'] \
and len(value) and not param.startswith('_'):
if not param.startswith('ext_'):
c.fields.append((param, value))
q += ' %s: "%s"' % (param, value)
if param not in c.fields_grouped:
c.fields_grouped[param] = [value]
else:
c.fields_grouped[param].append(value)
else:
search_extras[param] = value
facets = OrderedDict()
default_facet_titles = {'organization': _('Organizations'),
'groups': _('Groups'),
'tags': _('Tags'),
'res_format': _('Formats'),
'license_id': _('Licenses')}
for facet in h.facets():
if facet in default_facet_titles:
facets[facet] = default_facet_titles[facet]
else:
facets[facet] = facet
# Facet titles
self._update_facet_titles(facets, group_type)
c.facet_titles = facets
data_dict = {
'q': q,
'fq': '',
'include_private': True,
'facet.field': facets.keys(),
'rows': limit,
'sort': sort_by,
'start': (page - 1) * limit,
'extras': search_extras
}
context_ = dict((k, v) for (k, v) in context.items()
if k != 'schema')
query = get_action('package_search')(context_, data_dict)
c.page = h.Page(
collection=query['results'],
page=page,
url=pager_url,
item_count=query['count'],
items_per_page=limit
)
c.group_dict['package_count'] = query['count']
c.search_facets = query['search_facets']
c.search_facets_limits = {}
for facet in c.search_facets.keys():
limit = int(request.params.get('_%s_limit' % facet,
config.get('search.facets.default', 10)))
c.search_facets_limits[facet] = limit
c.page.items = query['results']
c.sort_by_selected = sort_by
except search.SearchError, se:
log.error('Group search error: %r', se.args)
c.query_error = True
c.page = h.Page(collection=[])
self._setup_template_variables(context, {'id': id},
group_type=group_type)
def _update_facet_titles(self, facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
facets = plugin.group_facets(
facets, group_type, None)
def bulk_process(self, id):
''' Allow bulk processing of datasets for an organization. Make
private/public or delete. For organization admins.'''
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
# check we are org admin
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True, 'extras_as_string': True}
data_dict = {'id': id, 'type': group_type}
try:
self._check_access('bulk_update_public', context, {'org_id': id})
# Do not query for the group datasets when dictizing, as they will
# be ignored and get requested on the controller anyway
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.group = context['group']
except NotFound:
abort(404, _('Group not found'))
except NotAuthorized:
abort(403, _('User %r not authorized to edit %s') % (c.user, id))
if not c.group_dict['is_organization']:
# FIXME: better error
raise Exception('Must be an organization')
# use different form names so that ie7 can be detected
form_names = set(["bulk_action.public", "bulk_action.delete",
"bulk_action.private"])
actions_in_form = set(request.params.keys())
actions = form_names.intersection(actions_in_form)
# If no action then just show the datasets
if not actions:
# unicode format (decoded from utf8)
limit = 500
self._read(id, limit, group_type)
c.packages = c.page.items
return render(self._bulk_process_template(group_type),
extra_vars={'group_type': group_type})
# ie7 puts all buttons in form params but puts submitted one twice
for key, value in dict(request.params.dict_of_lists()).items():
if len(value) == 2:
action = key.split('.')[-1]
break
else:
# normal good browser form submission
action = actions.pop().split('.')[-1]
# process the action first find the datasets to perform the action on.
# they are prefixed by dataset_ in the form data
datasets = []
for param in request.params:
if param.startswith('dataset_'):
datasets.append(param[8:])
action_functions = {
'private': 'bulk_update_private',
'public': 'bulk_update_public',
'delete': 'bulk_update_delete',
}
data_dict = {'datasets': datasets, 'org_id': c.group_dict['id']}
try:
get_action(action_functions[action])(context, data_dict)
except NotAuthorized:
abort(403, _('Not authorized to perform bulk update'))
self._redirect_to_this_controller(action='bulk_process', id=id)
def new(self, data=None, errors=None, error_summary=None):
if data and 'type' in data:
group_type = data['type']
else:
group_type = self._guess_group_type(True)
if data:
data['type'] = group_type
context = {'model': model, 'session': model.Session,
'user': c.user,
'save': 'save' in request.params,
'parent': request.params.get('parent', None)}
try:
self._check_access('group_create', context)
except NotAuthorized:
abort(403, _('Unauthorized to create a group'))
if context['save'] and not data:
return self._save_new(context, group_type)
data = data or {}
if not data.get('image_url', '').startswith('http'):
data.pop('image_url', None)
errors = errors or {}
error_summary = error_summary or {}
vars = {'data': data, 'errors': errors,
'error_summary': error_summary, 'action': 'new',
'group_type': group_type}
self._setup_template_variables(context, data, group_type=group_type)
c.form = render(self._group_form(group_type=group_type),
extra_vars=vars)
return render(self._new_template(group_type),
extra_vars={'group_type': group_type})
def edit(self, id, data=None, errors=None, error_summary=None):
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
context = {'model': model, 'session': model.Session,
'user': c.user,
'save': 'save' in request.params,
'for_edit': True,
'parent': request.params.get('parent', None)
}
data_dict = {'id': id, 'include_datasets': False}
if context['save'] and not data:
return self._save_edit(id, context)
try:
data_dict['include_datasets'] = False
old_data = self._action('group_show')(context, data_dict)
c.grouptitle = old_data.get('title')
c.groupname = old_data.get('name')
data = data or old_data
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
group = context.get("group")
c.group = group
c.group_dict = self._action('group_show')(context, data_dict)
try:
self._check_access('group_update', context)
except NotAuthorized:
abort(403, _('User %r not authorized to edit %s') % (c.user, id))
errors = errors or {}
vars = {'data': data, 'errors': errors,
'error_summary': error_summary, 'action': 'edit',
'group_type': group_type}
self._setup_template_variables(context, data, group_type=group_type)
c.form = render(self._group_form(group_type), extra_vars=vars)
return render(self._edit_template(c.group.type),
extra_vars={'group_type': group_type})
def _save_new(self, context, group_type=None):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
data_dict['type'] = group_type or 'group'
context['message'] = data_dict.get('log_message', '')
data_dict['users'] = [{'name': c.user, 'capacity': 'admin'}]
group = self._action('group_create')(context, data_dict)
# Redirect to the appropriate _read route for the type of group
h.redirect_to(group['type'] + '_read', id=group['name'])
except (NotFound, NotAuthorized), e:
abort(404, _('Group not found'))
except dict_fns.DataError:
abort(400, _(u'Integrity Error'))
except ValidationError, e:
errors = e.error_dict
error_summary = e.error_summary
return self.new(data_dict, errors, error_summary)
def _force_reindex(self, grp):
''' When the group name has changed, we need to force a reindex
of the datasets within the group, otherwise they will stop
appearing on the read page for the group (as they're connected via
the group name)'''
group = model.Group.get(grp['name'])
for dataset in group.packages():
search.rebuild(dataset.name)
def _save_edit(self, id, context):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
context['message'] = data_dict.get('log_message', '')
data_dict['id'] = id
context['allow_partial_update'] = True
group = self._action('group_update')(context, data_dict)
if id != group['name']:
self._force_reindex(group)
h.redirect_to('%s_read' % group['type'], id=group['name'])
except (NotFound, NotAuthorized), e:
abort(404, _('Group not found'))
except dict_fns.DataError:
abort(400, _(u'Integrity Error'))
except ValidationError, e:
errors = e.error_dict
error_summary = e.error_summary
return self.edit(id, data_dict, errors, error_summary)
def authz(self, id):
group = model.Group.get(id)
if group is None:
abort(404, _('Group not found'))
group_type = group.type
if group_type not in self.group_types:
abort(404, _('Incorrect group type'))
c.groupname = group.name
c.grouptitle = group.display_name
try:
context = \
{'model': model, 'user': c.user, 'group': group}
self._check_access('group_edit_permissions', context)
c.authz_editable = True
c.group = context['group']
except NotAuthorized:
c.authz_editable = False
if not c.authz_editable:
abort(403,
_('User %r not authorized to edit %s authorizations') %
(c.user, id))
roles = self._handle_update_of_authz(group)
self._prepare_authz_info_for_render(roles)
return render('group/authz.html',
extra_vars={'group_type': group_type})
def delete(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'cancel' in request.params:
self._redirect_to_this_controller(action='edit', id=id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_delete', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s') % '')
try:
if request.method == 'POST':
self._action('group_delete')(context, {'id': id})
if group_type == 'organization':
h.flash_notice(_('Organization has been deleted.'))
elif group_type == 'group':
h.flash_notice(_('Group has been deleted.'))
else:
h.flash_notice(_('%s has been deleted.')
% _(group_type.capitalize()))
self._redirect_to_this_controller(action='index')
c.group_dict = self._action('group_show')(context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s') % '')
except NotFound:
abort(404, _('Group not found'))
except ValidationError as e:
h.flash_error(e.error_dict['message'])
h.redirect_to(controller='organization', action='read', id=id)
return self._render_template('group/confirm_delete.html', group_type)
def members(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
data_dict = {'id': id}
check_access('group_edit_permissions', context, data_dict)
c.members = self._action('member_list')(
context, {'id': id, 'object_type': 'user'}
)
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
except NotFound:
abort(404, _('Group not found'))
except NotAuthorized:
abort(
403,
_('User %r not authorized to edit members of %s') % (
c.user, id))
return self._render_template('group/members.html', group_type)
def member_new(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_member_create', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to create group %s members') % '')
try:
data_dict = {'id': id}
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.roles = self._action('member_roles_list')(
context, {'group_type': group_type}
)
if request.method == 'POST':
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
data_dict['id'] = id
email = data_dict.get('email')
if email:
user_data_dict = {
'email': email,
'group_id': data_dict['id'],
'role': data_dict['role']
}
del data_dict['email']
user_dict = self._action('user_invite')(
context, user_data_dict)
data_dict['username'] = user_dict['name']
c.group_dict = self._action('group_member_create')(
context, data_dict)
self._redirect_to_this_controller(action='members', id=id)
else:
user = request.params.get('user')
if user:
c.user_dict = \
get_action('user_show')(context, {'id': user})
c.user_role = \
authz.users_role_for_group_or_org(id, user) or 'member'
else:
c.user_role = 'member'
except NotAuthorized:
abort(403, _('Unauthorized to add member to group %s') % '')
except NotFound:
abort(404, _('Group not found'))
except ValidationError, e:
h.flash_error(e.error_summary)
return self._render_template('group/member_new.html', group_type)
def member_delete(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'cancel' in request.params:
self._redirect_to_this_controller(action='members', id=id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_member_delete', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s members') % '')
try:
user_id = request.params.get('user')
if request.method == 'POST':
self._action('group_member_delete')(
context, {'id': id, 'user_id': user_id})
h.flash_notice(_('Group member has been deleted.'))
self._redirect_to_this_controller(action='members', id=id)
c.user_dict = self._action('user_show')(context, {'id': user_id})
c.user_id = user_id
c.group_id = id
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s members') % '')
except NotFound:
abort(404, _('Group not found'))
return self._render_template('group/confirm_delete_member.html',
group_type)
def history(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'diff' in request.params or 'selected1' in request.params:
try:
params = {'id': request.params.getone('group_name'),
'diff': request.params.getone('selected1'),
'oldid': request.params.getone('selected2'),
}
except KeyError:
if 'group_name' in dict(request.params):
id = request.params.getone('group_name')
c.error = \
_('Select two revisions before doing the comparison.')
else:
params['diff_entity'] = 'group'
h.redirect_to(controller='revision', action='diff', **params)
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema()}
data_dict = {'id': id}
try:
c.group_dict = self._action('group_show')(context, data_dict)
c.group_revisions = self._action('group_revision_list')(context,
data_dict)
# TODO: remove
# Still necessary for the authz check in group/layout.html
c.group = context['group']
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
format = request.params.get('format', '')
if format == 'atom':
# Generate and return Atom 1.0 document.
from webhelpers.feedgenerator import Atom1Feed
feed = Atom1Feed(
title=_(u'CKAN Group Revision History'),
link=self._url_for_this_controller(
action='read',
id=c.group_dict['name']),
description=_(u'Recent changes to CKAN Group: ') +
c.group_dict['display_name'],
language=unicode(get_lang()),
)
for revision_dict in c.group_revisions:
revision_date = h.date_str_to_datetime(
revision_dict['timestamp'])
try:
dayHorizon = int(request.params.get('days'))
except:
dayHorizon = 30
dayAge = (datetime.datetime.now() - revision_date).days
if dayAge >= dayHorizon:
break
if revision_dict['message']:
item_title = u'%s' % revision_dict['message'].\
split('\n')[0]
else:
item_title = u'%s' % revision_dict['id']
item_link = h.url_for(controller='revision', action='read',
id=revision_dict['id'])
item_description = _('Log message: ')
item_description += '%s' % (revision_dict['message'] or '')
item_author_name = revision_dict['author']
item_pubdate = revision_date
feed.add_item(
title=item_title,
link=item_link,
description=item_description,
author_name=item_author_name,
pubdate=item_pubdate,
)
feed.content_type = 'application/atom+xml'
return feed.writeString('utf-8')
return render(self._history_template(group_type),
extra_vars={'group_type': group_type})
def activity(self, id, offset=0):
'''Render this group's public activity stream page.'''
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user, 'for_view': True}
try:
c.group_dict = self._get_group_dict(id)
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
try:
# Add the group's activity stream (already rendered to HTML) to the
# template context for the group/read.html
# template to retrieve later.
c.group_activity_stream = self._action('group_activity_list_html')(
context, {'id': c.group_dict['id'], 'offset': offset})
except ValidationError as error:
base.abort(400)
return render(self._activity_template(group_type),
extra_vars={'group_type': group_type})
def follow(self, id):
'''Start following this group.'''
self._ensure_controller_matches_group_type(id)
context = {'model': model,
'session': model.Session,
'user': c.user}
data_dict = {'id': id}
try:
get_action('follow_group')(context, data_dict)
group_dict = get_action('group_show')(context, data_dict)
h.flash_success(_("You are now following {0}").format(
group_dict['title']))
except ValidationError as e:
error_message = (e.message or e.error_summary
or e.error_dict)
h.flash_error(error_message)
except NotAuthorized as e:
h.flash_error(e.message)
h.redirect_to(controller='group', action='read', id=id)
def unfollow(self, id):
'''Stop following this group.'''
self._ensure_controller_matches_group_type(id)
context = {'model': model,
'session': model.Session,
'user': c.user}
data_dict = {'id': id}
try:
get_action('unfollow_group')(context, data_dict)
group_dict = get_action('group_show')(context, data_dict)
h.flash_success(_("You are no longer following {0}").format(
group_dict['title']))
except ValidationError as e:
error_message = (e.message or e.error_summary
or e.error_dict)
h.flash_error(error_message)
except (NotFound, NotAuthorized) as e:
error_message = e.message
h.flash_error(error_message)
h.redirect_to(controller='group', action='read', id=id)
def followers(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
c.group_dict = self._get_group_dict(id)
try:
c.followers = \
get_action('group_follower_list')(context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to view followers %s') % '')
return render('group/followers.html',
extra_vars={'group_type': group_type})
def admins(self, id):
group_type = self._ensure_controller_matches_group_type(id)
c.group_dict = self._get_group_dict(id)
c.admins = authz.get_group_or_org_admin_ids(id)
return render(self._admins_template(c.group_dict['type']),
extra_vars={'group_type': group_type})
def about(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
c.group_dict = self._get_group_dict(id)
group_type = c.group_dict['type']
self._setup_template_variables(context, {'id': id},
group_type=group_type)
return render(self._about_template(group_type),
extra_vars={'group_type': group_type})
def _get_group_dict(self, id):
''' returns the result of group_show action or aborts if there is a
problem '''
context = {'model': model, 'session': model.Session,
'user': c.user,
'for_view': True}
try:
return self._action('group_show')(
context, {'id': id, 'include_datasets': False})
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
| 39.811241 | 79 | 0.561451 |
import logging
import datetime
from urllib import urlencode
from pylons.i18n import get_lang
import ckan.lib.base as base
import ckan.lib.helpers as h
import ckan.lib.navl.dictization_functions as dict_fns
import ckan.logic as logic
import ckan.lib.search as search
import ckan.model as model
import ckan.authz as authz
import ckan.lib.plugins
import ckan.plugins as plugins
from ckan.common import OrderedDict, c, config, request, _
log = logging.getLogger(__name__)
render = base.render
abort = base.abort
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
check_access = logic.check_access
get_action = logic.get_action
tuplize_dict = logic.tuplize_dict
clean_dict = logic.clean_dict
parse_params = logic.parse_params
lookup_group_plugin = ckan.lib.plugins.lookup_group_plugin
lookup_group_controller = ckan.lib.plugins.lookup_group_controller
class GroupController(base.BaseController):
group_types = ['group']
def _group_form(self, group_type=None):
return lookup_group_plugin(group_type).group_form()
def _form_to_db_schema(self, group_type=None):
return lookup_group_plugin(group_type).form_to_db_schema()
def _db_to_form_schema(self, group_type=None):
'''This is an interface to manipulate data from the database
into a format suitable for the form (optional)'''
return lookup_group_plugin(group_type).db_to_form_schema()
def _setup_template_variables(self, context, data_dict, group_type=None):
return lookup_group_plugin(group_type).\
setup_template_variables(context, data_dict)
def _new_template(self, group_type):
return lookup_group_plugin(group_type).new_template()
def _index_template(self, group_type):
return lookup_group_plugin(group_type).index_template()
def _about_template(self, group_type):
return lookup_group_plugin(group_type).about_template()
def _read_template(self, group_type):
return lookup_group_plugin(group_type).read_template()
def _history_template(self, group_type):
return lookup_group_plugin(group_type).history_template()
def _edit_template(self, group_type):
return lookup_group_plugin(group_type).edit_template()
def _activity_template(self, group_type):
return lookup_group_plugin(group_type).activity_template()
def _admins_template(self, group_type):
return lookup_group_plugin(group_type).admins_template()
def _bulk_process_template(self, group_type):
return lookup_group_plugin(group_type).bulk_process_template()
def _replace_group_org(self, string):
''' substitute organization for group if this is an org'''
return string
def _action(self, action_name):
''' select the correct group/org action '''
return get_action(self._replace_group_org(action_name))
def _check_access(self, action_name, *args, **kw):
''' select the correct group/org check_access '''
return check_access(self._replace_group_org(action_name), *args, **kw)
def _render_template(self, template_name, group_type):
''' render the correct group/org template '''
return render(self._replace_group_org(template_name),
extra_vars={'group_type': group_type})
def _redirect_to_this_controller(self, *args, **kw):
''' wrapper around redirect_to but it adds in this request's controller
(so that it works for Organization or other derived controllers)'''
kw['controller'] = request.environ['pylons.routes_dict']['controller']
return h.redirect_to(*args, **kw)
def _url_for_this_controller(self, *args, **kw):
''' wrapper around url_for but it adds in this request's controller
(so that it works for Organization or other derived controllers)'''
kw['controller'] = request.environ['pylons.routes_dict']['controller']
return h.url_for(*args, **kw)
def _guess_group_type(self, expecting_name=False):
"""
Guess the type of group from the URL.
* The default url '/group/xyz' returns None
* group_type is unicode
* this handles the case where there is a prefix on the URL
(such as /data/organization)
"""
parts = [x for x in request.path.split('/') if x]
idx = -1
if expecting_name:
idx = -2
gt = parts[idx]
return gt
def _ensure_controller_matches_group_type(self, id):
group = model.Group.get(id)
if group is None:
abort(404, _('Group not found'))
if group.type not in self.group_types:
abort(404, _('Incorrect group type'))
return group.type
@classmethod
def add_group_type(cls, group_type):
''' Notify this controller that it is to be used for a particular
group_type. (Called on plugin registration.)
'''
cls.group_types.append(group_type)
def index(self):
group_type = self._guess_group_type()
page = h.get_page_number(request.params) or 1
items_per_page = 21
context = {'model': model, 'session': model.Session,
'user': c.user, 'for_view': True,
'with_private': False}
q = c.q = request.params.get('q', '')
sort_by = c.sort_by_selected = request.params.get('sort')
try:
self._check_access('site_read', context)
self._check_access('group_list', context)
except NotAuthorized:
abort(403, _('Not authorized to see this page'))
if c.userobj:
context['user_id'] = c.userobj.id
context['user_is_admin'] = c.userobj.sysadmin
try:
data_dict_global_results = {
'all_fields': False,
'q': q,
'sort': sort_by,
'type': group_type or 'group',
}
global_results = self._action('group_list')(
context, data_dict_global_results)
except ValidationError as e:
if e.error_dict and e.error_dict.get('message'):
msg = e.error_dict['message']
else:
msg = str(e)
h.flash_error(msg)
c.page = h.Page([], 0)
return render(self._index_template(group_type),
extra_vars={'group_type': group_type})
data_dict_page_results = {
'all_fields': True,
'q': q,
'sort': sort_by,
'type': group_type or 'group',
'limit': items_per_page,
'offset': items_per_page * (page - 1),
'include_extras': True
}
page_results = self._action('group_list')(context,
data_dict_page_results)
c.page = h.Page(
collection=global_results,
page=page,
url=h.pager_url,
items_per_page=items_per_page,
)
c.page.items = page_results
return render(self._index_template(group_type),
extra_vars={'group_type': group_type})
def read(self, id, limit=20):
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True}
data_dict = {'id': id, 'type': group_type}
c.q = request.params.get('q', '')
try:
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.group = context['group']
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
self._read(id, limit, group_type)
return render(self._read_template(c.group_dict['type']),
extra_vars={'group_type': group_type})
def _read(self, id, limit, group_type):
''' This is common code used by both read and bulk_process'''
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True, 'extras_as_string': True}
q = c.q = request.params.get('q', '')
if c.group_dict.get('is_organization'):
q += ' owner_org:"%s"' % c.group_dict.get('id')
else:
q += ' groups:"%s"' % c.group_dict.get('name')
c.description_formatted = \
h.render_markdown(c.group_dict.get('description'))
context['return_query'] = True
page = h.get_page_number(request.params)
params_nopage = [(k, v) for k, v in request.params.items()
if k != 'page']
sort_by = request.params.get('sort', None)
def search_url(params):
controller = lookup_group_controller(group_type)
action = 'bulk_process' if c.action == 'bulk_process' else 'read'
url = h.url_for(controller=controller, action=action, id=id)
params = [(k, v.encode('utf-8') if isinstance(v, basestring)
else str(v)) for k, v in params]
return url + u'?' + urlencode(params)
def drill_down_url(**by):
return h.add_url_param(alternative_url=None,
controller='group', action='read',
extras=dict(id=c.group_dict.get('name')),
new_params=by)
c.drill_down_url = drill_down_url
def remove_field(key, value=None, replace=None):
controller = lookup_group_controller(group_type)
return h.remove_url_param(key, value=value, replace=replace,
controller=controller, action='read',
extras=dict(id=c.group_dict.get('name')))
c.remove_field = remove_field
def pager_url(q=None, page=None):
params = list(params_nopage)
params.append(('page', page))
return search_url(params)
try:
c.fields = []
c.fields_grouped = {}
search_extras = {}
for (param, value) in request.params.items():
if param not in ['q', 'page', 'sort'] \
and len(value) and not param.startswith('_'):
if not param.startswith('ext_'):
c.fields.append((param, value))
q += ' %s: "%s"' % (param, value)
if param not in c.fields_grouped:
c.fields_grouped[param] = [value]
else:
c.fields_grouped[param].append(value)
else:
search_extras[param] = value
facets = OrderedDict()
default_facet_titles = {'organization': _('Organizations'),
'groups': _('Groups'),
'tags': _('Tags'),
'res_format': _('Formats'),
'license_id': _('Licenses')}
for facet in h.facets():
if facet in default_facet_titles:
facets[facet] = default_facet_titles[facet]
else:
facets[facet] = facet
self._update_facet_titles(facets, group_type)
c.facet_titles = facets
data_dict = {
'q': q,
'fq': '',
'include_private': True,
'facet.field': facets.keys(),
'rows': limit,
'sort': sort_by,
'start': (page - 1) * limit,
'extras': search_extras
}
context_ = dict((k, v) for (k, v) in context.items()
if k != 'schema')
query = get_action('package_search')(context_, data_dict)
c.page = h.Page(
collection=query['results'],
page=page,
url=pager_url,
item_count=query['count'],
items_per_page=limit
)
c.group_dict['package_count'] = query['count']
c.search_facets = query['search_facets']
c.search_facets_limits = {}
for facet in c.search_facets.keys():
limit = int(request.params.get('_%s_limit' % facet,
config.get('search.facets.default', 10)))
c.search_facets_limits[facet] = limit
c.page.items = query['results']
c.sort_by_selected = sort_by
except search.SearchError, se:
log.error('Group search error: %r', se.args)
c.query_error = True
c.page = h.Page(collection=[])
self._setup_template_variables(context, {'id': id},
group_type=group_type)
def _update_facet_titles(self, facets, group_type):
for plugin in plugins.PluginImplementations(plugins.IFacets):
facets = plugin.group_facets(
facets, group_type, None)
def bulk_process(self, id):
''' Allow bulk processing of datasets for an organization. Make
private/public or delete. For organization admins.'''
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema(group_type=group_type),
'for_view': True, 'extras_as_string': True}
data_dict = {'id': id, 'type': group_type}
try:
self._check_access('bulk_update_public', context, {'org_id': id})
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.group = context['group']
except NotFound:
abort(404, _('Group not found'))
except NotAuthorized:
abort(403, _('User %r not authorized to edit %s') % (c.user, id))
if not c.group_dict['is_organization']:
raise Exception('Must be an organization')
form_names = set(["bulk_action.public", "bulk_action.delete",
"bulk_action.private"])
actions_in_form = set(request.params.keys())
actions = form_names.intersection(actions_in_form)
if not actions:
limit = 500
self._read(id, limit, group_type)
c.packages = c.page.items
return render(self._bulk_process_template(group_type),
extra_vars={'group_type': group_type})
for key, value in dict(request.params.dict_of_lists()).items():
if len(value) == 2:
action = key.split('.')[-1]
break
else:
action = actions.pop().split('.')[-1]
datasets = []
for param in request.params:
if param.startswith('dataset_'):
datasets.append(param[8:])
action_functions = {
'private': 'bulk_update_private',
'public': 'bulk_update_public',
'delete': 'bulk_update_delete',
}
data_dict = {'datasets': datasets, 'org_id': c.group_dict['id']}
try:
get_action(action_functions[action])(context, data_dict)
except NotAuthorized:
abort(403, _('Not authorized to perform bulk update'))
self._redirect_to_this_controller(action='bulk_process', id=id)
def new(self, data=None, errors=None, error_summary=None):
if data and 'type' in data:
group_type = data['type']
else:
group_type = self._guess_group_type(True)
if data:
data['type'] = group_type
context = {'model': model, 'session': model.Session,
'user': c.user,
'save': 'save' in request.params,
'parent': request.params.get('parent', None)}
try:
self._check_access('group_create', context)
except NotAuthorized:
abort(403, _('Unauthorized to create a group'))
if context['save'] and not data:
return self._save_new(context, group_type)
data = data or {}
if not data.get('image_url', '').startswith('http'):
data.pop('image_url', None)
errors = errors or {}
error_summary = error_summary or {}
vars = {'data': data, 'errors': errors,
'error_summary': error_summary, 'action': 'new',
'group_type': group_type}
self._setup_template_variables(context, data, group_type=group_type)
c.form = render(self._group_form(group_type=group_type),
extra_vars=vars)
return render(self._new_template(group_type),
extra_vars={'group_type': group_type})
def edit(self, id, data=None, errors=None, error_summary=None):
group_type = self._ensure_controller_matches_group_type(
id.split('@')[0])
context = {'model': model, 'session': model.Session,
'user': c.user,
'save': 'save' in request.params,
'for_edit': True,
'parent': request.params.get('parent', None)
}
data_dict = {'id': id, 'include_datasets': False}
if context['save'] and not data:
return self._save_edit(id, context)
try:
data_dict['include_datasets'] = False
old_data = self._action('group_show')(context, data_dict)
c.grouptitle = old_data.get('title')
c.groupname = old_data.get('name')
data = data or old_data
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
group = context.get("group")
c.group = group
c.group_dict = self._action('group_show')(context, data_dict)
try:
self._check_access('group_update', context)
except NotAuthorized:
abort(403, _('User %r not authorized to edit %s') % (c.user, id))
errors = errors or {}
vars = {'data': data, 'errors': errors,
'error_summary': error_summary, 'action': 'edit',
'group_type': group_type}
self._setup_template_variables(context, data, group_type=group_type)
c.form = render(self._group_form(group_type), extra_vars=vars)
return render(self._edit_template(c.group.type),
extra_vars={'group_type': group_type})
def _save_new(self, context, group_type=None):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
data_dict['type'] = group_type or 'group'
context['message'] = data_dict.get('log_message', '')
data_dict['users'] = [{'name': c.user, 'capacity': 'admin'}]
group = self._action('group_create')(context, data_dict)
h.redirect_to(group['type'] + '_read', id=group['name'])
except (NotFound, NotAuthorized), e:
abort(404, _('Group not found'))
except dict_fns.DataError:
abort(400, _(u'Integrity Error'))
except ValidationError, e:
errors = e.error_dict
error_summary = e.error_summary
return self.new(data_dict, errors, error_summary)
def _force_reindex(self, grp):
''' When the group name has changed, we need to force a reindex
of the datasets within the group, otherwise they will stop
appearing on the read page for the group (as they're connected via
the group name)'''
group = model.Group.get(grp['name'])
for dataset in group.packages():
search.rebuild(dataset.name)
def _save_edit(self, id, context):
try:
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
context['message'] = data_dict.get('log_message', '')
data_dict['id'] = id
context['allow_partial_update'] = True
group = self._action('group_update')(context, data_dict)
if id != group['name']:
self._force_reindex(group)
h.redirect_to('%s_read' % group['type'], id=group['name'])
except (NotFound, NotAuthorized), e:
abort(404, _('Group not found'))
except dict_fns.DataError:
abort(400, _(u'Integrity Error'))
except ValidationError, e:
errors = e.error_dict
error_summary = e.error_summary
return self.edit(id, data_dict, errors, error_summary)
def authz(self, id):
group = model.Group.get(id)
if group is None:
abort(404, _('Group not found'))
group_type = group.type
if group_type not in self.group_types:
abort(404, _('Incorrect group type'))
c.groupname = group.name
c.grouptitle = group.display_name
try:
context = \
{'model': model, 'user': c.user, 'group': group}
self._check_access('group_edit_permissions', context)
c.authz_editable = True
c.group = context['group']
except NotAuthorized:
c.authz_editable = False
if not c.authz_editable:
abort(403,
_('User %r not authorized to edit %s authorizations') %
(c.user, id))
roles = self._handle_update_of_authz(group)
self._prepare_authz_info_for_render(roles)
return render('group/authz.html',
extra_vars={'group_type': group_type})
def delete(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'cancel' in request.params:
self._redirect_to_this_controller(action='edit', id=id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_delete', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s') % '')
try:
if request.method == 'POST':
self._action('group_delete')(context, {'id': id})
if group_type == 'organization':
h.flash_notice(_('Organization has been deleted.'))
elif group_type == 'group':
h.flash_notice(_('Group has been deleted.'))
else:
h.flash_notice(_('%s has been deleted.')
% _(group_type.capitalize()))
self._redirect_to_this_controller(action='index')
c.group_dict = self._action('group_show')(context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s') % '')
except NotFound:
abort(404, _('Group not found'))
except ValidationError as e:
h.flash_error(e.error_dict['message'])
h.redirect_to(controller='organization', action='read', id=id)
return self._render_template('group/confirm_delete.html', group_type)
def members(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
data_dict = {'id': id}
check_access('group_edit_permissions', context, data_dict)
c.members = self._action('member_list')(
context, {'id': id, 'object_type': 'user'}
)
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
except NotFound:
abort(404, _('Group not found'))
except NotAuthorized:
abort(
403,
_('User %r not authorized to edit members of %s') % (
c.user, id))
return self._render_template('group/members.html', group_type)
def member_new(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_member_create', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to create group %s members') % '')
try:
data_dict = {'id': id}
data_dict['include_datasets'] = False
c.group_dict = self._action('group_show')(context, data_dict)
c.roles = self._action('member_roles_list')(
context, {'group_type': group_type}
)
if request.method == 'POST':
data_dict = clean_dict(dict_fns.unflatten(
tuplize_dict(parse_params(request.params))))
data_dict['id'] = id
email = data_dict.get('email')
if email:
user_data_dict = {
'email': email,
'group_id': data_dict['id'],
'role': data_dict['role']
}
del data_dict['email']
user_dict = self._action('user_invite')(
context, user_data_dict)
data_dict['username'] = user_dict['name']
c.group_dict = self._action('group_member_create')(
context, data_dict)
self._redirect_to_this_controller(action='members', id=id)
else:
user = request.params.get('user')
if user:
c.user_dict = \
get_action('user_show')(context, {'id': user})
c.user_role = \
authz.users_role_for_group_or_org(id, user) or 'member'
else:
c.user_role = 'member'
except NotAuthorized:
abort(403, _('Unauthorized to add member to group %s') % '')
except NotFound:
abort(404, _('Group not found'))
except ValidationError, e:
h.flash_error(e.error_summary)
return self._render_template('group/member_new.html', group_type)
def member_delete(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'cancel' in request.params:
self._redirect_to_this_controller(action='members', id=id)
context = {'model': model, 'session': model.Session,
'user': c.user}
try:
self._check_access('group_member_delete', context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s members') % '')
try:
user_id = request.params.get('user')
if request.method == 'POST':
self._action('group_member_delete')(
context, {'id': id, 'user_id': user_id})
h.flash_notice(_('Group member has been deleted.'))
self._redirect_to_this_controller(action='members', id=id)
c.user_dict = self._action('user_show')(context, {'id': user_id})
c.user_id = user_id
c.group_id = id
except NotAuthorized:
abort(403, _('Unauthorized to delete group %s members') % '')
except NotFound:
abort(404, _('Group not found'))
return self._render_template('group/confirm_delete_member.html',
group_type)
def history(self, id):
group_type = self._ensure_controller_matches_group_type(id)
if 'diff' in request.params or 'selected1' in request.params:
try:
params = {'id': request.params.getone('group_name'),
'diff': request.params.getone('selected1'),
'oldid': request.params.getone('selected2'),
}
except KeyError:
if 'group_name' in dict(request.params):
id = request.params.getone('group_name')
c.error = \
_('Select two revisions before doing the comparison.')
else:
params['diff_entity'] = 'group'
h.redirect_to(controller='revision', action='diff', **params)
context = {'model': model, 'session': model.Session,
'user': c.user,
'schema': self._db_to_form_schema()}
data_dict = {'id': id}
try:
c.group_dict = self._action('group_show')(context, data_dict)
c.group_revisions = self._action('group_revision_list')(context,
data_dict)
# TODO: remove
# Still necessary for the authz check in group/layout.html
c.group = context['group']
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
format = request.params.get('format', '')
if format == 'atom':
# Generate and return Atom 1.0 document.
from webhelpers.feedgenerator import Atom1Feed
feed = Atom1Feed(
title=_(u'CKAN Group Revision History'),
link=self._url_for_this_controller(
action='read',
id=c.group_dict['name']),
description=_(u'Recent changes to CKAN Group: ') +
c.group_dict['display_name'],
language=unicode(get_lang()),
)
for revision_dict in c.group_revisions:
revision_date = h.date_str_to_datetime(
revision_dict['timestamp'])
try:
dayHorizon = int(request.params.get('days'))
except:
dayHorizon = 30
dayAge = (datetime.datetime.now() - revision_date).days
if dayAge >= dayHorizon:
break
if revision_dict['message']:
item_title = u'%s' % revision_dict['message'].\
split('\n')[0]
else:
item_title = u'%s' % revision_dict['id']
item_link = h.url_for(controller='revision', action='read',
id=revision_dict['id'])
item_description = _('Log message: ')
item_description += '%s' % (revision_dict['message'] or '')
item_author_name = revision_dict['author']
item_pubdate = revision_date
feed.add_item(
title=item_title,
link=item_link,
description=item_description,
author_name=item_author_name,
pubdate=item_pubdate,
)
feed.content_type = 'application/atom+xml'
return feed.writeString('utf-8')
return render(self._history_template(group_type),
extra_vars={'group_type': group_type})
def activity(self, id, offset=0):
'''Render this group's public activity stream page.'''
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user, 'for_view': True}
try:
c.group_dict = self._get_group_dict(id)
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
try:
# template context for the group/read.html
# template to retrieve later.
c.group_activity_stream = self._action('group_activity_list_html')(
context, {'id': c.group_dict['id'], 'offset': offset})
except ValidationError as error:
base.abort(400)
return render(self._activity_template(group_type),
extra_vars={'group_type': group_type})
def follow(self, id):
'''Start following this group.'''
self._ensure_controller_matches_group_type(id)
context = {'model': model,
'session': model.Session,
'user': c.user}
data_dict = {'id': id}
try:
get_action('follow_group')(context, data_dict)
group_dict = get_action('group_show')(context, data_dict)
h.flash_success(_("You are now following {0}").format(
group_dict['title']))
except ValidationError as e:
error_message = (e.message or e.error_summary
or e.error_dict)
h.flash_error(error_message)
except NotAuthorized as e:
h.flash_error(e.message)
h.redirect_to(controller='group', action='read', id=id)
def unfollow(self, id):
'''Stop following this group.'''
self._ensure_controller_matches_group_type(id)
context = {'model': model,
'session': model.Session,
'user': c.user}
data_dict = {'id': id}
try:
get_action('unfollow_group')(context, data_dict)
group_dict = get_action('group_show')(context, data_dict)
h.flash_success(_("You are no longer following {0}").format(
group_dict['title']))
except ValidationError as e:
error_message = (e.message or e.error_summary
or e.error_dict)
h.flash_error(error_message)
except (NotFound, NotAuthorized) as e:
error_message = e.message
h.flash_error(error_message)
h.redirect_to(controller='group', action='read', id=id)
def followers(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
c.group_dict = self._get_group_dict(id)
try:
c.followers = \
get_action('group_follower_list')(context, {'id': id})
except NotAuthorized:
abort(403, _('Unauthorized to view followers %s') % '')
return render('group/followers.html',
extra_vars={'group_type': group_type})
def admins(self, id):
group_type = self._ensure_controller_matches_group_type(id)
c.group_dict = self._get_group_dict(id)
c.admins = authz.get_group_or_org_admin_ids(id)
return render(self._admins_template(c.group_dict['type']),
extra_vars={'group_type': group_type})
def about(self, id):
group_type = self._ensure_controller_matches_group_type(id)
context = {'model': model, 'session': model.Session,
'user': c.user}
c.group_dict = self._get_group_dict(id)
group_type = c.group_dict['type']
self._setup_template_variables(context, {'id': id},
group_type=group_type)
return render(self._about_template(group_type),
extra_vars={'group_type': group_type})
def _get_group_dict(self, id):
''' returns the result of group_show action or aborts if there is a
problem '''
context = {'model': model, 'session': model.Session,
'user': c.user,
'for_view': True}
try:
return self._action('group_show')(
context, {'id': id, 'include_datasets': False})
except (NotFound, NotAuthorized):
abort(404, _('Group not found'))
| false | true |
f71badae1870e808949da29b629a3e7d4dc4fa3d | 4,753 | py | Python | i18n/i18n.py | AshleyFires/krux | 80de3ee0df5e7147dd32c10967cac7c3e6aecd09 | [
"MIT"
] | null | null | null | i18n/i18n.py | AshleyFires/krux | 80de3ee0df5e7147dd32c10967cac7c3e6aecd09 | [
"MIT"
] | null | null | null | i18n/i18n.py | AshleyFires/krux | 80de3ee0df5e7147dd32c10967cac7c3e6aecd09 | [
"MIT"
] | null | null | null | # The MIT License (MIT)
# Copyright (c) 2021 Tom J. Sun
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import json
from os import listdir, walk
from os.path import isfile, join
import re
import shutil
SRC_DIR = '../src'
TRANSLATION_FILES_DIR = 'translations'
def find_translation_slugs():
"""Searches the src directory for all 'slugs' that should be translated
by looking for matches of the pattern ( 'string' )
"""
slugs = {}
for (dirpath, _, filenames) in walk(SRC_DIR):
for filename in filenames:
if not filename.endswith('.py'):
continue
with open(join(dirpath, filename), 'r') as src_file:
contents = src_file.read()
for match in re.findall(r'\( \'(.+?)\' \)', contents):
slugs[match] = True
return slugs
def load_translations(translation_file):
"""Loads translations from the given file and returns them as a map"""
translations = json.load(translation_file)
for slug, translation in list(translations.items()):
del translations[slug]
translations[slug.replace('\n', '\\n')] = translation.replace('\n', '\\n')
return translations
def main():
"""Main handler"""
slugs = find_translation_slugs()
if sys.argv[1] == 'validate':
translation_filenames = [
f for f in listdir(TRANSLATION_FILES_DIR)
if isfile(join(TRANSLATION_FILES_DIR, f))
]
for translation_filename in translation_filenames:
print('Validating %s...' % translation_filename)
valid = True
with open(join(TRANSLATION_FILES_DIR, translation_filename), 'r') as translation_file:
translations = load_translations(translation_file)
for slug in slugs:
if slug not in translations or translations[slug] == '':
print('Missing translation for "%s"' % slug)
valid = False
for translation_slug in translations:
if translation_slug not in slugs:
print('Unnecessary translation for "%s"' % translation_slug)
valid = False
if valid:
print('OK')
elif sys.argv[1] == 'new':
locale = sys.argv[2]
translations = {}
for slug in slugs:
translations[slug.replace('\\n', '\n')] = ''
with open(join(TRANSLATION_FILES_DIR, '%s.json' % locale), 'w') as translation_file:
translation_file.write(json.dumps(translations, sort_keys=True, indent=4))
elif sys.argv[1] == 'translate':
locale = sys.argv[2]
output_dir = sys.argv[3]
with open(join(TRANSLATION_FILES_DIR, '%s.json' % locale), 'r') as translation_file:
translations = load_translations(translation_file)
for (dirpath, _, filenames) in walk(output_dir):
for filename in filenames:
if not filename.endswith('.py'):
continue
with open(join(dirpath, filename), 'r') as src_file:
contents = src_file.read()
for slug, translation in translations.items():
contents = contents.replace(
'( \'%s\' )' % slug,
'"""%s"""' % translation
)
with open(join(dirpath, filename + '.tmp'), 'w') as tmp_src_file:
tmp_src_file.write(contents)
shutil.move(join(dirpath, filename + '.tmp'), join(dirpath, filename))
if __name__ == '__main__':
main()
| 43.605505 | 98 | 0.606775 |
import sys
import json
from os import listdir, walk
from os.path import isfile, join
import re
import shutil
SRC_DIR = '../src'
TRANSLATION_FILES_DIR = 'translations'
def find_translation_slugs():
slugs = {}
for (dirpath, _, filenames) in walk(SRC_DIR):
for filename in filenames:
if not filename.endswith('.py'):
continue
with open(join(dirpath, filename), 'r') as src_file:
contents = src_file.read()
for match in re.findall(r'\( \'(.+?)\' \)', contents):
slugs[match] = True
return slugs
def load_translations(translation_file):
translations = json.load(translation_file)
for slug, translation in list(translations.items()):
del translations[slug]
translations[slug.replace('\n', '\\n')] = translation.replace('\n', '\\n')
return translations
def main():
slugs = find_translation_slugs()
if sys.argv[1] == 'validate':
translation_filenames = [
f for f in listdir(TRANSLATION_FILES_DIR)
if isfile(join(TRANSLATION_FILES_DIR, f))
]
for translation_filename in translation_filenames:
print('Validating %s...' % translation_filename)
valid = True
with open(join(TRANSLATION_FILES_DIR, translation_filename), 'r') as translation_file:
translations = load_translations(translation_file)
for slug in slugs:
if slug not in translations or translations[slug] == '':
print('Missing translation for "%s"' % slug)
valid = False
for translation_slug in translations:
if translation_slug not in slugs:
print('Unnecessary translation for "%s"' % translation_slug)
valid = False
if valid:
print('OK')
elif sys.argv[1] == 'new':
locale = sys.argv[2]
translations = {}
for slug in slugs:
translations[slug.replace('\\n', '\n')] = ''
with open(join(TRANSLATION_FILES_DIR, '%s.json' % locale), 'w') as translation_file:
translation_file.write(json.dumps(translations, sort_keys=True, indent=4))
elif sys.argv[1] == 'translate':
locale = sys.argv[2]
output_dir = sys.argv[3]
with open(join(TRANSLATION_FILES_DIR, '%s.json' % locale), 'r') as translation_file:
translations = load_translations(translation_file)
for (dirpath, _, filenames) in walk(output_dir):
for filename in filenames:
if not filename.endswith('.py'):
continue
with open(join(dirpath, filename), 'r') as src_file:
contents = src_file.read()
for slug, translation in translations.items():
contents = contents.replace(
'( \'%s\' )' % slug,
'"""%s"""' % translation
)
with open(join(dirpath, filename + '.tmp'), 'w') as tmp_src_file:
tmp_src_file.write(contents)
shutil.move(join(dirpath, filename + '.tmp'), join(dirpath, filename))
if __name__ == '__main__':
main()
| true | true |
f71badc6bf833dce168ea8abc5e6eedabacd9bc3 | 1,205 | py | Python | pari/article/urls.py | theju/pari | 318a4ffba08362e78253ded100a63f5b5c6eadf9 | [
"BSD-3-Clause"
] | null | null | null | pari/article/urls.py | theju/pari | 318a4ffba08362e78253ded100a63f5b5c6eadf9 | [
"BSD-3-Clause"
] | null | null | null | pari/article/urls.py | theju/pari | 318a4ffba08362e78253ded100a63f5b5c6eadf9 | [
"BSD-3-Clause"
] | null | null | null | from django.conf.urls import patterns, url
from .views import (LocationDetail, CategoriesList, CategoryDetail, ArticleDetail,
ArticleList, KeywordDetail, AuthorDetail, ArchiveDetail, ArticleCarouselImageDetail)
urlpatterns = patterns('pari.article.views',
url(r'^categories/(?P<slug>.+)/$', CategoryDetail.as_view(), name='category-detail'),
url(r'^categories/$', CategoriesList.as_view(), name='category-list'),
url(r'^authors/(?P<slug>.+)/$', AuthorDetail.as_view(), name='author-detail'),
url(r'^articles/(?P<slug>.+)/$', ArticleDetail.as_view(), name='article-detail'),
url(r'^articles/(?P<slug>.+)/(?P<order>\d+)/$', ArticleCarouselImageDetail.as_view(), name='article-image-detail'),
url(r'^articles/$', ArticleList.as_view(), name='article-list'),
url(r'^topics/(?P<slug>.+)/$', AuthorDetail.as_view(), name='topic-detail'),
url(r'^locations/(?P<slug>.+)/$', LocationDetail.as_view(), name='location-detail'),
url(r'^keywords/(?P<slug>.+)/$', KeywordDetail.as_view(template_name="article/keyword_detail.html"), name='keyword-detail'),
url(r'^archive/(?P<year>\d{4})/(?P<month>\d+)/$', ArchiveDetail.as_view(), name='archive-detail'),
)
| 66.944444 | 128 | 0.674689 | from django.conf.urls import patterns, url
from .views import (LocationDetail, CategoriesList, CategoryDetail, ArticleDetail,
ArticleList, KeywordDetail, AuthorDetail, ArchiveDetail, ArticleCarouselImageDetail)
urlpatterns = patterns('pari.article.views',
url(r'^categories/(?P<slug>.+)/$', CategoryDetail.as_view(), name='category-detail'),
url(r'^categories/$', CategoriesList.as_view(), name='category-list'),
url(r'^authors/(?P<slug>.+)/$', AuthorDetail.as_view(), name='author-detail'),
url(r'^articles/(?P<slug>.+)/$', ArticleDetail.as_view(), name='article-detail'),
url(r'^articles/(?P<slug>.+)/(?P<order>\d+)/$', ArticleCarouselImageDetail.as_view(), name='article-image-detail'),
url(r'^articles/$', ArticleList.as_view(), name='article-list'),
url(r'^topics/(?P<slug>.+)/$', AuthorDetail.as_view(), name='topic-detail'),
url(r'^locations/(?P<slug>.+)/$', LocationDetail.as_view(), name='location-detail'),
url(r'^keywords/(?P<slug>.+)/$', KeywordDetail.as_view(template_name="article/keyword_detail.html"), name='keyword-detail'),
url(r'^archive/(?P<year>\d{4})/(?P<month>\d+)/$', ArchiveDetail.as_view(), name='archive-detail'),
)
| true | true |
f71bae99af72eaffd84e9a35dfa07be932c56df2 | 4,017 | py | Python | classes/Helpers.py | alexdevmotion/UnifiedEegLogger | 735b2734fc9cd5dd9e6b7148b4310a4267624e63 | [
"Apache-2.0"
] | 1 | 2018-06-07T03:47:31.000Z | 2018-06-07T03:47:31.000Z | classes/Helpers.py | alexdevmotion/unified-eeg-experiment-machine | 735b2734fc9cd5dd9e6b7148b4310a4267624e63 | [
"Apache-2.0"
] | null | null | null | classes/Helpers.py | alexdevmotion/unified-eeg-experiment-machine | 735b2734fc9cd5dd9e6b7148b4310a4267624e63 | [
"Apache-2.0"
] | null | null | null | from Tkinter import *
from PIL import ImageTk, Image
import tkMessageBox
import sys
import os
def getNoImagesInDirectory(dir):
return len(getImagesInDirectory(dir))
def getImagesInDirectory(dir):
files = os.listdir(dir)
images = []
for file in files:
if file.lower().endswith((".jpg", ".png", ".jpeg", ".gif")):
images.append(file)
return images
def representsInt(s):
try:
int(s)
return True
except ValueError:
return False
class FullScreenWindow:
def __init__(self, closingCallback):
self.closingCallback = closingCallback
self.tk = Tk()
self.frame = Frame(self.tk)
self.frame.pack()
self.state = False
self.tk.iconbitmap("misc/favicon.ico")
self.tk.title("EEG Unified Logger a.k.a. The Experiment Machine")
self.tk.minsize(width=600, height=400)
self.tk.bind("<F11>", self.toggle_fullscreen)
self.tk.bind("<Escape>", self.end_fullscreen)
self.tk.protocol("WM_DELETE_WINDOW", self.on_closing)
def toggle_fullscreen(self, event=None):
self.state = not self.state
self.tk.attributes("-fullscreen", self.state)
return "break"
def end_fullscreen(self, event=None):
self.state = False
self.tk.attributes("-fullscreen", False)
return "break"
def on_closing(self):
if tkMessageBox.askokcancel("Quit", "Are you sure you want to exit?"):
self.tk.destroy()
if self.closingCallback:
self.closingCallback()
sys.exit(0)
class ImageWindow:
def __init__(self, tk, dir, images, imageInterval, threadedTasks, crop):
self.tk = tk
self.dir = dir
self.images = images
self.imageInterval = imageInterval
self.threadedTasks = threadedTasks
self.crop = crop
self.curImageIndex = 0
self.window = Toplevel(self.tk)
self.window.attributes("-fullscreen", True)
self.window.focus_force()
self.window.bind("<Escape>", self.experimentStoppedByUser)
self.windowDestroyed = False
self.imagePanel = Label(self.window, image=None)
self.imagePanel.pack(side="bottom", fill="both", expand="yes")
def experimentStoppedByUser(self, event=None):
self.window.destroy()
self.windowDestroyed = True
self.threadedTasks.stopLoggingToFile()
def handleNextImage(self):
if not self.windowDestroyed:
try:
curImage = str(self.images[self.curImageIndex])
self.threadedTasks.setCurrentFileName(curImage)
self.displayImage(self.dir + "/" + curImage)
self.curImageIndex += 1
self.window.after(self.imageInterval * 1000, self.handleNextImage)
except IndexError:
self.experimentStoppedByUser()
def displayImage(self, path):
img = Image.open(path)
if self.crop:
img = self.cropAndResize(img, self.window.winfo_screenwidth(), self.window.winfo_screenheight())
photoimg = ImageTk.PhotoImage(img)
self.imagePanel.configure(image=photoimg)
self.imagePanel.image = photoimg
def cropAndResize(self, image, ideal_width, ideal_height):
width = image.size[0]
height = image.size[1]
aspect = width / float(height)
ideal_aspect = ideal_width / float(ideal_height)
if aspect > ideal_aspect:
# Then crop the left and right edges:
new_width = int(ideal_aspect * height)
offset = (width - new_width) / 2
resize = (offset, 0, width - offset, height)
else:
# ... crop the top and bottom:
new_height = int(width / ideal_aspect)
offset = (height - new_height) / 2
resize = (0, offset, width, height - offset)
return image.crop(resize).resize((ideal_width, ideal_height), Image.ANTIALIAS)
| 30.664122 | 108 | 0.61638 | from Tkinter import *
from PIL import ImageTk, Image
import tkMessageBox
import sys
import os
def getNoImagesInDirectory(dir):
return len(getImagesInDirectory(dir))
def getImagesInDirectory(dir):
files = os.listdir(dir)
images = []
for file in files:
if file.lower().endswith((".jpg", ".png", ".jpeg", ".gif")):
images.append(file)
return images
def representsInt(s):
try:
int(s)
return True
except ValueError:
return False
class FullScreenWindow:
def __init__(self, closingCallback):
self.closingCallback = closingCallback
self.tk = Tk()
self.frame = Frame(self.tk)
self.frame.pack()
self.state = False
self.tk.iconbitmap("misc/favicon.ico")
self.tk.title("EEG Unified Logger a.k.a. The Experiment Machine")
self.tk.minsize(width=600, height=400)
self.tk.bind("<F11>", self.toggle_fullscreen)
self.tk.bind("<Escape>", self.end_fullscreen)
self.tk.protocol("WM_DELETE_WINDOW", self.on_closing)
def toggle_fullscreen(self, event=None):
self.state = not self.state
self.tk.attributes("-fullscreen", self.state)
return "break"
def end_fullscreen(self, event=None):
self.state = False
self.tk.attributes("-fullscreen", False)
return "break"
def on_closing(self):
if tkMessageBox.askokcancel("Quit", "Are you sure you want to exit?"):
self.tk.destroy()
if self.closingCallback:
self.closingCallback()
sys.exit(0)
class ImageWindow:
def __init__(self, tk, dir, images, imageInterval, threadedTasks, crop):
self.tk = tk
self.dir = dir
self.images = images
self.imageInterval = imageInterval
self.threadedTasks = threadedTasks
self.crop = crop
self.curImageIndex = 0
self.window = Toplevel(self.tk)
self.window.attributes("-fullscreen", True)
self.window.focus_force()
self.window.bind("<Escape>", self.experimentStoppedByUser)
self.windowDestroyed = False
self.imagePanel = Label(self.window, image=None)
self.imagePanel.pack(side="bottom", fill="both", expand="yes")
def experimentStoppedByUser(self, event=None):
self.window.destroy()
self.windowDestroyed = True
self.threadedTasks.stopLoggingToFile()
def handleNextImage(self):
if not self.windowDestroyed:
try:
curImage = str(self.images[self.curImageIndex])
self.threadedTasks.setCurrentFileName(curImage)
self.displayImage(self.dir + "/" + curImage)
self.curImageIndex += 1
self.window.after(self.imageInterval * 1000, self.handleNextImage)
except IndexError:
self.experimentStoppedByUser()
def displayImage(self, path):
img = Image.open(path)
if self.crop:
img = self.cropAndResize(img, self.window.winfo_screenwidth(), self.window.winfo_screenheight())
photoimg = ImageTk.PhotoImage(img)
self.imagePanel.configure(image=photoimg)
self.imagePanel.image = photoimg
def cropAndResize(self, image, ideal_width, ideal_height):
width = image.size[0]
height = image.size[1]
aspect = width / float(height)
ideal_aspect = ideal_width / float(ideal_height)
if aspect > ideal_aspect:
new_width = int(ideal_aspect * height)
offset = (width - new_width) / 2
resize = (offset, 0, width - offset, height)
else:
new_height = int(width / ideal_aspect)
offset = (height - new_height) / 2
resize = (0, offset, width, height - offset)
return image.crop(resize).resize((ideal_width, ideal_height), Image.ANTIALIAS)
| true | true |
f71baee95ce425491965abf613df86bac3425409 | 3,126 | py | Python | acm/uri/1455-icpc-finals.py | neizod/problems | 180aaf7d0ecfc3d0dd5f1d4345a7a4d83b1b884a | [
"MIT"
] | 1 | 2015-10-17T11:15:42.000Z | 2015-10-17T11:15:42.000Z | acm/uri/1455-icpc-finals.py | neizod/problems | 180aaf7d0ecfc3d0dd5f1d4345a7a4d83b1b884a | [
"MIT"
] | null | null | null | acm/uri/1455-icpc-finals.py | neizod/problems | 180aaf7d0ecfc3d0dd5f1d4345a7a4d83b1b884a | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import random
from itertools import count
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Point.from_spec = lambda st: Point(*[float(si) for si in st.split()])
Circle = namedtuple('Circle', 'c r')
Circle.__new__.__defaults__ = (Point(0, 0), 0)
Circle.__contains__ = lambda s, p: s.r > 0 and sq_dist(p, s.c) <= s.r**2
Circle.from_arc = lambda *ps: ( circle_from_1_points(*ps) if len(ps) == 1 else
circle_from_2_points(*ps) if len(ps) == 2 else
circle_decide_3_points(*ps) if len(ps) == 3 else
NotImplemented )
sq_dist = lambda p, q=Point(0, 0): (p.x-q.x)**2 + (p.y-q.y)**2
det = lambda u, v, w: u.x*v.y + v.x*w.y + w.x*u.y - u.x*w.y - v.x*u.y - w.x*v.y
detx = lambda u, v, w: ( sq_dist(u)*v.y + sq_dist(v)*w.y + sq_dist(w)*u.y
- sq_dist(u)*w.y - sq_dist(v)*u.y - sq_dist(w)*v.y )
dety = lambda u, v, w: ( u.x*sq_dist(v) + v.x*sq_dist(w) + w.x*sq_dist(u)
- u.x*sq_dist(w) - v.x*sq_dist(u) - w.x*sq_dist(v) )
dets = lambda u, v, w: ( u.x*v.y*sq_dist(w) + v.x*w.y*sq_dist(u) + w.x*u.y*sq_dist(v)
- u.x*w.y*sq_dist(v) - v.x*u.y*sq_dist(w) - w.x*v.y*sq_dist(u) )
def shuffled(points):
ls = list(points)
random.shuffle(ls)
return ls
# XXX please note that though the problem statement says 2 <= n <= 100,
# the actual test does contain case of n == 1 too. WTF!!!
def circle_from_1_points(p1):
return Circle(p1, 0)
def circle_from_2_points(p1, p2):
dx = (p1.x + p2.x)/2
dy = (p1.y + p2.y)/2
c = Point(dx, dy)
r = sq_dist(p1, p2)**.5/2
return Circle(c, r)
def circle_from_3_points(p1, p2, p3):
a = det(p1, p2, p3)
b = dets(p1, p2, p3)
sx = detx(p1, p2, p3)
sy = dety(p1, p2, p3)
c = Point(sx/a/2, sy/a/2)
return Circle(c, (b/a + sq_dist(c))**.5)
def circle_decide_3_points(p1, p2, p3):
ps = {p1, p2, p3}
for p in ps:
circle = circle_from_2_points(*ps-{p})
if p in circle:
return circle
return circle_from_3_points(p1, p2, p3)
def mincircle2p(points, p1, p2):
circle = Circle.from_arc(p1, p2)
for i, p in enumerate(points):
if p not in circle:
circle = Circle.from_arc(p1, p2, p)
return circle
def mincircle1p(points, p1):
circle = Circle.from_arc(p1)
ps = shuffled(points)
for i, p in enumerate(ps):
if p not in circle:
circle = mincircle2p(set(ps[:i]), p1, p)
return circle
def mincircle(points):
circle = Circle()
ps = shuffled(points)
for i, p in enumerate(ps):
if p not in circle:
circle = mincircle1p(set(ps[:i]), p)
return circle
def main():
for t in count(1):
n = int(input())
if n == 0:
break
points = [Point.from_spec(input()) for _ in range(n)]
ans = mincircle(points)
print('Instancia {}'.format(t))
print('{:.2f} {:.2f} {:.2f}'.format(ans.c.x, ans.c.y, ans.r))
print()
if __name__ == '__main__':
main()
| 28.944444 | 87 | 0.555662 |
import random
from itertools import count
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Point.from_spec = lambda st: Point(*[float(si) for si in st.split()])
Circle = namedtuple('Circle', 'c r')
Circle.__new__.__defaults__ = (Point(0, 0), 0)
Circle.__contains__ = lambda s, p: s.r > 0 and sq_dist(p, s.c) <= s.r**2
Circle.from_arc = lambda *ps: ( circle_from_1_points(*ps) if len(ps) == 1 else
circle_from_2_points(*ps) if len(ps) == 2 else
circle_decide_3_points(*ps) if len(ps) == 3 else
NotImplemented )
sq_dist = lambda p, q=Point(0, 0): (p.x-q.x)**2 + (p.y-q.y)**2
det = lambda u, v, w: u.x*v.y + v.x*w.y + w.x*u.y - u.x*w.y - v.x*u.y - w.x*v.y
detx = lambda u, v, w: ( sq_dist(u)*v.y + sq_dist(v)*w.y + sq_dist(w)*u.y
- sq_dist(u)*w.y - sq_dist(v)*u.y - sq_dist(w)*v.y )
dety = lambda u, v, w: ( u.x*sq_dist(v) + v.x*sq_dist(w) + w.x*sq_dist(u)
- u.x*sq_dist(w) - v.x*sq_dist(u) - w.x*sq_dist(v) )
dets = lambda u, v, w: ( u.x*v.y*sq_dist(w) + v.x*w.y*sq_dist(u) + w.x*u.y*sq_dist(v)
- u.x*w.y*sq_dist(v) - v.x*u.y*sq_dist(w) - w.x*v.y*sq_dist(u) )
def shuffled(points):
ls = list(points)
random.shuffle(ls)
return ls
def circle_from_1_points(p1):
return Circle(p1, 0)
def circle_from_2_points(p1, p2):
dx = (p1.x + p2.x)/2
dy = (p1.y + p2.y)/2
c = Point(dx, dy)
r = sq_dist(p1, p2)**.5/2
return Circle(c, r)
def circle_from_3_points(p1, p2, p3):
a = det(p1, p2, p3)
b = dets(p1, p2, p3)
sx = detx(p1, p2, p3)
sy = dety(p1, p2, p3)
c = Point(sx/a/2, sy/a/2)
return Circle(c, (b/a + sq_dist(c))**.5)
def circle_decide_3_points(p1, p2, p3):
ps = {p1, p2, p3}
for p in ps:
circle = circle_from_2_points(*ps-{p})
if p in circle:
return circle
return circle_from_3_points(p1, p2, p3)
def mincircle2p(points, p1, p2):
circle = Circle.from_arc(p1, p2)
for i, p in enumerate(points):
if p not in circle:
circle = Circle.from_arc(p1, p2, p)
return circle
def mincircle1p(points, p1):
circle = Circle.from_arc(p1)
ps = shuffled(points)
for i, p in enumerate(ps):
if p not in circle:
circle = mincircle2p(set(ps[:i]), p1, p)
return circle
def mincircle(points):
circle = Circle()
ps = shuffled(points)
for i, p in enumerate(ps):
if p not in circle:
circle = mincircle1p(set(ps[:i]), p)
return circle
def main():
for t in count(1):
n = int(input())
if n == 0:
break
points = [Point.from_spec(input()) for _ in range(n)]
ans = mincircle(points)
print('Instancia {}'.format(t))
print('{:.2f} {:.2f} {:.2f}'.format(ans.c.x, ans.c.y, ans.r))
print()
if __name__ == '__main__':
main()
| true | true |
f71baf805de10ecd0c891aeb9bfc3b748a4b7980 | 4,340 | py | Python | openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py | CplusShen/aurora-horizon | 8df16b3b87097d5a19bae3752d4b341ac64bda75 | [
"Apache-2.0"
] | 1 | 2020-04-12T19:21:18.000Z | 2020-04-12T19:21:18.000Z | openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py | CplusShen/aurora-horizon | 8df16b3b87097d5a19bae3752d4b341ac64bda75 | [
"Apache-2.0"
] | 12 | 2022-03-22T07:28:29.000Z | 2022-03-22T07:29:55.000Z | openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py | CplusShen/aurora-horizon | 8df16b3b87097d5a19bae3752d4b341ac64bda75 | [
"Apache-2.0"
] | 2 | 2019-01-17T06:06:00.000Z | 2019-08-07T02:21:07.000Z | # Copyright 2013 CentRin Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables # noqa
from horizon import exceptions
from horizon import forms
from horizon import workflows
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.instances \
import utils as instance_utils
from openstack_dashboard.dashboards.project.instances.workflows \
import create_instance
class SetFlavorChoiceAction(workflows.Action):
old_flavor_id = forms.CharField(required=False, widget=forms.HiddenInput())
old_flavor_name = forms.CharField(
label=_("Old Flavor"),
widget=forms.TextInput(attrs={'readonly': 'readonly'}),
required=False,
)
flavor = forms.ThemableChoiceField(
label=_("New Flavor"),
help_text=_("Choose the flavor to launch."))
class Meta(object):
name = _("Flavor Choice")
slug = 'flavor_choice'
help_text_template = ("project/instances/"
"_flavors_and_quotas.html")
def populate_flavor_choices(self, request, context):
old_flavor_id = context.get('old_flavor_id')
flavors = context.get('flavors').values()
# Remove current flavor from the list of flavor choices
flavors = [flavor for flavor in flavors if flavor.id != old_flavor_id]
if flavors:
if len(flavors) > 1:
flavors = instance_utils.sort_flavor_list(request, flavors)
else:
flavor = flavors[0]
flavors = [(flavor.id, flavor.name)]
flavors.insert(0, ("", _("Select a New Flavor")))
else:
flavors.insert(0, ("", _("No flavors available")))
return flavors
def get_help_text(self, extra_context=None):
extra = {} if extra_context is None else dict(extra_context)
try:
extra['usages'] = api.nova.tenant_absolute_limits(self.request,
reserved=True)
extra['usages_json'] = json.dumps(extra['usages'])
flavors = json.dumps([f._info for f in
instance_utils.flavor_list(self.request)])
extra['flavors'] = flavors
extra['resize_instance'] = True
except Exception:
exceptions.handle(self.request,
_("Unable to retrieve quota information."))
return super(SetFlavorChoiceAction, self).get_help_text(extra)
class SetFlavorChoice(workflows.Step):
action_class = SetFlavorChoiceAction
depends_on = ("instance_id", "name")
contributes = ("old_flavor_id", "old_flavor_name", "flavors", "flavor")
class ResizeInstance(workflows.Workflow):
slug = "resize_instance"
name = _("Resize Instance")
finalize_button_name = _("Resize")
success_message = _('Request for resizing of instance "%s" '
'has been submitted.')
failure_message = _('Unable to resize instance "%s".')
success_url = "horizon:project:instances:index"
default_steps = (SetFlavorChoice, create_instance.SetAdvanced)
def format_status_message(self, message):
return message % self.context.get('name', 'unknown instance')
@sensitive_variables('context')
def handle(self, request, context):
instance_id = context.get('instance_id', None)
flavor = context.get('flavor', None)
disk_config = context.get('disk_config', None)
try:
api.nova.server_resize(request, instance_id, flavor, disk_config)
return True
except Exception:
exceptions.handle(request)
return False
| 38.75 | 79 | 0.65 |
import json
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables
from horizon import exceptions
from horizon import forms
from horizon import workflows
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.instances \
import utils as instance_utils
from openstack_dashboard.dashboards.project.instances.workflows \
import create_instance
class SetFlavorChoiceAction(workflows.Action):
old_flavor_id = forms.CharField(required=False, widget=forms.HiddenInput())
old_flavor_name = forms.CharField(
label=_("Old Flavor"),
widget=forms.TextInput(attrs={'readonly': 'readonly'}),
required=False,
)
flavor = forms.ThemableChoiceField(
label=_("New Flavor"),
help_text=_("Choose the flavor to launch."))
class Meta(object):
name = _("Flavor Choice")
slug = 'flavor_choice'
help_text_template = ("project/instances/"
"_flavors_and_quotas.html")
def populate_flavor_choices(self, request, context):
old_flavor_id = context.get('old_flavor_id')
flavors = context.get('flavors').values()
flavors = [flavor for flavor in flavors if flavor.id != old_flavor_id]
if flavors:
if len(flavors) > 1:
flavors = instance_utils.sort_flavor_list(request, flavors)
else:
flavor = flavors[0]
flavors = [(flavor.id, flavor.name)]
flavors.insert(0, ("", _("Select a New Flavor")))
else:
flavors.insert(0, ("", _("No flavors available")))
return flavors
def get_help_text(self, extra_context=None):
extra = {} if extra_context is None else dict(extra_context)
try:
extra['usages'] = api.nova.tenant_absolute_limits(self.request,
reserved=True)
extra['usages_json'] = json.dumps(extra['usages'])
flavors = json.dumps([f._info for f in
instance_utils.flavor_list(self.request)])
extra['flavors'] = flavors
extra['resize_instance'] = True
except Exception:
exceptions.handle(self.request,
_("Unable to retrieve quota information."))
return super(SetFlavorChoiceAction, self).get_help_text(extra)
class SetFlavorChoice(workflows.Step):
action_class = SetFlavorChoiceAction
depends_on = ("instance_id", "name")
contributes = ("old_flavor_id", "old_flavor_name", "flavors", "flavor")
class ResizeInstance(workflows.Workflow):
slug = "resize_instance"
name = _("Resize Instance")
finalize_button_name = _("Resize")
success_message = _('Request for resizing of instance "%s" '
'has been submitted.')
failure_message = _('Unable to resize instance "%s".')
success_url = "horizon:project:instances:index"
default_steps = (SetFlavorChoice, create_instance.SetAdvanced)
def format_status_message(self, message):
return message % self.context.get('name', 'unknown instance')
@sensitive_variables('context')
def handle(self, request, context):
instance_id = context.get('instance_id', None)
flavor = context.get('flavor', None)
disk_config = context.get('disk_config', None)
try:
api.nova.server_resize(request, instance_id, flavor, disk_config)
return True
except Exception:
exceptions.handle(request)
return False
| true | true |
f71baf91c9ac2a1be7c1a45f7c74c72209692386 | 207 | py | Python | tests/test_MBus_connect.py | droid4control/python-mbus | 8e26c1847c06e57bc0e878ef3d6610dc9ba913b4 | [
"BSD-3-Clause"
] | 23 | 2015-05-19T15:57:40.000Z | 2021-03-18T11:33:22.000Z | tests/test_MBus_connect.py | Sensenode/python-mbus | 9b598ada5b3da17bb513cf78e5b4a8f2a3f9a1f1 | [
"BSD-3-Clause"
] | 14 | 2015-09-20T20:26:22.000Z | 2020-05-13T16:39:15.000Z | tests/test_MBus_connect.py | neurobat/python-mbus | 8e26c1847c06e57bc0e878ef3d6610dc9ba913b4 | [
"BSD-3-Clause"
] | 22 | 2015-07-27T08:50:44.000Z | 2022-03-19T01:17:18.000Z | import sys
sys.path.append('../python-mbus')
import pytest
from mbus import MBus
@pytest.fixture
def mbus_tcp():
return MBus.MBus(host="127.0.0.1")
def test_connect(mbus_tcp):
mbus_tcp.connect()
| 14.785714 | 38 | 0.714976 | import sys
sys.path.append('../python-mbus')
import pytest
from mbus import MBus
@pytest.fixture
def mbus_tcp():
return MBus.MBus(host="127.0.0.1")
def test_connect(mbus_tcp):
mbus_tcp.connect()
| true | true |
f71bafa9a01675524b1c846aa6c881e2336cfcb0 | 609 | py | Python | utils.py | Duy-Vu/stock-network | 3e84cfc581cd07001e86c20101c91c2f8910deb2 | [
"MIT"
] | null | null | null | utils.py | Duy-Vu/stock-network | 3e84cfc581cd07001e86c20101c91c2f8910deb2 | [
"MIT"
] | null | null | null | utils.py | Duy-Vu/stock-network | 3e84cfc581cd07001e86c20101c91c2f8910deb2 | [
"MIT"
] | null | null | null | import numpy as np
def clean_data(df, out_df_dir=""):
df.dropna(axis=1, inplace=True)
if out_df_dir:
df.to_csv(out_df_dir)
return df
# Calculate log change of daily price
def log_change(series):
return np.log(series[1] / series[0])
# Calculate correaltion
def calculate_cor(df, start, end):
return df[start:end].rolling(
window=2,
min_periods=2
).apply(
log_change,
raw=True
).corr(method="pearson")
# Calculate profit
def take_profit(price, start, end):
return price.iloc[end]/price.iloc[start] - 1 | 20.3 | 48 | 0.62069 | import numpy as np
def clean_data(df, out_df_dir=""):
df.dropna(axis=1, inplace=True)
if out_df_dir:
df.to_csv(out_df_dir)
return df
def log_change(series):
return np.log(series[1] / series[0])
def calculate_cor(df, start, end):
return df[start:end].rolling(
window=2,
min_periods=2
).apply(
log_change,
raw=True
).corr(method="pearson")
def take_profit(price, start, end):
return price.iloc[end]/price.iloc[start] - 1 | true | true |
f71bb0f290045da4932989588f794fc5c7a82389 | 12,982 | py | Python | dateparser/data/numeral_translation_data/nb.py | bazingarj/dateparser | 48c4563fb7f6ce685fbd6d27e9e83257521d2203 | [
"BSD-3-Clause"
] | 8 | 2019-11-15T21:00:15.000Z | 2021-12-21T22:09:42.000Z | dateparser/data/numeral_translation_data/nb.py | bazingarj/dateparser | 48c4563fb7f6ce685fbd6d27e9e83257521d2203 | [
"BSD-3-Clause"
] | 9 | 2020-06-05T21:28:57.000Z | 2022-02-12T12:30:39.000Z | dateparser/data/numeral_translation_data/nb.py | bazingarj/dateparser | 48c4563fb7f6ce685fbd6d27e9e83257521d2203 | [
"BSD-3-Clause"
] | 21 | 2019-03-11T04:25:23.000Z | 2022-02-03T08:54:33.000Z | # -*- coding: utf-8 -*-
info = {
"%%and-small": {
"(0, 99)": "og =%%spellout-cardinal-reale=;",
"(100, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%%and-small-f": {
"(0, 99)": "og =%spellout-cardinal-feminine=;",
"(100, 'inf')": "=%spellout-cardinal-feminine=;"
},
"%%and-small-n": {
"(0, 99)": "og =%spellout-cardinal-neuter=;",
"(100, 'inf')": "=%spellout-cardinal-neuter=;"
},
"%%ord-fem-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-feminine=;"
},
"%%ord-fem-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-feminine=;"
},
"%%ord-fem-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-feminine=;"
},
"%%ord-fem-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-feminine=;"
},
"%%ord-masc-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-masculine=;"
},
"%%ord-masc-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-masculine=;"
},
"%%ord-masc-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-masculine=;"
},
"%%ord-masc-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-masculine=;"
},
"%%ord-neut-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-neuter=;"
},
"%%ord-neut-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-neuter=;"
},
"%%ord-neut-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-neuter=;"
},
"%%ord-neut-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-neuter=;"
},
"%%ord-plural-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-plural=;"
},
"%%ord-plural-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-plural=;"
},
"%%ord-plural-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-plural=;"
},
"%%ord-plural-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-plural=;"
},
"%%spellout-cardinal-reale": {
"0": "null;",
"1": "én;",
"2": "to;",
"3": "tre;",
"4": "fire;",
"5": "fem;",
"6": "seks;",
"7": "sju;",
"8": "åtte;",
"9": "ni;",
"10": "ti;",
"11": "elleve;",
"12": "tolv;",
"13": "tretten;",
"14": "fjorten;",
"15": "femten;",
"16": "seksten;",
"17": "sytten;",
"18": "atten;",
"19": "nitten;",
"(20, 29)": "tjue[>>];",
"(30, 39)": "tretti[>>];",
"(40, 49)": "førti[>>];",
"(50, 59)": "femti[>>];",
"(60, 69)": "seksti[>>];",
"(70, 79)": "sytti[>>];",
"(80, 89)": "åtti[>>];",
"(90, 99)": "nitti[>>];",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-cardinal-feminine": {
"0": "null;",
"1": "ei;",
"(2, 99)": "=%%spellout-cardinal-reale=;",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small-f>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small-f>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-cardinal-masculine": {
"(0, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%spellout-cardinal-neuter": {
"0": "null;",
"1": "ett;",
"(2, 19)": "=%%spellout-cardinal-reale=;",
"(20, 29)": "tjue[>>];",
"(30, 39)": "tretti[>>];",
"(40, 49)": "førti[>>];",
"(50, 59)": "femti[>>];",
"(60, 69)": "seksti[>>];",
"(70, 79)": "sytti[>>];",
"(80, 89)": "åtti[>>];",
"(90, 99)": "nitti[>>];",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small-n>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small-n>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-numbering": {
"(0, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%spellout-numbering-year": {
"(0, 9999)": "=%spellout-numbering=;",
"(10000, 'inf')": "=%spellout-numbering=;"
},
"%spellout-ordinal-feminine": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-fem-nde>;",
"(30, 39)": "tretti>%%ord-fem-nde>;",
"(40, 49)": "førti>%%ord-fem-nde>;",
"(50, 59)": "femti>%%ord-fem-nde>;",
"(60, 69)": "seksti>%%ord-fem-nde>;",
"(70, 79)": "sytti>%%ord-fem-nde>;",
"(80, 89)": "åtti>%%ord-fem-nde>;",
"(90, 99)": "nitti>%%ord-fem-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-fem-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-fem-de>;",
"(1000000, 1999999)": "én million>%%ord-fem-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-fem-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-fem-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-fem-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-fem-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-fem-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-fem-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-fem-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-masculine": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-masc-nde>;",
"(30, 39)": "tretti>%%ord-masc-nde>;",
"(40, 49)": "førti>%%ord-masc-nde>;",
"(50, 59)": "femti>%%ord-masc-nde>;",
"(60, 69)": "seksti>%%ord-masc-nde>;",
"(70, 79)": "sytti>%%ord-masc-nde>;",
"(80, 89)": "åtti>%%ord-masc-nde>;",
"(90, 99)": "nitti>%%ord-masc-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-masc-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-masc-de>;",
"(1000000, 1999999)": "én million>%%ord-masc-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-masc-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-masc-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-masc-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-masc-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-masc-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-masc-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-masc-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-neuter": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-neut-nde>;",
"(30, 39)": "tretti>%%ord-neut-nde>;",
"(40, 49)": "førti>%%ord-neut-nde>;",
"(50, 59)": "femti>%%ord-neut-nde>;",
"(60, 69)": "seksti>%%ord-neut-nde>;",
"(70, 79)": "sytti>%%ord-neut-nde>;",
"(80, 89)": "åtti>%%ord-neut-nde>;",
"(90, 99)": "nitti>%%ord-neut-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-neut-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-neut-de>;",
"(1000000, 1999999)": "én million>%%ord-neut-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-neut-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-neut-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-neut-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-neut-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-neut-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-neut-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-neut-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-plural": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-plural-nde>;",
"(30, 39)": "tretti>%%ord-plural-nde>;",
"(40, 49)": "førti>%%ord-plural-nde>;",
"(50, 59)": "femti>%%ord-plural-nde>;",
"(60, 69)": "seksti>%%ord-plural-nde>;",
"(70, 79)": "sytti>%%ord-plural-nde>;",
"(80, 89)": "åtti>%%ord-plural-nde>;",
"(90, 99)": "nitti>%%ord-plural-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-plural-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-plural-de>;",
"(1000000, 1999999)": "én million>%%ord-plural-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-plural-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-plural-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-plural-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-plural-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-plural-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-plural-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-plural-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
}
} | 41.082278 | 109 | 0.470498 |
info = {
"%%and-small": {
"(0, 99)": "og =%%spellout-cardinal-reale=;",
"(100, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%%and-small-f": {
"(0, 99)": "og =%spellout-cardinal-feminine=;",
"(100, 'inf')": "=%spellout-cardinal-feminine=;"
},
"%%and-small-n": {
"(0, 99)": "og =%spellout-cardinal-neuter=;",
"(100, 'inf')": "=%spellout-cardinal-neuter=;"
},
"%%ord-fem-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-feminine=;"
},
"%%ord-fem-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-feminine=;"
},
"%%ord-fem-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-feminine=;"
},
"%%ord-fem-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-feminine=;"
},
"%%ord-masc-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-masculine=;"
},
"%%ord-masc-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-masculine=;"
},
"%%ord-masc-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-masculine=;"
},
"%%ord-masc-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-masculine=;"
},
"%%ord-neut-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-neuter=;"
},
"%%ord-neut-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-neuter=;"
},
"%%ord-neut-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-neuter=;"
},
"%%ord-neut-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-neuter=;"
},
"%%ord-plural-de": {
"0": "de;",
"(1, 'inf')": "' =%spellout-ordinal-plural=;"
},
"%%ord-plural-nde": {
"0": "ende;",
"(1, 'inf')": "=%spellout-ordinal-plural=;"
},
"%%ord-plural-te": {
"0": "te;",
"(1, 'inf')": "' =%spellout-ordinal-plural=;"
},
"%%ord-plural-teer": {
"0": "te;",
"(1, 'inf')": "er =%spellout-ordinal-plural=;"
},
"%%spellout-cardinal-reale": {
"0": "null;",
"1": "én;",
"2": "to;",
"3": "tre;",
"4": "fire;",
"5": "fem;",
"6": "seks;",
"7": "sju;",
"8": "åtte;",
"9": "ni;",
"10": "ti;",
"11": "elleve;",
"12": "tolv;",
"13": "tretten;",
"14": "fjorten;",
"15": "femten;",
"16": "seksten;",
"17": "sytten;",
"18": "atten;",
"19": "nitten;",
"(20, 29)": "tjue[>>];",
"(30, 39)": "tretti[>>];",
"(40, 49)": "førti[>>];",
"(50, 59)": "femti[>>];",
"(60, 69)": "seksti[>>];",
"(70, 79)": "sytti[>>];",
"(80, 89)": "åtti[>>];",
"(90, 99)": "nitti[>>];",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-cardinal-feminine": {
"0": "null;",
"1": "ei;",
"(2, 99)": "=%%spellout-cardinal-reale=;",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small-f>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small-f>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-cardinal-masculine": {
"(0, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%spellout-cardinal-neuter": {
"0": "null;",
"1": "ett;",
"(2, 19)": "=%%spellout-cardinal-reale=;",
"(20, 29)": "tjue[>>];",
"(30, 39)": "tretti[>>];",
"(40, 49)": "førti[>>];",
"(50, 59)": "femti[>>];",
"(60, 69)": "seksti[>>];",
"(70, 79)": "sytti[>>];",
"(80, 89)": "åtti[>>];",
"(90, 99)": "nitti[>>];",
"(100, 199)": "hundre[ og >>];",
"(200, 999)": "<%spellout-cardinal-neuter< hundre[ og >>];",
"(1000, 1999)": "tusen[ >%%and-small-n>];",
"(2000, 999999)": "<%spellout-cardinal-neuter< tusen[ >%%and-small-n>];",
"(1000000, 1999999)": "én million[ >>];",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< millioner[ >>];",
"(1000000000, 1999999999)": "én milliard[ >>];",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliarder[ >>];",
"(1000000000000, 1999999999999)": "én billion[ >>];",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billioner[ >>];",
"(1000000000000000, 1999999999999999)": "én billiard[ >>];",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiarder[ >>];",
"(1000000000000000000, 'inf')": "=#,##0=;"
},
"%spellout-numbering": {
"(0, 'inf')": "=%%spellout-cardinal-reale=;"
},
"%spellout-numbering-year": {
"(0, 9999)": "=%spellout-numbering=;",
"(10000, 'inf')": "=%spellout-numbering=;"
},
"%spellout-ordinal-feminine": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-fem-nde>;",
"(30, 39)": "tretti>%%ord-fem-nde>;",
"(40, 49)": "førti>%%ord-fem-nde>;",
"(50, 59)": "femti>%%ord-fem-nde>;",
"(60, 69)": "seksti>%%ord-fem-nde>;",
"(70, 79)": "sytti>%%ord-fem-nde>;",
"(80, 89)": "åtti>%%ord-fem-nde>;",
"(90, 99)": "nitti>%%ord-fem-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-fem-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-fem-de>;",
"(1000000, 1999999)": "én million>%%ord-fem-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-fem-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-fem-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-fem-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-fem-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-fem-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-fem-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-fem-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-masculine": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-masc-nde>;",
"(30, 39)": "tretti>%%ord-masc-nde>;",
"(40, 49)": "førti>%%ord-masc-nde>;",
"(50, 59)": "femti>%%ord-masc-nde>;",
"(60, 69)": "seksti>%%ord-masc-nde>;",
"(70, 79)": "sytti>%%ord-masc-nde>;",
"(80, 89)": "åtti>%%ord-masc-nde>;",
"(90, 99)": "nitti>%%ord-masc-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-masc-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-masc-de>;",
"(1000000, 1999999)": "én million>%%ord-masc-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-masc-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-masc-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-masc-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-masc-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-masc-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-masc-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-masc-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-neuter": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-neut-nde>;",
"(30, 39)": "tretti>%%ord-neut-nde>;",
"(40, 49)": "førti>%%ord-neut-nde>;",
"(50, 59)": "femti>%%ord-neut-nde>;",
"(60, 69)": "seksti>%%ord-neut-nde>;",
"(70, 79)": "sytti>%%ord-neut-nde>;",
"(80, 89)": "åtti>%%ord-neut-nde>;",
"(90, 99)": "nitti>%%ord-neut-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-neut-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-neut-de>;",
"(1000000, 1999999)": "én million>%%ord-neut-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-neut-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-neut-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-neut-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-neut-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-neut-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-neut-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-neut-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
},
"%spellout-ordinal-plural": {
"0": "nullte;",
"1": "første;",
"2": "andre;",
"3": "tredje;",
"4": "fjerde;",
"5": "femte;",
"6": "sjette;",
"7": "sjuende;",
"8": "åttende;",
"9": "niende;",
"10": "tiende;",
"11": "ellevte;",
"12": "tolvte;",
"(13, 19)": "=%spellout-cardinal-neuter=de;",
"(20, 29)": "tjue>%%ord-plural-nde>;",
"(30, 39)": "tretti>%%ord-plural-nde>;",
"(40, 49)": "førti>%%ord-plural-nde>;",
"(50, 59)": "femti>%%ord-plural-nde>;",
"(60, 69)": "seksti>%%ord-plural-nde>;",
"(70, 79)": "sytti>%%ord-plural-nde>;",
"(80, 89)": "åtti>%%ord-plural-nde>;",
"(90, 99)": "nitti>%%ord-plural-nde>;",
"(100, 999)": "<%spellout-numbering<hundre>%%ord-plural-de>;",
"(1000, 999999)": "<%spellout-numbering<tusen>%%ord-plural-de>;",
"(1000000, 1999999)": "én million>%%ord-plural-te>;",
"(2000000, 999999999)": "<%%spellout-cardinal-reale< million>%%ord-plural-teer>;",
"(1000000000, 1999999999)": "én milliard>%%ord-plural-te>;",
"(2000000000, 999999999999)": "<%%spellout-cardinal-reale< milliard>%%ord-plural-teer>;",
"(1000000000000, 1999999999999)": "én billion>%%ord-plural-te>;",
"(2000000000000, 999999999999999)": "<%%spellout-cardinal-reale< billion>%%ord-plural-teer>;",
"(1000000000000000, 1999999999999999)": "én billiard>%%ord-plural-te>;",
"(2000000000000000, 999999999999999999)": "<%%spellout-cardinal-reale< billiard>%%ord-plural-teer>;",
"(1000000000000000000, 'inf')": "=#,##0=.;"
}
} | true | true |
f71bb2656be1b32d52b27e3457db0d1c0fb78c7c | 1,806 | py | Python | networks/example_ParticleTransformer.py | jet-universe/particle_transformer | 68a7fbcd7d39a64b753251064f120462400895a1 | [
"MIT"
] | 2 | 2022-03-30T12:07:17.000Z | 2022-03-30T13:22:18.000Z | networks/example_ParticleTransformer.py | jet-universe/particle_transformer | 68a7fbcd7d39a64b753251064f120462400895a1 | [
"MIT"
] | null | null | null | networks/example_ParticleTransformer.py | jet-universe/particle_transformer | 68a7fbcd7d39a64b753251064f120462400895a1 | [
"MIT"
] | null | null | null | import os
import torch
from weaver.utils.logger import _logger
from weaver.utils.import_tools import import_module
ParticleTransformer = import_module(
os.path.join(os.path.dirname(__file__), 'ParticleTransformer.py'), 'ParT').ParticleTransformer
class ParticleTransformerWrapper(torch.nn.Module):
def __init__(self, **kwargs) -> None:
super().__init__()
self.mod = ParticleTransformer(**kwargs)
@torch.jit.ignore
def no_weight_decay(self):
return {'mod.cls_token', }
def forward(self, points, features, lorentz_vectors, mask):
return self.mod(features, v=lorentz_vectors, mask=mask)
def get_model(data_config, **kwargs):
cfg = dict(
input_dim=len(data_config.input_dicts['pf_features']),
num_classes=len(data_config.label_value),
# network configurations
pair_input_dim=4,
embed_dims=[128, 512, 128],
pair_embed_dims=[64, 64, 64],
num_heads=8,
num_layers=8,
num_cls_layers=2,
block_params=None,
cls_block_params={'dropout': 0, 'attn_dropout': 0, 'activation_dropout': 0},
fc_params=[],
activation='gelu',
# misc
trim=True,
for_inference=False,
)
cfg.update(**kwargs)
_logger.info('Model config: %s' % str(cfg))
model = ParticleTransformerWrapper(**cfg)
model_info = {
'input_names': list(data_config.input_names),
'input_shapes': {k: ((1,) + s[1:]) for k, s in data_config.input_shapes.items()},
'output_names': ['softmax'],
'dynamic_axes': {**{k: {0: 'N', 2: 'n_' + k.split('_')[0]} for k in data_config.input_names}, **{'softmax': {0: 'N'}}},
}
return model, model_info
def get_loss(data_config, **kwargs):
return torch.nn.CrossEntropyLoss()
| 30.1 | 127 | 0.640089 | import os
import torch
from weaver.utils.logger import _logger
from weaver.utils.import_tools import import_module
ParticleTransformer = import_module(
os.path.join(os.path.dirname(__file__), 'ParticleTransformer.py'), 'ParT').ParticleTransformer
class ParticleTransformerWrapper(torch.nn.Module):
def __init__(self, **kwargs) -> None:
super().__init__()
self.mod = ParticleTransformer(**kwargs)
@torch.jit.ignore
def no_weight_decay(self):
return {'mod.cls_token', }
def forward(self, points, features, lorentz_vectors, mask):
return self.mod(features, v=lorentz_vectors, mask=mask)
def get_model(data_config, **kwargs):
cfg = dict(
input_dim=len(data_config.input_dicts['pf_features']),
num_classes=len(data_config.label_value),
pair_input_dim=4,
embed_dims=[128, 512, 128],
pair_embed_dims=[64, 64, 64],
num_heads=8,
num_layers=8,
num_cls_layers=2,
block_params=None,
cls_block_params={'dropout': 0, 'attn_dropout': 0, 'activation_dropout': 0},
fc_params=[],
activation='gelu',
trim=True,
for_inference=False,
)
cfg.update(**kwargs)
_logger.info('Model config: %s' % str(cfg))
model = ParticleTransformerWrapper(**cfg)
model_info = {
'input_names': list(data_config.input_names),
'input_shapes': {k: ((1,) + s[1:]) for k, s in data_config.input_shapes.items()},
'output_names': ['softmax'],
'dynamic_axes': {**{k: {0: 'N', 2: 'n_' + k.split('_')[0]} for k in data_config.input_names}, **{'softmax': {0: 'N'}}},
}
return model, model_info
def get_loss(data_config, **kwargs):
return torch.nn.CrossEntropyLoss()
| true | true |
f71bb3b612e73dc0ead31535809f8a66a642d316 | 35 | py | Python | tests/translators/__init__.py | cancervariants/variant-normalization | e89a9f8366a659c82b2042aeb7effe339851bfb4 | [
"MIT"
] | 1 | 2022-01-19T18:17:49.000Z | 2022-01-19T18:17:49.000Z | tests/translators/__init__.py | cancervariants/variation-normalization | 9c8fbab1562591ae9445d82ddd15df29f1ea1f5a | [
"MIT"
] | 99 | 2021-06-07T12:50:34.000Z | 2022-03-23T13:38:29.000Z | tests/translators/__init__.py | cancervariants/variant-normalization | e89a9f8366a659c82b2042aeb7effe339851bfb4 | [
"MIT"
] | null | null | null | """The test translator package."""
| 17.5 | 34 | 0.685714 | true | true | |
f71bb42f23d2dcf4e3a6c7c499095bafb5976cc2 | 4,781 | py | Python | nicos_mlz/kws1/testscripts/counting.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 12 | 2019-11-06T15:40:36.000Z | 2022-01-01T16:23:00.000Z | nicos_mlz/kws1/testscripts/counting.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 91 | 2020-08-18T09:20:26.000Z | 2022-02-01T11:07:14.000Z | nicos_mlz/kws1/testscripts/counting.py | jkrueger1/nicos | 5f4ce66c312dedd78995f9d91e8a6e3c891b262b | [
"CC-BY-3.0",
"Apache-2.0",
"CC-BY-4.0"
] | 6 | 2020-01-11T10:52:30.000Z | 2022-02-25T12:35:23.000Z | # pylint: skip-file
ClearSamples()
SetSample(1, 'Alu1', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 208.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(2, 'Alu2', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 235.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(3, 'Alu3', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 262.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(4, 'Alu10', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 289.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(5, 'Alu11', aperture=(1.2, 5.4, 12.0, 12.0), position={u'sam_trans_x': 316.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(6, 'Alu19', aperture=(1.2, 5.4, 15.0, 15.0), position={u'sam_trans_x': 343.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetupNormal()
notify('new test script started')
kwscount(sample='Alu1' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu2' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu3' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu10', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu11', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu19', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
notify('7A, 20m, 10.0%, finished')
kwscount(sample='Alu1' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu2' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu3' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu10', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu11', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu19', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
notify('6A, 20m, chopper off, finished')
kwscount(sample='Alu1' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu2' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu3' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu10', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu11', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu19', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
notify('5A, 8m, 2.5%, finished')
kwscount(sample='Alu1' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu2' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu3' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu10', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu11', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu19', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
notify('10A, 8m, chopper off, finished')
| 116.609756 | 173 | 0.673081 |
ClearSamples()
SetSample(1, 'Alu1', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 208.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(2, 'Alu2', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 235.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(3, 'Alu3', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 262.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(4, 'Alu10', aperture=(1.2, 5.4, 7.0, 7.0), position={u'sam_trans_x': 289.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(5, 'Alu11', aperture=(1.2, 5.4, 12.0, 12.0), position={u'sam_trans_x': 316.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetSample(6, 'Alu19', aperture=(1.2, 5.4, 15.0, 15.0), position={u'sam_trans_x': 343.0, u'sam_trans_y': 202.5}, timefactor=1.0, thickness=1.0, detoffset=-315.0, comment=u'')
SetupNormal()
notify('new test script started')
kwscount(sample='Alu1' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu2' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu3' , selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu10', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu11', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
kwscount(sample='Alu19', selector='7A' , detector='20m' , chopper='10.0%', collimation='20m (30x30)', polarizer='up' , time=720.0, T_julabo=25.0)
notify('7A, 20m, 10.0%, finished')
kwscount(sample='Alu1' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu2' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu3' , selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu10', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu11', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
kwscount(sample='Alu19', selector='6A' , detector='20m' , chopper='off' , collimation='20m (30x30)', polarizer='down', time=720.0, T_julabo=20.0)
notify('6A, 20m, chopper off, finished')
kwscount(sample='Alu1' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu2' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu3' , selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu10', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu11', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
kwscount(sample='Alu19', selector='5A' , detector='8m' , chopper='2.5%', collimation='8m (30x30)' , polarizer='up' , time=720.0, T_julabo=30.0)
notify('5A, 8m, 2.5%, finished')
kwscount(sample='Alu1' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu2' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu3' , selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu10', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu11', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
kwscount(sample='Alu19', selector='10A', detector='8m' , chopper='off' , collimation='14m (30x30)', polarizer='out' , time=720.0, T_julabo=20.0)
notify('10A, 8m, chopper off, finished')
| true | true |
f71bb4a59b7a4873bb3899fb045f2a55091bf311 | 13,199 | py | Python | sen/tui/ui.py | lachmanfrantisek/sen | a45e87bcdd60de1a246bd62dfdec32f60027bd37 | [
"MIT"
] | 956 | 2015-10-22T14:32:14.000Z | 2022-03-21T02:27:28.000Z | sen/tui/ui.py | lachmanfrantisek/sen | a45e87bcdd60de1a246bd62dfdec32f60027bd37 | [
"MIT"
] | 146 | 2015-09-29T10:04:14.000Z | 2022-02-22T08:28:08.000Z | sen/tui/ui.py | lachmanfrantisek/sen | a45e87bcdd60de1a246bd62dfdec32f60027bd37 | [
"MIT"
] | 77 | 2015-11-12T22:02:18.000Z | 2022-01-24T10:14:46.000Z | """
This is a framework for terminal interfaces built on top of urwid.Frame.
It must NOT contain any application specific code.
"""
import logging
import threading
from concurrent.futures.thread import ThreadPoolExecutor
import urwid
from sen.exceptions import NotifyError
from sen.tui.commands.base import (
FrontendPriority, BackendPriority,
SameThreadPriority, KeyNotMapped
)
from sen.tui.constants import CLEAR_NOTIF_BAR_MESSAGE_IN
from sen.tui.widgets.util import ThreadSafeFrame
from sen.util import log_traceback, OrderedSet
logger = logging.getLogger(__name__)
class ConcurrencyMixin:
def __init__(self):
# worker for long-running tasks - requests
self.worker = ThreadPoolExecutor(max_workers=4)
# worker for quick ui operations
self.ui_worker = ThreadPoolExecutor(max_workers=2)
@staticmethod
def _run(worker, f, *args, **kwargs):
# TODO: do another wrapper to wrap notify exceptions and show them
f = log_traceback(f)
worker.submit(f, *args, **kwargs)
def run_in_background(self, task, *args, **kwargs):
logger.info("running task %r(%s, %s) in background", task, args, kwargs)
self._run(self.worker, task, *args, **kwargs)
def run_quickly_in_background(self, task, *args, **kwargs):
logger.info("running a quick task %r(%s, %s) in background", task, args, kwargs)
self._run(self.ui_worker, task, *args, **kwargs)
class UI(ThreadSafeFrame, ConcurrencyMixin):
"""
handles all UI-specific code
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# widget -> message or None
self.widget_message_dict = {}
# message -> widget
self.message_widget_dict = {}
self.status_bar = None
self.prompt_bar = None
# lock when managing notifications:
# * when accessing self.notification_*
# * when accessing widgets
# and most importantly, remember, locking is voodoo
self.notifications_lock = threading.RLock()
# populated when loop and UI are instantiated
self.loop = None
self.commander = None
self.buffers = []
self.buffer_movement_history = OrderedSet()
self.main_list_buffer = None # singleton
self.current_buffer = None
def refresh(self):
self.loop.refresh()
def quit(self):
"""
This could be called from another thread, so let's do this via alarm
"""
def q(*args):
raise urwid.ExitMainLoop()
self.worker.shutdown(wait=False)
self.ui_worker.shutdown(wait=False)
self.loop.set_alarm_in(0, q)
# FIXME: move these to separate mixin
def _set_main_widget(self, widget, redraw):
"""
add provided widget to widget list and display it
:param widget:
:return:
"""
self.set_body(widget)
self.reload_footer()
if redraw:
logger.debug("redraw main widget")
self.refresh()
def display_buffer(self, buffer, redraw=True):
"""
display provided buffer
:param buffer: Buffer
:return:
"""
logger.debug("display buffer %r", buffer)
self.buffer_movement_history.append(buffer)
self.current_buffer = buffer
self._set_main_widget(buffer.widget, redraw=redraw)
def add_and_display_buffer(self, buffer, redraw=True):
"""
add provided buffer to buffer list and display it
:param buffer:
:return:
"""
# FIXME: some buffers have arguments, do a proper comparison -- override __eq__
if buffer not in self.buffers:
logger.debug("adding new buffer {!r}".format(buffer))
self.buffers.append(buffer)
self.display_buffer(buffer, redraw=redraw)
def pick_and_display_buffer(self, i):
"""
pick i-th buffer from list and display it
:param i: int
:return: None
"""
if len(self.buffers) == 1:
# we don't need to display anything
# listing is already displayed
return
else:
try:
self.display_buffer(self.buffers[i])
except IndexError:
# i > len
self.display_buffer(self.buffers[0])
@property
def current_buffer_index(self):
return self.buffers.index(self.current_buffer)
def remove_current_buffer(self, close_if_no_buffer=False):
if len(self.buffers) == 1 and not close_if_no_buffer:
return
self.buffers.remove(self.current_buffer)
self.buffer_movement_history.remove(self.current_buffer)
self.current_buffer.destroy()
if len(self.buffers) > 0:
self.display_buffer(self.buffer_movement_history[-1], True)
return len(self.buffers)
def reload_footer(self, refresh=True, rebuild_statusbar=True):
logger.debug("reload footer")
footer = list(self.widget_message_dict.keys())
if self.prompt_bar:
footer.append(self.prompt_bar)
else:
if rebuild_statusbar or self.status_bar is None:
self.status_bar = self.build_statusbar()
footer.append(self.status_bar)
# logger.debug(footer)
self.set_footer(urwid.Pile(footer))
if refresh:
self.loop.refresh()
def build_statusbar(self):
"""construct and return statusbar widget"""
if self.prompt_bar:
logger.info("prompt is active, won't build status bar")
return
try:
left_widgets = self.current_buffer.build_status_bar() or []
except AttributeError:
left_widgets = []
text_list = []
# FIXME: this code should be placed in buffer
# TODO: display current active worker threads
for idx, buffer in enumerate(self.buffers):
# #1 [I] fedora #2 [L]
fmt = "#{idx} [{name}]"
markup = fmt.format(idx=idx, name=buffer.display_name)
text_list.append((
"status_box_focus" if buffer == self.current_buffer else "status_box",
markup,
))
text_list.append(" ")
text_list = text_list[:-1]
if text_list:
buffer_text = urwid.Text(text_list, align="right")
else:
buffer_text = urwid.Text("", align="right")
columns = urwid.Columns(left_widgets + [buffer_text])
return urwid.AttrMap(columns, "status")
def remove_notification_message(self, message):
logger.debug("requested remove of message %r from notif bar", message)
with self.notifications_lock:
try:
w = self.message_widget_dict[message]
except KeyError:
logger.warning("there is no notification %r displayed: %s",
message, self.message_widget_dict)
return
else:
logger.debug("remove widget %r from new pile", w)
del self.widget_message_dict[w]
del self.message_widget_dict[message]
self.reload_footer(rebuild_statusbar=False)
def remove_widget(self, widget, message=None):
logger.debug("remove widget %r from notif bar", widget)
with self.notifications_lock:
try:
del self.widget_message_dict[widget]
except KeyError:
logger.info("widget %s was already removed", widget)
return
if message:
del self.message_widget_dict[message]
self.reload_footer(rebuild_statusbar=False)
def notify_message(self, message, level="info", clear_if_dupl=True,
clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN):
"""
:param message, str
:param level: str, {info, error}
:param clear_if_dupl: bool, if True, don't display the notification again
:param clear_in: seconds, remove the notificantion after some time
opens notification popup.
"""
with self.notifications_lock:
if clear_if_dupl and message in self.message_widget_dict.keys():
logger.debug("notification %r is already displayed", message)
return
logger.debug("display notification %r", message)
widget = urwid.AttrMap(urwid.Text(message), "notif_{}".format(level))
return self.notify_widget(widget, message=message, clear_in=clear_in)
def notify_widget(self, widget, message=None, clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN):
"""
opens notification popup.
:param widget: instance of Widget, widget to display
:param message: str, message to remove from list of notifications
:param clear_in: int, time seconds when notification should be removed
"""
@log_traceback
def clear_notification(*args, **kwargs):
# the point here is the log_traceback
self.remove_widget(widget, message=message)
if not widget:
return
logger.debug("display notification widget %s", widget)
with self.notifications_lock:
self.widget_message_dict[widget] = message
if message:
self.message_widget_dict[message] = widget
self.reload_footer(rebuild_statusbar=False)
self.loop.set_alarm_in(clear_in, clear_notification)
return widget
def run_command(self, command_input, queue=None, **kwargs):
kwargs["buffer"] = self.current_buffer
command = self.commander.get_command(command_input, **kwargs)
if command is None:
return
if queue is None:
queue = command.priority
if isinstance(queue, FrontendPriority):
self.run_quickly_in_background(command.run)
elif isinstance(queue, BackendPriority):
self.run_in_background(command.run)
elif isinstance(queue, SameThreadPriority):
logger.info("running command %s", command)
try:
command.run()
except NotifyError as ex:
self.notify_message(str(ex), level="error")
logger.error(repr(ex))
else:
raise RuntimeError("command %s doesn't have any priority: %s %s" %
(command_input, command.priority, FrontendPriority))
def run_command_by_key(self, key, size, **kwargs):
command_input = self.commander.get_command_input_by_key(key)
self.run_command(command_input, size=size, **kwargs)
def keypress(self, size, key):
logger.debug("%s keypress %r", self.__class__.__name__, key)
# we should pass the key to header, body, footer first so it's consumed in e.g. statusbar
key = super().keypress(size, key)
if key is None:
logger.info("key was consumed by frame components")
return
logger.info("key was not consumed by frame components")
focused_docker_object = None
selected_widget = getattr(self.current_buffer, "widget", None)
if selected_widget:
focused_docker_object = getattr(self.current_buffer.widget, "focused_docker_object", None)
logger.debug("focused docker object is %s", focused_docker_object)
try:
self.run_command_by_key(
key,
docker_object=focused_docker_object,
size=size
)
except KeyNotMapped as ex:
super_class = ThreadSafeFrame
logger.debug("calling: %s.keypress(%s, %s)", super_class, size, key)
# TODO: up/down doesn't do anything if len(lines) < screen height, that's confusing
key = super_class.keypress(self, size, key)
if key:
self.notify_message(str(ex), level="error")
logger.debug("was key handled? %s", "yes" if key is None else "no")
return key
return
class ThreadSafeLoop(urwid.MainLoop):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.refresh_lock = threading.RLock()
def entering_idle(self):
with self.refresh_lock:
return super().entering_idle()
def refresh(self):
"""
explicitely refresh user interface; useful when changing widgets dynamically
"""
logger.debug("refresh user interface")
try:
with self.refresh_lock:
self.draw_screen()
except AssertionError:
logger.warning("application is not running")
pass
def get_app_in_loop(pallete):
screen = urwid.raw_display.Screen()
screen.set_terminal_properties(256)
screen.register_palette(pallete)
ui = UI(urwid.SolidFill())
decorated_ui = urwid.AttrMap(ui, "root")
loop = ThreadSafeLoop(decorated_ui, screen=screen, event_loop=urwid.AsyncioEventLoop(),
handle_mouse=False)
ui.loop = loop
return loop, ui
| 35.197333 | 102 | 0.615577 | import logging
import threading
from concurrent.futures.thread import ThreadPoolExecutor
import urwid
from sen.exceptions import NotifyError
from sen.tui.commands.base import (
FrontendPriority, BackendPriority,
SameThreadPriority, KeyNotMapped
)
from sen.tui.constants import CLEAR_NOTIF_BAR_MESSAGE_IN
from sen.tui.widgets.util import ThreadSafeFrame
from sen.util import log_traceback, OrderedSet
logger = logging.getLogger(__name__)
class ConcurrencyMixin:
def __init__(self):
self.worker = ThreadPoolExecutor(max_workers=4)
self.ui_worker = ThreadPoolExecutor(max_workers=2)
@staticmethod
def _run(worker, f, *args, **kwargs):
f = log_traceback(f)
worker.submit(f, *args, **kwargs)
def run_in_background(self, task, *args, **kwargs):
logger.info("running task %r(%s, %s) in background", task, args, kwargs)
self._run(self.worker, task, *args, **kwargs)
def run_quickly_in_background(self, task, *args, **kwargs):
logger.info("running a quick task %r(%s, %s) in background", task, args, kwargs)
self._run(self.ui_worker, task, *args, **kwargs)
class UI(ThreadSafeFrame, ConcurrencyMixin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.widget_message_dict = {}
self.message_widget_dict = {}
self.status_bar = None
self.prompt_bar = None
self.notifications_lock = threading.RLock()
self.loop = None
self.commander = None
self.buffers = []
self.buffer_movement_history = OrderedSet()
self.main_list_buffer = None
self.current_buffer = None
def refresh(self):
self.loop.refresh()
def quit(self):
def q(*args):
raise urwid.ExitMainLoop()
self.worker.shutdown(wait=False)
self.ui_worker.shutdown(wait=False)
self.loop.set_alarm_in(0, q)
def _set_main_widget(self, widget, redraw):
self.set_body(widget)
self.reload_footer()
if redraw:
logger.debug("redraw main widget")
self.refresh()
def display_buffer(self, buffer, redraw=True):
logger.debug("display buffer %r", buffer)
self.buffer_movement_history.append(buffer)
self.current_buffer = buffer
self._set_main_widget(buffer.widget, redraw=redraw)
def add_and_display_buffer(self, buffer, redraw=True):
if buffer not in self.buffers:
logger.debug("adding new buffer {!r}".format(buffer))
self.buffers.append(buffer)
self.display_buffer(buffer, redraw=redraw)
def pick_and_display_buffer(self, i):
if len(self.buffers) == 1:
# listing is already displayed
return
else:
try:
self.display_buffer(self.buffers[i])
except IndexError:
# i > len
self.display_buffer(self.buffers[0])
@property
def current_buffer_index(self):
return self.buffers.index(self.current_buffer)
def remove_current_buffer(self, close_if_no_buffer=False):
if len(self.buffers) == 1 and not close_if_no_buffer:
return
self.buffers.remove(self.current_buffer)
self.buffer_movement_history.remove(self.current_buffer)
self.current_buffer.destroy()
if len(self.buffers) > 0:
self.display_buffer(self.buffer_movement_history[-1], True)
return len(self.buffers)
def reload_footer(self, refresh=True, rebuild_statusbar=True):
logger.debug("reload footer")
footer = list(self.widget_message_dict.keys())
if self.prompt_bar:
footer.append(self.prompt_bar)
else:
if rebuild_statusbar or self.status_bar is None:
self.status_bar = self.build_statusbar()
footer.append(self.status_bar)
# logger.debug(footer)
self.set_footer(urwid.Pile(footer))
if refresh:
self.loop.refresh()
def build_statusbar(self):
if self.prompt_bar:
logger.info("prompt is active, won't build status bar")
return
try:
left_widgets = self.current_buffer.build_status_bar() or []
except AttributeError:
left_widgets = []
text_list = []
for idx, buffer in enumerate(self.buffers):
[{name}]"
markup = fmt.format(idx=idx, name=buffer.display_name)
text_list.append((
"status_box_focus" if buffer == self.current_buffer else "status_box",
markup,
))
text_list.append(" ")
text_list = text_list[:-1]
if text_list:
buffer_text = urwid.Text(text_list, align="right")
else:
buffer_text = urwid.Text("", align="right")
columns = urwid.Columns(left_widgets + [buffer_text])
return urwid.AttrMap(columns, "status")
def remove_notification_message(self, message):
logger.debug("requested remove of message %r from notif bar", message)
with self.notifications_lock:
try:
w = self.message_widget_dict[message]
except KeyError:
logger.warning("there is no notification %r displayed: %s",
message, self.message_widget_dict)
return
else:
logger.debug("remove widget %r from new pile", w)
del self.widget_message_dict[w]
del self.message_widget_dict[message]
self.reload_footer(rebuild_statusbar=False)
def remove_widget(self, widget, message=None):
logger.debug("remove widget %r from notif bar", widget)
with self.notifications_lock:
try:
del self.widget_message_dict[widget]
except KeyError:
logger.info("widget %s was already removed", widget)
return
if message:
del self.message_widget_dict[message]
self.reload_footer(rebuild_statusbar=False)
def notify_message(self, message, level="info", clear_if_dupl=True,
clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN):
with self.notifications_lock:
if clear_if_dupl and message in self.message_widget_dict.keys():
logger.debug("notification %r is already displayed", message)
return
logger.debug("display notification %r", message)
widget = urwid.AttrMap(urwid.Text(message), "notif_{}".format(level))
return self.notify_widget(widget, message=message, clear_in=clear_in)
def notify_widget(self, widget, message=None, clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN):
@log_traceback
def clear_notification(*args, **kwargs):
self.remove_widget(widget, message=message)
if not widget:
return
logger.debug("display notification widget %s", widget)
with self.notifications_lock:
self.widget_message_dict[widget] = message
if message:
self.message_widget_dict[message] = widget
self.reload_footer(rebuild_statusbar=False)
self.loop.set_alarm_in(clear_in, clear_notification)
return widget
def run_command(self, command_input, queue=None, **kwargs):
kwargs["buffer"] = self.current_buffer
command = self.commander.get_command(command_input, **kwargs)
if command is None:
return
if queue is None:
queue = command.priority
if isinstance(queue, FrontendPriority):
self.run_quickly_in_background(command.run)
elif isinstance(queue, BackendPriority):
self.run_in_background(command.run)
elif isinstance(queue, SameThreadPriority):
logger.info("running command %s", command)
try:
command.run()
except NotifyError as ex:
self.notify_message(str(ex), level="error")
logger.error(repr(ex))
else:
raise RuntimeError("command %s doesn't have any priority: %s %s" %
(command_input, command.priority, FrontendPriority))
def run_command_by_key(self, key, size, **kwargs):
command_input = self.commander.get_command_input_by_key(key)
self.run_command(command_input, size=size, **kwargs)
def keypress(self, size, key):
logger.debug("%s keypress %r", self.__class__.__name__, key)
# we should pass the key to header, body, footer first so it's consumed in e.g. statusbar
key = super().keypress(size, key)
if key is None:
logger.info("key was consumed by frame components")
return
logger.info("key was not consumed by frame components")
focused_docker_object = None
selected_widget = getattr(self.current_buffer, "widget", None)
if selected_widget:
focused_docker_object = getattr(self.current_buffer.widget, "focused_docker_object", None)
logger.debug("focused docker object is %s", focused_docker_object)
try:
self.run_command_by_key(
key,
docker_object=focused_docker_object,
size=size
)
except KeyNotMapped as ex:
super_class = ThreadSafeFrame
logger.debug("calling: %s.keypress(%s, %s)", super_class, size, key)
key = super_class.keypress(self, size, key)
if key:
self.notify_message(str(ex), level="error")
logger.debug("was key handled? %s", "yes" if key is None else "no")
return key
return
class ThreadSafeLoop(urwid.MainLoop):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.refresh_lock = threading.RLock()
def entering_idle(self):
with self.refresh_lock:
return super().entering_idle()
def refresh(self):
logger.debug("refresh user interface")
try:
with self.refresh_lock:
self.draw_screen()
except AssertionError:
logger.warning("application is not running")
pass
def get_app_in_loop(pallete):
screen = urwid.raw_display.Screen()
screen.set_terminal_properties(256)
screen.register_palette(pallete)
ui = UI(urwid.SolidFill())
decorated_ui = urwid.AttrMap(ui, "root")
loop = ThreadSafeLoop(decorated_ui, screen=screen, event_loop=urwid.AsyncioEventLoop(),
handle_mouse=False)
ui.loop = loop
return loop, ui
| true | true |
f71bb74a3fd635e20003d3cfecbe5cb463ebe09a | 3,783 | py | Python | airbyte-integrations/connectors/source-marketo-singer/source_marketo_singer/source.py | abalustre/airbyte | e629613588620e8a4c48b155e0f414f41a005bd0 | [
"MIT"
] | 1 | 2021-11-04T07:55:40.000Z | 2021-11-04T07:55:40.000Z | airbyte-integrations/connectors/source-marketo-singer/source_marketo_singer/source.py | Outoftheblue-ai/airbyte | 98b18fd852ec70dafe02fb3ffe45b1ac30345cd0 | [
"MIT"
] | 1 | 2021-11-01T10:44:54.000Z | 2021-11-01T10:47:42.000Z | airbyte-integrations/connectors/source-marketo-singer/source_marketo_singer/source.py | Outoftheblue-ai/airbyte | 98b18fd852ec70dafe02fb3ffe45b1ac30345cd0 | [
"MIT"
] | null | null | null | #
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
from typing import Dict
from airbyte_protocol import AirbyteConnectionStatus, Status, SyncMode
from base_python import AirbyteLogger
from base_singer import BaseSingerSource, SyncModeInfo
class SourceMarketoSinger(BaseSingerSource):
tap_cmd = "tap-marketo"
tap_name = "Marketo API"
api_error = Exception
def transform_config(self, raw_config):
return {
"endpoint": raw_config["endpoint_url"],
"identity": raw_config["identity_url"],
"client_id": raw_config["client_id"],
"client_secret": raw_config["client_secret"],
"start_date": raw_config["start_date"],
}
def try_connect(self, logger: AirbyteLogger, config_path: str):
self.discover(logger, config_path)
def check_config(self, logger: AirbyteLogger, config_path: str, config: json) -> AirbyteConnectionStatus:
try:
self.try_connect(logger, config_path)
except self.api_error as err:
logger.error(f"Exception while connecting to {self.tap_name}: {err}")
# this should be in UI
error_msg = f"Unable to connect to {self.tap_name} with the provided credentials."
return AirbyteConnectionStatus(status=Status.FAILED, message=error_msg)
return AirbyteConnectionStatus(status=Status.SUCCEEDED)
def get_sync_mode_overrides(self) -> Dict[str, SyncModeInfo]:
incremental_streams = [
"leads",
"activities_visit_webpage",
"activities_fill_out_form",
"activities_click_link",
"activities_send_email",
"activities_email_delivered",
"activities_email_bounced",
"activities_unsubscribe_email",
"activities_open_email",
"activities_click_email",
"activities_new_lead",
"activities_change_data_value",
"activities_change_score",
"activities_add_to_list",
"activities_remove_from_list",
"activities_email_bounced_soft",
"activities_merge_leads",
"activities_add_to_opportunity",
"activities_remove_from_opportunity",
"activities_update_opportunity",
"activities_delete_lead",
"activities_send_alert",
"activities_send_sales_email",
"activities_open_sales_email",
"activities_click_sales_email",
"activities_receive_sales_email",
"activities_request_campaign",
"activities_sales_email_bounced",
"activities_change_lead_partition",
"activities_change_revenue_stage",
"activities_change_revenue_stage_manually",
"activities_change_status_in_progression",
"activities_change_segment",
"activities_call_webhook",
"activities_sent_forward_to_friend_email",
"activities_received_forward_to_friend_email",
"activities_add_to_nurture",
"activities_change_nurture_track",
"activities_change_nurture_cadence",
"activities_change_program_member_data",
"activities_push_lead_to_marketo",
"activities_share_content",
"campaigns",
"lists",
"programs",
]
return {s: SyncModeInfo([SyncMode.incremental], True, []) for s in incremental_streams}
def read_cmd(self, logger: AirbyteLogger, config_path: str, catalog_path: str, state_path: str = None) -> str:
state_opt = f"--state {state_path}" if state_path else ""
return f"{self.tap_cmd} --config {config_path} --properties {catalog_path} {state_opt}"
| 39.821053 | 114 | 0.651335 |
import json
from typing import Dict
from airbyte_protocol import AirbyteConnectionStatus, Status, SyncMode
from base_python import AirbyteLogger
from base_singer import BaseSingerSource, SyncModeInfo
class SourceMarketoSinger(BaseSingerSource):
tap_cmd = "tap-marketo"
tap_name = "Marketo API"
api_error = Exception
def transform_config(self, raw_config):
return {
"endpoint": raw_config["endpoint_url"],
"identity": raw_config["identity_url"],
"client_id": raw_config["client_id"],
"client_secret": raw_config["client_secret"],
"start_date": raw_config["start_date"],
}
def try_connect(self, logger: AirbyteLogger, config_path: str):
self.discover(logger, config_path)
def check_config(self, logger: AirbyteLogger, config_path: str, config: json) -> AirbyteConnectionStatus:
try:
self.try_connect(logger, config_path)
except self.api_error as err:
logger.error(f"Exception while connecting to {self.tap_name}: {err}")
error_msg = f"Unable to connect to {self.tap_name} with the provided credentials."
return AirbyteConnectionStatus(status=Status.FAILED, message=error_msg)
return AirbyteConnectionStatus(status=Status.SUCCEEDED)
def get_sync_mode_overrides(self) -> Dict[str, SyncModeInfo]:
incremental_streams = [
"leads",
"activities_visit_webpage",
"activities_fill_out_form",
"activities_click_link",
"activities_send_email",
"activities_email_delivered",
"activities_email_bounced",
"activities_unsubscribe_email",
"activities_open_email",
"activities_click_email",
"activities_new_lead",
"activities_change_data_value",
"activities_change_score",
"activities_add_to_list",
"activities_remove_from_list",
"activities_email_bounced_soft",
"activities_merge_leads",
"activities_add_to_opportunity",
"activities_remove_from_opportunity",
"activities_update_opportunity",
"activities_delete_lead",
"activities_send_alert",
"activities_send_sales_email",
"activities_open_sales_email",
"activities_click_sales_email",
"activities_receive_sales_email",
"activities_request_campaign",
"activities_sales_email_bounced",
"activities_change_lead_partition",
"activities_change_revenue_stage",
"activities_change_revenue_stage_manually",
"activities_change_status_in_progression",
"activities_change_segment",
"activities_call_webhook",
"activities_sent_forward_to_friend_email",
"activities_received_forward_to_friend_email",
"activities_add_to_nurture",
"activities_change_nurture_track",
"activities_change_nurture_cadence",
"activities_change_program_member_data",
"activities_push_lead_to_marketo",
"activities_share_content",
"campaigns",
"lists",
"programs",
]
return {s: SyncModeInfo([SyncMode.incremental], True, []) for s in incremental_streams}
def read_cmd(self, logger: AirbyteLogger, config_path: str, catalog_path: str, state_path: str = None) -> str:
state_opt = f"--state {state_path}" if state_path else ""
return f"{self.tap_cmd} --config {config_path} --properties {catalog_path} {state_opt}"
| true | true |
f71bba63aef3cc3729067901106dcb6217bcab5d | 24,141 | py | Python | benchmarks/pipe.py | jessijzhao/fairscale | d6a8fc6dadc5d5ab4e3ee3f42f8cd570d70d30ec | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | benchmarks/pipe.py | jessijzhao/fairscale | d6a8fc6dadc5d5ab4e3ee3f42f8cd570d70d30ec | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | benchmarks/pipe.py | jessijzhao/fairscale | d6a8fc6dadc5d5ab4e3ee3f42f8cd570d70d30ec | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import argparse
import logging
import math
import os
import time
import warnings
from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm
import torch
from torch.distributed import rpc
import torch.multiprocessing as mp
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader
import torchtext
from torchtext.data.utils import get_tokenizer
from fairscale.nn import Pipe
from fairscale.nn.model_parallel import initialize_model_parallel
from fairscale.nn.model_parallel.initialize import get_data_parallel_group, get_pipeline_parallel_group
from fairscale.nn.pipe import LazyModule, pipe
from fairscale.optim import GradScaler
from fairscale.optim.oss import OSS
from fairscale.utils.testing import dist_init, get_worker_map
try:
from fairscale.optim import Adam # type: ignore
can_benchmark = True
except ImportError:
from torch.optim import Adam # type: ignore
can_benchmark = False
def init_random_seed(seed: int):
import numpy
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
numpy.random.seed(seed)
PIPE_CHUNKS = 2
iteration_count = 0
class EmbeddingLayer(nn.Embedding):
def __init__(self, ntoken, ninp, initrange):
super().__init__(ntoken, ninp)
self.ninp = ninp
self.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
return super().forward(src) * math.sqrt(self.ninp)
class PositionalEncodingLayer(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncodingLayer, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer("pe", pe)
def forward(self, x):
x = x + self.pe[: x.size(0), :]
return self.dropout(x)
class TransformerDecoderLayer(nn.TransformerEncoderLayer):
"""Though this class inherits from torch.nn.TransformerEncoderLayer,
it functions as a decoder in this model"""
def __init__(self, ninp, nhead, nhid, droupout):
super().__init__(ninp, nhead, nhid, droupout)
self.src_mask = None
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, float(0.0))
return mask
def forward(self, src):
global iteration_count
iteration_count += 1
# if iteration_count == 196:
# dump_cuda_tensors()
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
return super().forward(src, self.src_mask)
class LinearLayer(nn.Linear):
def __init__(self, ninp, ntoken, initrange):
super().__init__(ninp, ntoken)
self.bias.data.zero_()
self.weight.data.uniform_(-initrange, initrange)
class TransformerLMSequential(nn.Sequential):
"""A small language model based on the design of GPT-2 using nn.Sequential
for compatability with Pipe"""
def __init__(self, ntokens, ninp, nhead, nhid, dropout, initrange, ndecoder):
layers = [
EmbeddingLayer(ntokens, ninp, initrange),
PositionalEncodingLayer(ninp, dropout),
]
for _ in range(ndecoder):
layers.append(TransformerDecoderLayer(ninp, nhead, nhid, dropout))
layers.append(LinearLayer(ninp, ntokens, initrange))
super(TransformerLMSequential, self).__init__(*layers)
def get_data(device):
with warnings.catch_warnings(record=True) as fjldska:
TEXT = torchtext.data.Field(
tokenize=get_tokenizer("basic_english"), init_token="<sos>", eos_token="<eos>", lower=True
)
train_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)
TEXT.build_vocab(train_txt)
ntokens = len(TEXT.vocab.stoi)
batch_size = 20
eval_batch_size = 10
train_data = batchify(train_txt, batch_size, TEXT, device)
val_data = batchify(val_txt, eval_batch_size, TEXT, device)
test_data = batchify(test_txt, eval_batch_size, TEXT, device)
return ntokens, train_data, val_data, test_data
def batchify(data, bsz, TEXT, device):
data = TEXT.numericalize([data.examples[0].text])
nbatch = data.size(0) // bsz
data = data.narrow(0, 0, nbatch * bsz)
data = data.view(bsz, -1).t().contiguous()
return data.to(device)
def get_batch(source, i, bptt):
seq_len = min(bptt, len(source) - 1 - i)
data = source[i : i + seq_len]
target = source[i + 1 : i + 1 + seq_len].view(-1)
return data, target
def make_model(args, device, ntokens):
ninp = 2048 # embedding dimension
nhid = 2048 # the dimension of the feedforward network model in nn.TransformerEncoder
nhead = 32 # the number of heads in the multiheadattention models
dropout = 0
initrange = 0.1
ndecoder = args.num_decoder_layers
if args.lazy_construction:
layers = [
LazyModule(lambda: EmbeddingLayer(ntokens, ninp, initrange)),
LazyModule(lambda: PositionalEncodingLayer(ninp, dropout)),
]
for _ in range(ndecoder):
layers.append(LazyModule(lambda: TransformerDecoderLayer(ninp, nhead, nhid, dropout)))
layers.append(LazyModule(lambda: LinearLayer(ninp, ntokens, initrange)))
model = layers
else:
model = TransformerLMSequential(ntokens, ninp, nhead, nhid, dropout, initrange, ndecoder).to(device)
criterion = nn.CrossEntropyLoss()
lr = 0.01 # learning rate
def make_adam(model):
if args.ddp_zero:
return OSS(params=model.parameters(), optim=Adam, group=get_data_parallel_group(), lr=lr)
else:
return Adam(model.parameters(), lr=lr)
optimizer = make_adam
scaler = GradScaler()
return model, criterion, optimizer, scaler
def get_tensors_by_size_bucket():
from collections import defaultdict
import gc
size_buckets = defaultdict(int)
for obj in gc.get_objects():
if not isinstance(obj, torch.Tensor):
continue
if obj.device.type == "cuda":
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
return size_buckets
def dump_size_buckets(size_buckets, prefix=""):
from functools import reduce
import operator
total = 0
for key, value in size_buckets.items():
this = reduce(operator.mul, key) * value
total += this
print(prefix + f"{key} : {value}, {this}")
print(prefix + f"total = {total}")
last_size_buckets = None
once = True
def safe_rank():
try:
return torch.distributed.get_rank()
except AssertionError:
return 0
def check_size_buckets():
global last_size_buckets
global once
size_buckets = get_tensors_by_size_bucket()
if last_size_buckets is not None:
if size_buckets != last_size_buckets:
print(f"difference is oustanding tensors: {safe-rank()}")
dump_size_buckets(last_size_buckets, "old: ")
dump_size_buckets(size_buckets, "new: ")
if once:
print(f"dumping buckets for: {safe_rank()}")
dump_size_buckets(last_size_buckets, "old: ")
dump_size_buckets(size_buckets, "new: ")
once = False
else:
print(f"size buckets none on {safe_rank()}")
last_size_buckets = size_buckets
def dump_cuda_tensors():
print(f"dumping cuda tensors...")
from functools import reduce
import gc
import operator
for obj in gc.get_objects():
if not isinstance(obj, torch.Tensor):
continue
if obj.device.type == "cuda":
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
print(f"outstanding cuda tensors:")
total = 0
for key, value in size_buckets.items():
this = reduce(operator.mul, key) * value
total += this
print(f"{key} : {value}, {this}")
print(f"total size = {total}")
import pprint
pprint.pprint(torch.cuda.memory_stats())
def train(lm_dataloader, model, criterion, optimizer, vocab_size, args):
model.train()
from functools import reduce
import operator
num_params = reduce(operator.add, (reduce(operator.mul, x.size()) for x in model.parameters()))
if model.group:
total = torch.Tensor([num_params])
if torch.cuda.is_available():
total = total.cuda()
torch.distributed.all_reduce(total, group=model.group)
logging.info(
f"training model, #prams = {num_params}, group: {model.group.rank()}, grank:"
f" {torch.distributed.get_rank()}, sizes {model.group.size()}"
)
torch.distributed.barrier()
if model.group.rank() == 0:
logging.info(f"total #prams = {total.item()}")
else:
logging.info(f"training model, #prams = {num_params}")
vocab_size = 10000 # FIXME
total_loss = 0.0
start_time = time.time()
word_counter = 0
optimizer = optimizer(model)
def get_first_device(model):
if isinstance(model, DDP):
model = model.module
if not torch.cuda.is_available():
return torch.device("cpu")
if model.devices:
return model.devices[0]
else:
return torch.cuda.current_device()
def get_last_device(model):
if isinstance(model, DDP):
model = model.module
if not torch.cuda.is_available():
return torch.device("cpu")
if model.devices:
return model.devices[-1]
else:
return torch.cuda.current_device()
pipe_group = model.group
if args.ddp_zero:
model = DDP(
model,
device_ids=[torch.cuda.current_device()],
process_group=get_data_parallel_group(),
find_unused_parameters=False,
)
if pipe_group and pipe_group.rank() != 0 and pipe_group.rank() != (pipe_group.size() - 1):
thing = {"input": torch.zeros(args.batch_size)}
class FakeDataset:
def __getitem__(self, index):
return thing
def __len__(self):
return len(lm_dataloader)
lm_dataloader = FakeDataset()
for i, batch in enumerate(lm_dataloader):
bi = batch["input"]
if args.max_batch and i > args.max_batch:
break
optimizer.zero_grad()
try:
if (pipe_group is None or pipe_group.rank() == 0) and not args.ddp_zero:
tmp = batch["input"].to(get_first_device(model))
output = model(tmp)
else:
output = model(batch["input"])
except Exception as e:
raise RuntimeError(f"training failed on {torch.distributed.get_rank()}") from e
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
target = batch["target"].to(get_last_device(model))
output = output.to(target.device)
loss = criterion(output.view(-1, vocab_size), target.view(-1))
if args.ddp_zero:
ddp_group = get_data_parallel_group()
torch.distributed.all_reduce(loss, op=torch.distributed.ReduceOp.SUM, group=ddp_group)
loss /= ddp_group.size()
loss.backward()
del target
else:
if args.ddp_zero:
model.module.back_helper(output)
else:
model.back_helper(output)
del output
torch.nn.utils.clip_grad_value_(model.parameters(), 0.05)
optimizer.step()
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
total_loss += loss.item()
log_interval = 1
word_counter += batch["ntokens"]
if i % log_interval == 0 and i > 0:
cur_loss = total_loss / log_interval
elapsed = time.time() - start_time
print(
"| batch {:5d} | wps {:5.2f} | loss {:5.2f} | ppl {:8.2f}".format(
i, word_counter / elapsed, cur_loss, math.exp(cur_loss)
)
)
word_counter = 0
total_loss = 0
start_time = time.time()
# if i >= 10:
# break
# torch.cuda.empty_cache()
# check_size_buckets()
def evaluate(eval_model, data_source, criterion, bptt, ntokens):
eval_model.eval()
total_loss = 0.0
with torch.no_grad():
for i in range(0, data_source.size(0) - 1, bptt):
data, targets = get_batch(data_source, i, bptt)
output = eval_model(data)
output = output.to(targets.device)
output_flat = output.view(-1, ntokens)
total_loss += len(data) * criterion(output_flat, targets).item()
return total_loss / (len(data_source) - 1)
def get_number_of_words(data):
return data.size()[0] * data.size()[1]
def benchmark_language_model(train_data, val_data, test_data, model, criterion, optimizer, ntokens, args):
epoch = 1
bptt = 35
start_time = time.time()
print("-" * 110)
print("| start of epoch {:1d}".format(epoch))
print("-" * 110)
epoch_start_time = time.time()
train(train_data, model, criterion, optimizer, bptt, ntokens, args)
val_loss = 1 # evaluate(model, val_data, criterion, bptt, ntokens)
print("-" * 89)
print(
"| end of epoch {:1d} | time: {:5.2f}s | valid loss {:5.2f} ".format(
epoch, (time.time() - epoch_start_time), val_loss
)
)
print("-" * 110)
elapsed_time = time.time() - start_time
nwords = get_number_of_words(train_data) + get_number_of_words(val_data)
wps = nwords / elapsed_time
test_loss = 1 # evaluate(model, test_data, criterion, bptt, ntokens)
print("=" * 89)
print(
"| end of training | test loss {:5.2f} \n| time: {:5.2f}s | words: {:3d} | wps: {:5.2f}".format(
test_loss, elapsed_time, nwords, wps
)
)
print("=" * 110)
if can_benchmark and len(model.balance) == 4:
# Assert that words per second is within 3 standard deviations of the average
# of six golden runs
assert wps > 36954.4 - (3 * 116.825)
print("Peak allocated bytes on cuda:0: {:1d}".format(torch.cuda.memory_stats(0)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:1: {:1d}".format(torch.cuda.memory_stats(1)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:2: {:1d}".format(torch.cuda.memory_stats(2)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:3: {:1d}".format(torch.cuda.memory_stats(3)["allocated_bytes.all.peak"]))
# Assert that memory usage on each GPU is within 10% of golden run
# Right-hand-side is golden run bytes * 110%
assert torch.cuda.memory_stats(0)["allocated_bytes.all.peak"] < 4061909504 * 1.1
assert torch.cuda.memory_stats(1)["allocated_bytes.all.peak"] < 4050944 * 1.1
assert torch.cuda.memory_stats(2)["allocated_bytes.all.peak"] < 10427392 * 1.1
assert torch.cuda.memory_stats(3)["allocated_bytes.all.peak"] < 2031824896 * 1.1
print("No regression detected")
def generate_balance_weighted(num_devices, num_layers, fraction=0.5):
balance = []
layers_assigned = 0
average_count = num_layers / num_devices
last_layers = int(average_count * fraction)
balance = generate_balance(num_devices - 1, num_layers - last_layers)
balance.append(last_layers)
return balance
def generate_balance(num_devices, num_layers):
balance = []
layers_assigned = 0
for i in range(num_devices):
x = (num_layers - layers_assigned) / (num_devices - i)
if x.is_integer():
balance.append(int(x))
layers_assigned += x
else:
balance.append(math.ceil(x))
layers_assigned += math.ceil(x)
return balance
def make_model_and_data(args, device, new_data: bool = True):
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
if new_data:
vocab_size = 10000
model, criterion, optimizer, scaler = make_model(args, device, vocab_size)
lm_dataset = BenchmarkLMDataset()
lm_dataloader = DataLoader(
lm_dataset, batch_size=args.batch_size, shuffle=True, num_workers=0, collate_fn=collate_sentences_lm
)
return {
"model": model,
"criterion": criterion,
"optimizer": optimizer,
"data": lm_dataloader,
"vocab_size": vocab_size,
}
else:
data = get_data(device)
ntokens, train_data, val_data, test_data = data
model, criterion, optimizer, scaler = make_model(args, device, ntokens)
return {
"model": model,
"criterion": criterion,
"optimizer": optimizer,
"data": data,
}
def bench_single_process(args):
num_devices = torch.cuda.device_count() if torch.cuda.is_available() else 1
assert num_devices > 0
init_random_seed(0)
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
new_data = True
blob = make_model_and_data(args, None, new_data=new_data)
model = blob["model"]
balance = generate_balance(min(num_devices, 4), len(model))
p = pipe.Pipe(
model, balance, chunks=args.chunks, pipelined_backward=args.pipelined_backward, checkpoint=args.checkpoint
)
del model
del blob["model"]
if new_data:
train(blob["data"], p, blob["criterion"], blob["optimizer"], blob["vocab_size"], args)
else:
ntokens, train_data, val_data, test_data = blob["data"]
benchmark_language_model(train_data, val_data, test_data, p, criterion, optimizer, ntokens, args)
def run_mp_worker(args, available_workers):
new_data = True
blob = make_model_and_data(args, None, new_data=new_data)
model = blob["model"]
balance = generate_balance_weighted(get_pipeline_parallel_group().size(), len(model), 0.8)
p = pipe.Pipe(
model,
balance,
style=Pipe.AsyncSchedule,
chunks=args.chunks,
worker_map=get_worker_map(),
input_device=torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"),
pipelined_backward=args.pipelined_backward,
checkpoint=args.checkpoint,
# loss_fn=blob["criterion"],
)
if torch.cuda.is_available():
p = p.cuda()
if args.all_at_once and p.pipeline:
print(f"running all at once")
p.pipeline.all_at_once = True
if new_data:
train(blob["data"], p, blob["criterion"], blob["optimizer"], blob["vocab_size"], args)
else:
ntokens, train_data, val_data, test_data = blob["data"]
benchmark_language_model(train_data, val_data, test_data, p, criterion, optimizer, ntokens, args)
def run_worker(rank, world_size, args):
if args.world_size != 0:
world_size = args.world_size
dist_init(rank + args.rank_base, world_size, hostname=args.host)
initialize_model_parallel(1, world_size)
init_random_seed(0)
run_mp_worker(args, world_size)
rpc.shutdown()
torch.distributed.destroy_process_group()
def bench_multi_process(args, all_at_once=False):
if args.local_world_size != 0:
world_size = args.local_world_size
else:
world_size = min(torch.cuda.device_count(), 2)
mp.spawn(run_worker, args=(world_size, args), nprocs=world_size, join=True)
best_device_map = {
0: "mlx5_0:1",
1: "mlx5_0:1",
2: "mlx5_1:1",
3: "mlx5_1:1",
4: "mlx5_2:1",
5: "mlx5_2:1",
6: "mlx5_3:1",
7: "mlx5_3:1",
}
def bench_mpi(args):
guess_rank = int(os.environ["OMPI_COMM_WORLD_RANK"])
world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"])
local_rank = int(os.environ["OMPI_COMM_WORLD_LOCAL_RANK"])
os.environ["UCX_NET_DEVICES"] = best_device_map[local_rank]
os.environ["MASTER_ADDR"] = args.host
os.environ["MASTER_PORT"] = "10638"
if args.socket_name:
os.environ["GLOO_SOCKET_IFNAME"] = args.socket_name
os.environ["TP_SOCKET_IFNAME"] = args.socket_name
torch.distributed.init_process_group(backend="gloo", rank=guess_rank, world_size=world_size)
os.environ["MASTER_ADDR"] = args.host
os.environ["MASTER_PORT"] = "10639"
init_method = f"tcp://{os.environ['MASTER_ADDR']}:{os.environ['MASTER_PORT']}"
rank = torch.distributed.get_rank()
world_size = torch.distributed.get_world_size()
torch.cuda.set_device(local_rank % torch.cuda.device_count())
rpc.init_rpc(
f"Test{rank}",
rank=rank,
world_size=world_size,
backend=rpc.BackendType.PROCESS_GROUP,
rpc_backend_options=rpc.ProcessGroupRpcBackendOptions(rpc_timeout=20, init_method=init_method),
)
backends = {"model_parallel_backend": "nccl", "pipeline_backend": "mpi", "ddp_backend": "nccl"}
if args.ddp_zero:
initialize_model_parallel(1, 4, **backends)
else:
initialize_model_parallel(1, world_size, **backends)
init_random_seed(0)
run_mp_worker(args, world_size)
rpc.shutdown()
torch.distributed.destroy_process_group()
parser = argparse.ArgumentParser(description="benchmark")
parser.add_argument("--local-world-size", "-l", type=int, default=0, help="local world size")
parser.add_argument("--world-size", "-w", type=int, default=0, help="world size")
parser.add_argument("--rank-base", "-r", type=int, help="rank base", default=0)
parser.add_argument("--host", "-o", type=str, default="localhost", help="hostname")
parser.add_argument("--no-mpi", action="store_true", default=False, help="disable mpi")
parser.add_argument("--chunks", type=int, default=1, help="number of microbatches per batch")
parser.add_argument("--batch-size", type=int, default=8, help="size of a batch")
parser.add_argument("--all-at-once", action="store_true", default=False, help="do backward pass on whole batch at once")
parser.add_argument("--max-batch", type=int, default=4, help="Max number of batches")
parser.add_argument("--socket-name", type=str, default=None, help="socket ifname for gloo/tp")
parser.add_argument("--num-decoder-layers", type=int, default=10, help="Number of decoder layers in the model")
parser.add_argument("--ddp-zero", action="store_true", default=False, help="enable ddp")
parser.add_argument(
"--lazy-construction", action="store_true", default=False, help="Number of decoder layers in the model"
)
parser.add_argument(
"--checkpoint", default="never", choices=["always", "except_last", "never"], help="Checkpointing strategy for pipe"
)
parser.add_argument(
"--pipelined-backward", dest="pipelined_backward", action="store_true", help="Pipelined backward pass"
)
parser.add_argument(
"--no-pipelined-backward", dest="pipelined_backward", action="store_false", help="Pipelined backward pass"
)
parser.set_defaults(pipelined_backward=True)
if __name__ == "__main__":
args = parser.parse_args()
# bench_multi_process(args, all_at_once=True)
if args.no_mpi or "OMPI_COMM_WORLD_RANK" not in os.environ:
print(f"Running benchmark with args: {args}")
bench_single_process(args)
else:
if os.environ["OMPI_COMM_WORLD_RANK"] == "0":
print(f"Running benchmark with args: {args}")
bench_mpi(args)
| 34.685345 | 120 | 0.645499 |
import argparse
import logging
import math
import os
import time
import warnings
from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm
import torch
from torch.distributed import rpc
import torch.multiprocessing as mp
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader
import torchtext
from torchtext.data.utils import get_tokenizer
from fairscale.nn import Pipe
from fairscale.nn.model_parallel import initialize_model_parallel
from fairscale.nn.model_parallel.initialize import get_data_parallel_group, get_pipeline_parallel_group
from fairscale.nn.pipe import LazyModule, pipe
from fairscale.optim import GradScaler
from fairscale.optim.oss import OSS
from fairscale.utils.testing import dist_init, get_worker_map
try:
from fairscale.optim import Adam
can_benchmark = True
except ImportError:
from torch.optim import Adam
can_benchmark = False
def init_random_seed(seed: int):
import numpy
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
numpy.random.seed(seed)
PIPE_CHUNKS = 2
iteration_count = 0
class EmbeddingLayer(nn.Embedding):
def __init__(self, ntoken, ninp, initrange):
super().__init__(ntoken, ninp)
self.ninp = ninp
self.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
return super().forward(src) * math.sqrt(self.ninp)
class PositionalEncodingLayer(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncodingLayer, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer("pe", pe)
def forward(self, x):
x = x + self.pe[: x.size(0), :]
return self.dropout(x)
class TransformerDecoderLayer(nn.TransformerEncoderLayer):
def __init__(self, ninp, nhead, nhid, droupout):
super().__init__(ninp, nhead, nhid, droupout)
self.src_mask = None
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, float(0.0))
return mask
def forward(self, src):
global iteration_count
iteration_count += 1
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
return super().forward(src, self.src_mask)
class LinearLayer(nn.Linear):
def __init__(self, ninp, ntoken, initrange):
super().__init__(ninp, ntoken)
self.bias.data.zero_()
self.weight.data.uniform_(-initrange, initrange)
class TransformerLMSequential(nn.Sequential):
def __init__(self, ntokens, ninp, nhead, nhid, dropout, initrange, ndecoder):
layers = [
EmbeddingLayer(ntokens, ninp, initrange),
PositionalEncodingLayer(ninp, dropout),
]
for _ in range(ndecoder):
layers.append(TransformerDecoderLayer(ninp, nhead, nhid, dropout))
layers.append(LinearLayer(ninp, ntokens, initrange))
super(TransformerLMSequential, self).__init__(*layers)
def get_data(device):
with warnings.catch_warnings(record=True) as fjldska:
TEXT = torchtext.data.Field(
tokenize=get_tokenizer("basic_english"), init_token="<sos>", eos_token="<eos>", lower=True
)
train_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)
TEXT.build_vocab(train_txt)
ntokens = len(TEXT.vocab.stoi)
batch_size = 20
eval_batch_size = 10
train_data = batchify(train_txt, batch_size, TEXT, device)
val_data = batchify(val_txt, eval_batch_size, TEXT, device)
test_data = batchify(test_txt, eval_batch_size, TEXT, device)
return ntokens, train_data, val_data, test_data
def batchify(data, bsz, TEXT, device):
data = TEXT.numericalize([data.examples[0].text])
nbatch = data.size(0) // bsz
data = data.narrow(0, 0, nbatch * bsz)
data = data.view(bsz, -1).t().contiguous()
return data.to(device)
def get_batch(source, i, bptt):
seq_len = min(bptt, len(source) - 1 - i)
data = source[i : i + seq_len]
target = source[i + 1 : i + 1 + seq_len].view(-1)
return data, target
def make_model(args, device, ntokens):
ninp = 2048
nhid = 2048
nhead = 32
dropout = 0
initrange = 0.1
ndecoder = args.num_decoder_layers
if args.lazy_construction:
layers = [
LazyModule(lambda: EmbeddingLayer(ntokens, ninp, initrange)),
LazyModule(lambda: PositionalEncodingLayer(ninp, dropout)),
]
for _ in range(ndecoder):
layers.append(LazyModule(lambda: TransformerDecoderLayer(ninp, nhead, nhid, dropout)))
layers.append(LazyModule(lambda: LinearLayer(ninp, ntokens, initrange)))
model = layers
else:
model = TransformerLMSequential(ntokens, ninp, nhead, nhid, dropout, initrange, ndecoder).to(device)
criterion = nn.CrossEntropyLoss()
lr = 0.01
def make_adam(model):
if args.ddp_zero:
return OSS(params=model.parameters(), optim=Adam, group=get_data_parallel_group(), lr=lr)
else:
return Adam(model.parameters(), lr=lr)
optimizer = make_adam
scaler = GradScaler()
return model, criterion, optimizer, scaler
def get_tensors_by_size_bucket():
from collections import defaultdict
import gc
size_buckets = defaultdict(int)
for obj in gc.get_objects():
if not isinstance(obj, torch.Tensor):
continue
if obj.device.type == "cuda":
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
return size_buckets
def dump_size_buckets(size_buckets, prefix=""):
from functools import reduce
import operator
total = 0
for key, value in size_buckets.items():
this = reduce(operator.mul, key) * value
total += this
print(prefix + f"{key} : {value}, {this}")
print(prefix + f"total = {total}")
last_size_buckets = None
once = True
def safe_rank():
try:
return torch.distributed.get_rank()
except AssertionError:
return 0
def check_size_buckets():
global last_size_buckets
global once
size_buckets = get_tensors_by_size_bucket()
if last_size_buckets is not None:
if size_buckets != last_size_buckets:
print(f"difference is oustanding tensors: {safe-rank()}")
dump_size_buckets(last_size_buckets, "old: ")
dump_size_buckets(size_buckets, "new: ")
if once:
print(f"dumping buckets for: {safe_rank()}")
dump_size_buckets(last_size_buckets, "old: ")
dump_size_buckets(size_buckets, "new: ")
once = False
else:
print(f"size buckets none on {safe_rank()}")
last_size_buckets = size_buckets
def dump_cuda_tensors():
print(f"dumping cuda tensors...")
from functools import reduce
import gc
import operator
for obj in gc.get_objects():
if not isinstance(obj, torch.Tensor):
continue
if obj.device.type == "cuda":
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
print(f"outstanding cuda tensors:")
total = 0
for key, value in size_buckets.items():
this = reduce(operator.mul, key) * value
total += this
print(f"{key} : {value}, {this}")
print(f"total size = {total}")
import pprint
pprint.pprint(torch.cuda.memory_stats())
def train(lm_dataloader, model, criterion, optimizer, vocab_size, args):
model.train()
from functools import reduce
import operator
num_params = reduce(operator.add, (reduce(operator.mul, x.size()) for x in model.parameters()))
if model.group:
total = torch.Tensor([num_params])
if torch.cuda.is_available():
total = total.cuda()
torch.distributed.all_reduce(total, group=model.group)
logging.info(
f"training model, #prams = {num_params}, group: {model.group.rank()}, grank:"
f" {torch.distributed.get_rank()}, sizes {model.group.size()}"
)
torch.distributed.barrier()
if model.group.rank() == 0:
logging.info(f"total #prams = {total.item()}")
else:
logging.info(f"training model, #prams = {num_params}")
vocab_size = 10000
total_loss = 0.0
start_time = time.time()
word_counter = 0
optimizer = optimizer(model)
def get_first_device(model):
if isinstance(model, DDP):
model = model.module
if not torch.cuda.is_available():
return torch.device("cpu")
if model.devices:
return model.devices[0]
else:
return torch.cuda.current_device()
def get_last_device(model):
if isinstance(model, DDP):
model = model.module
if not torch.cuda.is_available():
return torch.device("cpu")
if model.devices:
return model.devices[-1]
else:
return torch.cuda.current_device()
pipe_group = model.group
if args.ddp_zero:
model = DDP(
model,
device_ids=[torch.cuda.current_device()],
process_group=get_data_parallel_group(),
find_unused_parameters=False,
)
if pipe_group and pipe_group.rank() != 0 and pipe_group.rank() != (pipe_group.size() - 1):
thing = {"input": torch.zeros(args.batch_size)}
class FakeDataset:
def __getitem__(self, index):
return thing
def __len__(self):
return len(lm_dataloader)
lm_dataloader = FakeDataset()
for i, batch in enumerate(lm_dataloader):
bi = batch["input"]
if args.max_batch and i > args.max_batch:
break
optimizer.zero_grad()
try:
if (pipe_group is None or pipe_group.rank() == 0) and not args.ddp_zero:
tmp = batch["input"].to(get_first_device(model))
output = model(tmp)
else:
output = model(batch["input"])
except Exception as e:
raise RuntimeError(f"training failed on {torch.distributed.get_rank()}") from e
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
target = batch["target"].to(get_last_device(model))
output = output.to(target.device)
loss = criterion(output.view(-1, vocab_size), target.view(-1))
if args.ddp_zero:
ddp_group = get_data_parallel_group()
torch.distributed.all_reduce(loss, op=torch.distributed.ReduceOp.SUM, group=ddp_group)
loss /= ddp_group.size()
loss.backward()
del target
else:
if args.ddp_zero:
model.module.back_helper(output)
else:
model.back_helper(output)
del output
torch.nn.utils.clip_grad_value_(model.parameters(), 0.05)
optimizer.step()
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
total_loss += loss.item()
log_interval = 1
word_counter += batch["ntokens"]
if i % log_interval == 0 and i > 0:
cur_loss = total_loss / log_interval
elapsed = time.time() - start_time
print(
"| batch {:5d} | wps {:5.2f} | loss {:5.2f} | ppl {:8.2f}".format(
i, word_counter / elapsed, cur_loss, math.exp(cur_loss)
)
)
word_counter = 0
total_loss = 0
start_time = time.time()
def evaluate(eval_model, data_source, criterion, bptt, ntokens):
eval_model.eval()
total_loss = 0.0
with torch.no_grad():
for i in range(0, data_source.size(0) - 1, bptt):
data, targets = get_batch(data_source, i, bptt)
output = eval_model(data)
output = output.to(targets.device)
output_flat = output.view(-1, ntokens)
total_loss += len(data) * criterion(output_flat, targets).item()
return total_loss / (len(data_source) - 1)
def get_number_of_words(data):
return data.size()[0] * data.size()[1]
def benchmark_language_model(train_data, val_data, test_data, model, criterion, optimizer, ntokens, args):
epoch = 1
bptt = 35
start_time = time.time()
print("-" * 110)
print("| start of epoch {:1d}".format(epoch))
print("-" * 110)
epoch_start_time = time.time()
train(train_data, model, criterion, optimizer, bptt, ntokens, args)
val_loss = 1
print("-" * 89)
print(
"| end of epoch {:1d} | time: {:5.2f}s | valid loss {:5.2f} ".format(
epoch, (time.time() - epoch_start_time), val_loss
)
)
print("-" * 110)
elapsed_time = time.time() - start_time
nwords = get_number_of_words(train_data) + get_number_of_words(val_data)
wps = nwords / elapsed_time
test_loss = 1
print("=" * 89)
print(
"| end of training | test loss {:5.2f} \n| time: {:5.2f}s | words: {:3d} | wps: {:5.2f}".format(
test_loss, elapsed_time, nwords, wps
)
)
print("=" * 110)
if can_benchmark and len(model.balance) == 4:
assert wps > 36954.4 - (3 * 116.825)
print("Peak allocated bytes on cuda:0: {:1d}".format(torch.cuda.memory_stats(0)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:1: {:1d}".format(torch.cuda.memory_stats(1)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:2: {:1d}".format(torch.cuda.memory_stats(2)["allocated_bytes.all.peak"]))
print("Peak allocated bytes on cuda:3: {:1d}".format(torch.cuda.memory_stats(3)["allocated_bytes.all.peak"]))
assert torch.cuda.memory_stats(0)["allocated_bytes.all.peak"] < 4061909504 * 1.1
assert torch.cuda.memory_stats(1)["allocated_bytes.all.peak"] < 4050944 * 1.1
assert torch.cuda.memory_stats(2)["allocated_bytes.all.peak"] < 10427392 * 1.1
assert torch.cuda.memory_stats(3)["allocated_bytes.all.peak"] < 2031824896 * 1.1
print("No regression detected")
def generate_balance_weighted(num_devices, num_layers, fraction=0.5):
balance = []
layers_assigned = 0
average_count = num_layers / num_devices
last_layers = int(average_count * fraction)
balance = generate_balance(num_devices - 1, num_layers - last_layers)
balance.append(last_layers)
return balance
def generate_balance(num_devices, num_layers):
balance = []
layers_assigned = 0
for i in range(num_devices):
x = (num_layers - layers_assigned) / (num_devices - i)
if x.is_integer():
balance.append(int(x))
layers_assigned += x
else:
balance.append(math.ceil(x))
layers_assigned += math.ceil(x)
return balance
def make_model_and_data(args, device, new_data: bool = True):
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
if new_data:
vocab_size = 10000
model, criterion, optimizer, scaler = make_model(args, device, vocab_size)
lm_dataset = BenchmarkLMDataset()
lm_dataloader = DataLoader(
lm_dataset, batch_size=args.batch_size, shuffle=True, num_workers=0, collate_fn=collate_sentences_lm
)
return {
"model": model,
"criterion": criterion,
"optimizer": optimizer,
"data": lm_dataloader,
"vocab_size": vocab_size,
}
else:
data = get_data(device)
ntokens, train_data, val_data, test_data = data
model, criterion, optimizer, scaler = make_model(args, device, ntokens)
return {
"model": model,
"criterion": criterion,
"optimizer": optimizer,
"data": data,
}
def bench_single_process(args):
num_devices = torch.cuda.device_count() if torch.cuda.is_available() else 1
assert num_devices > 0
init_random_seed(0)
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
new_data = True
blob = make_model_and_data(args, None, new_data=new_data)
model = blob["model"]
balance = generate_balance(min(num_devices, 4), len(model))
p = pipe.Pipe(
model, balance, chunks=args.chunks, pipelined_backward=args.pipelined_backward, checkpoint=args.checkpoint
)
del model
del blob["model"]
if new_data:
train(blob["data"], p, blob["criterion"], blob["optimizer"], blob["vocab_size"], args)
else:
ntokens, train_data, val_data, test_data = blob["data"]
benchmark_language_model(train_data, val_data, test_data, p, criterion, optimizer, ntokens, args)
def run_mp_worker(args, available_workers):
new_data = True
blob = make_model_and_data(args, None, new_data=new_data)
model = blob["model"]
balance = generate_balance_weighted(get_pipeline_parallel_group().size(), len(model), 0.8)
p = pipe.Pipe(
model,
balance,
style=Pipe.AsyncSchedule,
chunks=args.chunks,
worker_map=get_worker_map(),
input_device=torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"),
pipelined_backward=args.pipelined_backward,
checkpoint=args.checkpoint,
)
if torch.cuda.is_available():
p = p.cuda()
if args.all_at_once and p.pipeline:
print(f"running all at once")
p.pipeline.all_at_once = True
if new_data:
train(blob["data"], p, blob["criterion"], blob["optimizer"], blob["vocab_size"], args)
else:
ntokens, train_data, val_data, test_data = blob["data"]
benchmark_language_model(train_data, val_data, test_data, p, criterion, optimizer, ntokens, args)
def run_worker(rank, world_size, args):
if args.world_size != 0:
world_size = args.world_size
dist_init(rank + args.rank_base, world_size, hostname=args.host)
initialize_model_parallel(1, world_size)
init_random_seed(0)
run_mp_worker(args, world_size)
rpc.shutdown()
torch.distributed.destroy_process_group()
def bench_multi_process(args, all_at_once=False):
if args.local_world_size != 0:
world_size = args.local_world_size
else:
world_size = min(torch.cuda.device_count(), 2)
mp.spawn(run_worker, args=(world_size, args), nprocs=world_size, join=True)
best_device_map = {
0: "mlx5_0:1",
1: "mlx5_0:1",
2: "mlx5_1:1",
3: "mlx5_1:1",
4: "mlx5_2:1",
5: "mlx5_2:1",
6: "mlx5_3:1",
7: "mlx5_3:1",
}
def bench_mpi(args):
guess_rank = int(os.environ["OMPI_COMM_WORLD_RANK"])
world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"])
local_rank = int(os.environ["OMPI_COMM_WORLD_LOCAL_RANK"])
os.environ["UCX_NET_DEVICES"] = best_device_map[local_rank]
os.environ["MASTER_ADDR"] = args.host
os.environ["MASTER_PORT"] = "10638"
if args.socket_name:
os.environ["GLOO_SOCKET_IFNAME"] = args.socket_name
os.environ["TP_SOCKET_IFNAME"] = args.socket_name
torch.distributed.init_process_group(backend="gloo", rank=guess_rank, world_size=world_size)
os.environ["MASTER_ADDR"] = args.host
os.environ["MASTER_PORT"] = "10639"
init_method = f"tcp://{os.environ['MASTER_ADDR']}:{os.environ['MASTER_PORT']}"
rank = torch.distributed.get_rank()
world_size = torch.distributed.get_world_size()
torch.cuda.set_device(local_rank % torch.cuda.device_count())
rpc.init_rpc(
f"Test{rank}",
rank=rank,
world_size=world_size,
backend=rpc.BackendType.PROCESS_GROUP,
rpc_backend_options=rpc.ProcessGroupRpcBackendOptions(rpc_timeout=20, init_method=init_method),
)
backends = {"model_parallel_backend": "nccl", "pipeline_backend": "mpi", "ddp_backend": "nccl"}
if args.ddp_zero:
initialize_model_parallel(1, 4, **backends)
else:
initialize_model_parallel(1, world_size, **backends)
init_random_seed(0)
run_mp_worker(args, world_size)
rpc.shutdown()
torch.distributed.destroy_process_group()
parser = argparse.ArgumentParser(description="benchmark")
parser.add_argument("--local-world-size", "-l", type=int, default=0, help="local world size")
parser.add_argument("--world-size", "-w", type=int, default=0, help="world size")
parser.add_argument("--rank-base", "-r", type=int, help="rank base", default=0)
parser.add_argument("--host", "-o", type=str, default="localhost", help="hostname")
parser.add_argument("--no-mpi", action="store_true", default=False, help="disable mpi")
parser.add_argument("--chunks", type=int, default=1, help="number of microbatches per batch")
parser.add_argument("--batch-size", type=int, default=8, help="size of a batch")
parser.add_argument("--all-at-once", action="store_true", default=False, help="do backward pass on whole batch at once")
parser.add_argument("--max-batch", type=int, default=4, help="Max number of batches")
parser.add_argument("--socket-name", type=str, default=None, help="socket ifname for gloo/tp")
parser.add_argument("--num-decoder-layers", type=int, default=10, help="Number of decoder layers in the model")
parser.add_argument("--ddp-zero", action="store_true", default=False, help="enable ddp")
parser.add_argument(
"--lazy-construction", action="store_true", default=False, help="Number of decoder layers in the model"
)
parser.add_argument(
"--checkpoint", default="never", choices=["always", "except_last", "never"], help="Checkpointing strategy for pipe"
)
parser.add_argument(
"--pipelined-backward", dest="pipelined_backward", action="store_true", help="Pipelined backward pass"
)
parser.add_argument(
"--no-pipelined-backward", dest="pipelined_backward", action="store_false", help="Pipelined backward pass"
)
parser.set_defaults(pipelined_backward=True)
if __name__ == "__main__":
args = parser.parse_args()
if args.no_mpi or "OMPI_COMM_WORLD_RANK" not in os.environ:
print(f"Running benchmark with args: {args}")
bench_single_process(args)
else:
if os.environ["OMPI_COMM_WORLD_RANK"] == "0":
print(f"Running benchmark with args: {args}")
bench_mpi(args)
| true | true |
f71bba9186b8cf7fd34a3d76235e2705e8296209 | 28,432 | py | Python | ambari-server/src/test/python/stacks/2.0.6/HIVE/test_webhcat_server.py | cas-packone/ambari-chs | 68033fbd4b810b6642853f2ad9128cbbd4e0cb7b | [
"Apache-2.0"
] | 3 | 2019-06-20T11:49:36.000Z | 2020-12-11T10:44:29.000Z | ambari-server/src/test/python/stacks/2.0.6/HIVE/test_webhcat_server.py | cas-packone/ambari-chs | 68033fbd4b810b6642853f2ad9128cbbd4e0cb7b | [
"Apache-2.0"
] | null | null | null | ambari-server/src/test/python/stacks/2.0.6/HIVE/test_webhcat_server.py | cas-packone/ambari-chs | 68033fbd4b810b6642853f2ad9128cbbd4e0cb7b | [
"Apache-2.0"
] | 1 | 2019-03-20T08:36:17.000Z | 2019-03-20T08:36:17.000Z | #!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import json
from mock.mock import MagicMock, patch
from stacks.utils.RMFTestCase import *
from resource_management.core.exceptions import Fail
@patch("os.path.isfile", new = MagicMock(return_value=True))
@patch("glob.glob", new = MagicMock(return_value=["one", "two"]))
class TestWebHCatServer(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "HIVE/0.12.0.2.0/package"
STACK_VERSION = "2.0.6"
def test_configure_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_default()
self.assertNoMoreResources()
def test_start_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "start",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_default()
self.assertResourceCalled('Execute', 'cd /var/run/webhcat ; /usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh start',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client'},
not_if = "ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `cat /var/run/webhcat/webhcat.pid` >/dev/null 2>&1'",
user = 'hcat',
)
self.assertNoMoreResources()
def test_stop_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', '/usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh stop',
user = 'hcat',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client' }
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def test_configure_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_secured()
self.assertNoMoreResources()
@patch("webhcat_service.graceful_stop", new = MagicMock(side_effect=Fail))
def test_stop_graceful_stop_failed(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', "find /var/log/webhcat -maxdepth 1 -type f -name '*' -exec echo '==> {} <==' \\; -exec tail -n 40 {} \\;",
logoutput = True,
ignore_failures = True,
user = 'hcat',
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def test_start_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "start",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_secured()
self.assertResourceCalled('Execute', 'cd /var/run/webhcat ; /usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh start',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client'},
not_if = "ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `cat /var/run/webhcat/webhcat.pid` >/dev/null 2>&1'",
user = 'hcat',
)
self.assertNoMoreResources()
def test_stop_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', '/usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh stop',
user = 'hcat',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client' }
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
@patch("webhcat_service.graceful_stop", new = MagicMock(side_effect=Fail))
def test_stop_secured_graceful_stop_failed(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', "find /var/log/webhcat -maxdepth 1 -type f -name '*' -exec echo '==> {} <==' \\; -exec tail -n 40 {} \\;",
logoutput = True,
ignore_failures = True,
user = 'hcat',
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def assert_configure_default(self):
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a'
)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/etc/hive-webhcat/conf',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site']
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop',
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
cd_access = 'a',
create_parents = True
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644,
)
def assert_configure_secured(self):
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a'
)
self.assertResourceCalled('Execute', '/usr/bin/kinit -kt /etc/security/keytabs/hdfs.headless.keytab hdfs;',
path = ['/bin'],
user = 'hcat',
)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/etc/hive-webhcat/conf',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site']
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop',
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
cd_access = 'a',
create_parents = True
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644,
)
@patch("resource_management.libraries.functions.security_commons.build_expectations")
@patch("resource_management.libraries.functions.security_commons.get_params_from_filesystem")
@patch("resource_management.libraries.functions.security_commons.validate_security_config_properties")
@patch("resource_management.libraries.functions.security_commons.cached_kinit_executor")
@patch("resource_management.libraries.script.Script.put_structured_out")
def test_security_status(self, put_structured_out_mock, cached_kinit_executor_mock, validate_security_config_mock, get_params_mock, build_exp_mock):
# Test that function works when is called with correct parameters
security_params = {
'webhcat-site': {
"templeton.kerberos.secret": "secret",
"templeton.kerberos.keytab": 'path/to/keytab',
"templeton.kerberos.principal": "principal"
},
"hive-site": {
"hive.server2.authentication": "KERBEROS",
"hive.metastore.sasl.enabled": "true",
"hive.security.authorization.enabled": "true"
}
}
result_issues = []
webhcat_props_value_check = {"templeton.kerberos.secret": "secret"}
webhcat_props_empty_check = ["templeton.kerberos.keytab",
"templeton.kerberos.principal"]
webhcat_props_read_check = ["templeton.kerberos.keytab"]
hive_props_value_check = {"hive.server2.authentication": "KERBEROS",
"hive.metastore.sasl.enabled": "true",
"hive.security.authorization.enabled": "true"}
hive_props_empty_check = None
hive_props_read_check = None
get_params_mock.return_value = security_params
validate_security_config_mock.return_value = result_issues
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
build_exp_mock.assert_called_with('hive-site', hive_props_value_check, hive_props_empty_check, hive_props_read_check)
# get_params_mock.assert_called_with(status_params.hive_conf_dir, {'hive-site.xml': "XML"})
get_params_mock.assert_called_with('/etc/hive-webhcat/conf', {'webhcat-site.xml': "XML"})
put_structured_out_mock.assert_called_with({"securityState": "SECURED_KERBEROS"})
self.assertTrue(cached_kinit_executor_mock.call_count, 2)
cached_kinit_executor_mock.assert_called_with('/usr/bin/kinit',
self.config_dict['configurations']['hive-env']['webhcat_user'],
security_params['webhcat-site']['templeton.kerberos.keytab'],
security_params['webhcat-site']['templeton.kerberos.principal'],
self.config_dict['hostname'],
'/tmp')
# Testing that the exception throw by cached_executor is caught
cached_kinit_executor_mock.reset_mock()
cached_kinit_executor_mock.side_effect = Exception("Invalid command")
try:
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
except:
self.assertTrue(True)
# Testing with a security_params which doesn't contains startup
empty_security_params = {}
cached_kinit_executor_mock.reset_mock()
get_params_mock.reset_mock()
put_structured_out_mock.reset_mock()
get_params_mock.return_value = empty_security_params
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityIssuesFound": "Keytab file or principal are not set property."})
# Testing with not empty result_issues
result_issues_with_params = {
'hive-site': "Something bad happened"
}
validate_security_config_mock.reset_mock()
get_params_mock.reset_mock()
validate_security_config_mock.return_value = result_issues_with_params
get_params_mock.return_value = security_params
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityState": "UNSECURED"})
# Testing with security_enable = false
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityState": "UNSECURED"})
def test_pre_upgrade_restart(self):
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.2.1.0-3242'
json_content['commandParams']['version'] = version
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "pre_upgrade_restart",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES)
self.assertResourceCalled('Execute',
('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hive-webhcat', version), sudo=True,)
self.assertNoMoreResources()
@patch("resource_management.core.shell.call")
def test_pre_upgrade_restart_23(self, call_mock):
import sys
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.3.0.0-1234'
json_content['commandParams']['version'] = version
json_content['hostLevelParams']['stack_version'] = "2.3"
mocks_dict = {}
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "pre_upgrade_restart",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES,
call_mocks = [(0, None, ''), (0, None, '')],
mocks_dict = mocks_dict)
self.assertTrue("params" in sys.modules)
self.assertTrue(sys.modules["params"].webhcat_conf_dir is not None)
self.assertTrue("/usr/hdp/current/hive-webhcat/etc/webhcat" == sys.modules["params"].webhcat_conf_dir)
self.assertResourceCalledIgnoreEarlier('Execute',
('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hive-webhcat', version), sudo=True,)
self.assertNoMoreResources()
self.assertEquals(2, mocks_dict['call'].call_count)
self.assertEquals(2, mocks_dict['checked_call'].call_count)
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'set-conf-dir', '--package', 'hive-hcatalog', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['checked_call'].call_args_list[0][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'create-conf-dir', '--package', 'hive-hcatalog', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['call'].call_args_list[0][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'set-conf-dir', '--package', 'hadoop', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['checked_call'].call_args_list[1][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'create-conf-dir', '--package', 'hadoop', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['call'].call_args_list[1][0][0])
@patch("resource_management.core.shell.call")
def test_rolling_restart_configure(self, call_mock):
import sys
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.3.0.0-1234'
json_content['commandParams']['version'] = version
json_content['hostLevelParams']['stack_version'] = "2.3"
mocks_dict = {}
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES,
call_mocks = [(0, None), (0, None)],
mocks_dict = mocks_dict)
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755)
self.assertResourceCalled('Directory', '/usr/hdp/current/hive-webhcat/etc/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a',)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/usr/hdp/current/hive-webhcat/etc/webhcat',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site'])
self.assertResourceCalled('XmlConfig', 'hive-site.xml',
owner = 'hive',
group = 'hadoop',
conf_dir = '/usr/hdp/2.3.0.0-1234/hive/conf',
configuration_attributes = {u'final': {u'hive.optimize.bucketmapjoin.sortedmerge': u'true',
u'javax.jdo.option.ConnectionDriverName': u'true',
u'javax.jdo.option.ConnectionPassword': u'true'}},
configurations = self.getConfig()['configurations']['hive-site'],
)
self.assertResourceCalled('XmlConfig', 'yarn-site.xml',
owner = 'yarn',
group = 'hadoop',
conf_dir = '/usr/hdp/2.3.0.0-1234/hadoop/conf',
configuration_attributes = {u'final': {u'yarn.nodemanager.container-executor.class': u'true',
u'yarn.nodemanager.disk-health-checker.min-healthy-disks': u'true',
u'yarn.nodemanager.local-dirs': u'true'}},
configurations = self.getConfig()['configurations']['yarn-site'],
)
self.assertResourceCalled('File', '/usr/hdp/current/hive-webhcat/etc/webhcat/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop')
self.assertResourceCalled('Directory', '/usr/hdp/current/hive-webhcat/etc/webhcat',
cd_access = 'a',
create_parents = True)
self.assertResourceCalled('File', '/usr/hdp/current/hive-webhcat/etc/webhcat/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644)
self.assertNoMoreResources()
| 51.414105 | 420 | 0.583708 |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import json
from mock.mock import MagicMock, patch
from stacks.utils.RMFTestCase import *
from resource_management.core.exceptions import Fail
@patch("os.path.isfile", new = MagicMock(return_value=True))
@patch("glob.glob", new = MagicMock(return_value=["one", "two"]))
class TestWebHCatServer(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "HIVE/0.12.0.2.0/package"
STACK_VERSION = "2.0.6"
def test_configure_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_default()
self.assertNoMoreResources()
def test_start_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "start",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_default()
self.assertResourceCalled('Execute', 'cd /var/run/webhcat ; /usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh start',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client'},
not_if = "ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `cat /var/run/webhcat/webhcat.pid` >/dev/null 2>&1'",
user = 'hcat',
)
self.assertNoMoreResources()
def test_stop_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', '/usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh stop',
user = 'hcat',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client' }
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def test_configure_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_secured()
self.assertNoMoreResources()
@patch("webhcat_service.graceful_stop", new = MagicMock(side_effect=Fail))
def test_stop_graceful_stop_failed(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', "find /var/log/webhcat -maxdepth 1 -type f -name '*' -exec echo '==> {} <==' \\; -exec tail -n 40 {} \\;",
logoutput = True,
ignore_failures = True,
user = 'hcat',
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def test_start_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "start",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assert_configure_secured()
self.assertResourceCalled('Execute', 'cd /var/run/webhcat ; /usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh start',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client'},
not_if = "ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `cat /var/run/webhcat/webhcat.pid` >/dev/null 2>&1'",
user = 'hcat',
)
self.assertNoMoreResources()
def test_stop_secured(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', '/usr/hdp/current/hive-webhcat/sbin/webhcat_server.sh stop',
user = 'hcat',
environment = {'HADOOP_HOME': '/usr/hdp/current/hadoop-client' }
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
@patch("webhcat_service.graceful_stop", new = MagicMock(side_effect=Fail))
def test_stop_secured_graceful_stop_failed(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "stop",
config_file="secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
self.assertResourceCalled('Execute', "find /var/log/webhcat -maxdepth 1 -type f -name '*' -exec echo '==> {} <==' \\; -exec tail -n 40 {} \\;",
logoutput = True,
ignore_failures = True,
user = 'hcat',
)
self.assertResourceCalled('Execute', 'ambari-sudo.sh kill -9 `ambari-sudo.sh su hcat -l -s /bin/bash -c \'[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid\'`',
not_if = "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) || ( sleep 10 && ! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1) )",
ignore_failures = True
)
self.assertResourceCalled('Execute', "! (ls /var/run/webhcat/webhcat.pid >/dev/null 2>&1 && ps -p `ambari-sudo.sh su hcat -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]cat /var/run/webhcat/webhcat.pid'` >/dev/null 2>&1)",
tries=20,
try_sleep=3,
)
self.assertResourceCalled('File', '/var/run/webhcat/webhcat.pid',
action = ['delete'],
)
self.assertNoMoreResources()
def assert_configure_default(self):
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a'
)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/etc/hive-webhcat/conf',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site']
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop',
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
cd_access = 'a',
create_parents = True
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644,
)
def assert_configure_secured(self):
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755,
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a'
)
self.assertResourceCalled('Execute', '/usr/bin/kinit -kt /etc/security/keytabs/hdfs.headless.keytab hdfs;',
path = ['/bin'],
user = 'hcat',
)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/etc/hive-webhcat/conf',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site']
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop',
)
self.assertResourceCalled('Directory', '/etc/hive-webhcat/conf',
cd_access = 'a',
create_parents = True
)
self.assertResourceCalled('File', '/etc/hive-webhcat/conf/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644,
)
@patch("resource_management.libraries.functions.security_commons.build_expectations")
@patch("resource_management.libraries.functions.security_commons.get_params_from_filesystem")
@patch("resource_management.libraries.functions.security_commons.validate_security_config_properties")
@patch("resource_management.libraries.functions.security_commons.cached_kinit_executor")
@patch("resource_management.libraries.script.Script.put_structured_out")
def test_security_status(self, put_structured_out_mock, cached_kinit_executor_mock, validate_security_config_mock, get_params_mock, build_exp_mock):
security_params = {
'webhcat-site': {
"templeton.kerberos.secret": "secret",
"templeton.kerberos.keytab": 'path/to/keytab',
"templeton.kerberos.principal": "principal"
},
"hive-site": {
"hive.server2.authentication": "KERBEROS",
"hive.metastore.sasl.enabled": "true",
"hive.security.authorization.enabled": "true"
}
}
result_issues = []
webhcat_props_value_check = {"templeton.kerberos.secret": "secret"}
webhcat_props_empty_check = ["templeton.kerberos.keytab",
"templeton.kerberos.principal"]
webhcat_props_read_check = ["templeton.kerberos.keytab"]
hive_props_value_check = {"hive.server2.authentication": "KERBEROS",
"hive.metastore.sasl.enabled": "true",
"hive.security.authorization.enabled": "true"}
hive_props_empty_check = None
hive_props_read_check = None
get_params_mock.return_value = security_params
validate_security_config_mock.return_value = result_issues
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
build_exp_mock.assert_called_with('hive-site', hive_props_value_check, hive_props_empty_check, hive_props_read_check)
get_params_mock.assert_called_with('/etc/hive-webhcat/conf', {'webhcat-site.xml': "XML"})
put_structured_out_mock.assert_called_with({"securityState": "SECURED_KERBEROS"})
self.assertTrue(cached_kinit_executor_mock.call_count, 2)
cached_kinit_executor_mock.assert_called_with('/usr/bin/kinit',
self.config_dict['configurations']['hive-env']['webhcat_user'],
security_params['webhcat-site']['templeton.kerberos.keytab'],
security_params['webhcat-site']['templeton.kerberos.principal'],
self.config_dict['hostname'],
'/tmp')
cached_kinit_executor_mock.reset_mock()
cached_kinit_executor_mock.side_effect = Exception("Invalid command")
try:
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
except:
self.assertTrue(True)
empty_security_params = {}
cached_kinit_executor_mock.reset_mock()
get_params_mock.reset_mock()
put_structured_out_mock.reset_mock()
get_params_mock.return_value = empty_security_params
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityIssuesFound": "Keytab file or principal are not set property."})
# Testing with not empty result_issues
result_issues_with_params = {
'hive-site': "Something bad happened"
}
validate_security_config_mock.reset_mock()
get_params_mock.reset_mock()
validate_security_config_mock.return_value = result_issues_with_params
get_params_mock.return_value = security_params
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/secured.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityState": "UNSECURED"})
# Testing with security_enable = false
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "security_status",
config_file="../../2.1/configs/default.json",
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES
)
put_structured_out_mock.assert_called_with({"securityState": "UNSECURED"})
def test_pre_upgrade_restart(self):
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.2.1.0-3242'
json_content['commandParams']['version'] = version
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "pre_upgrade_restart",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES)
self.assertResourceCalled('Execute',
('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hive-webhcat', version), sudo=True,)
self.assertNoMoreResources()
@patch("resource_management.core.shell.call")
def test_pre_upgrade_restart_23(self, call_mock):
import sys
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.3.0.0-1234'
json_content['commandParams']['version'] = version
json_content['hostLevelParams']['stack_version'] = "2.3"
mocks_dict = {}
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "pre_upgrade_restart",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES,
call_mocks = [(0, None, ''), (0, None, '')],
mocks_dict = mocks_dict)
self.assertTrue("params" in sys.modules)
self.assertTrue(sys.modules["params"].webhcat_conf_dir is not None)
self.assertTrue("/usr/hdp/current/hive-webhcat/etc/webhcat" == sys.modules["params"].webhcat_conf_dir)
self.assertResourceCalledIgnoreEarlier('Execute',
('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hive-webhcat', version), sudo=True,)
self.assertNoMoreResources()
self.assertEquals(2, mocks_dict['call'].call_count)
self.assertEquals(2, mocks_dict['checked_call'].call_count)
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'set-conf-dir', '--package', 'hive-hcatalog', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['checked_call'].call_args_list[0][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'create-conf-dir', '--package', 'hive-hcatalog', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['call'].call_args_list[0][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'set-conf-dir', '--package', 'hadoop', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['checked_call'].call_args_list[1][0][0])
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'create-conf-dir', '--package', 'hadoop', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['call'].call_args_list[1][0][0])
@patch("resource_management.core.shell.call")
def test_rolling_restart_configure(self, call_mock):
import sys
config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json"
with open(config_file, "r") as f:
json_content = json.load(f)
version = '2.3.0.0-1234'
json_content['commandParams']['version'] = version
json_content['hostLevelParams']['stack_version'] = "2.3"
mocks_dict = {}
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/webhcat_server.py",
classname = "WebHCatServer",
command = "configure",
config_dict = json_content,
stack_version = self.STACK_VERSION,
target = RMFTestCase.TARGET_COMMON_SERVICES,
call_mocks = [(0, None), (0, None)],
mocks_dict = mocks_dict)
self.assertResourceCalled('Directory', '/var/run/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755)
self.assertResourceCalled('Directory', '/var/log/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
mode = 0755)
self.assertResourceCalled('Directory', '/usr/hdp/current/hive-webhcat/etc/webhcat',
owner = 'hcat',
group = 'hadoop',
create_parents = True,
cd_access = 'a',)
self.assertResourceCalled('XmlConfig', 'webhcat-site.xml',
owner = 'hcat',
group = 'hadoop',
conf_dir = '/usr/hdp/current/hive-webhcat/etc/webhcat',
configurations = self.getConfig()['configurations']['webhcat-site'],
configuration_attributes = self.getConfig()['configuration_attributes']['webhcat-site'])
self.assertResourceCalled('XmlConfig', 'hive-site.xml',
owner = 'hive',
group = 'hadoop',
conf_dir = '/usr/hdp/2.3.0.0-1234/hive/conf',
configuration_attributes = {u'final': {u'hive.optimize.bucketmapjoin.sortedmerge': u'true',
u'javax.jdo.option.ConnectionDriverName': u'true',
u'javax.jdo.option.ConnectionPassword': u'true'}},
configurations = self.getConfig()['configurations']['hive-site'],
)
self.assertResourceCalled('XmlConfig', 'yarn-site.xml',
owner = 'yarn',
group = 'hadoop',
conf_dir = '/usr/hdp/2.3.0.0-1234/hadoop/conf',
configuration_attributes = {u'final': {u'yarn.nodemanager.container-executor.class': u'true',
u'yarn.nodemanager.disk-health-checker.min-healthy-disks': u'true',
u'yarn.nodemanager.local-dirs': u'true'}},
configurations = self.getConfig()['configurations']['yarn-site'],
)
self.assertResourceCalled('File', '/usr/hdp/current/hive-webhcat/etc/webhcat/webhcat-env.sh',
content = InlineTemplate(self.getConfig()['configurations']['webhcat-env']['content']),
owner = 'hcat',
group = 'hadoop')
self.assertResourceCalled('Directory', '/usr/hdp/current/hive-webhcat/etc/webhcat',
cd_access = 'a',
create_parents = True)
self.assertResourceCalled('File', '/usr/hdp/current/hive-webhcat/etc/webhcat/webhcat-log4j.properties',
content = 'log4jproperties\nline2',
owner = 'hcat',
group = 'hadoop',
mode = 0644)
self.assertNoMoreResources()
| false | true |
f71bbb4c268959f437ff99244e9ab109af82e1a0 | 1,774 | py | Python | jina/drivers/querylang/slice.py | kaushikb11/jina | 2856809cc5acb16b5a3e76e5c14af0c7b2346d09 | [
"Apache-2.0"
] | null | null | null | jina/drivers/querylang/slice.py | kaushikb11/jina | 2856809cc5acb16b5a3e76e5c14af0c7b2346d09 | [
"Apache-2.0"
] | null | null | null | jina/drivers/querylang/slice.py | kaushikb11/jina | 2856809cc5acb16b5a3e76e5c14af0c7b2346d09 | [
"Apache-2.0"
] | null | null | null | __copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Iterable
from .. import QuerySetReader, BaseRecursiveDriver
if False:
from ...proto import jina_pb2
class SliceQL(QuerySetReader, BaseRecursiveDriver):
"""Restrict the size of the ``docs`` to ``k`` (given by the request)
Example::
- !ReduceAllDriver
with:
granularity_range: [0, 0]
adjacency_range: [0, 1]
- !SortQL
with:
reverse: true
field: 'score.value'
granularity_range: [0, 0]
adjacency_range: [0, 1]
- !SliceQL
with:
start: 0
end: 50
granularity_range: [0, 0]
adjacency_range: [0, 1]
`SliceQL` will ensure that only the first 50 documents are returned from this `Pod`
"""
def __init__(self, start: int, end: int = None, *args, **kwargs):
"""
:param start: Zero-based index at which to start extraction.
:param end: Zero-based index before which to end extraction.
slice extracts up to but not including end. For example, take(1,4) extracts
the second element through the fourth element (elements indexed 1, 2, and 3).
"""
super().__init__(*args, **kwargs)
self._start = int(start)
self._end = int(end)
self.is_apply = False
def _apply_all(self, docs: Iterable['jina_pb2.Document'], *args, **kwargs):
if self.start <= 0 and (self.end is None or self.end >= len(docs)):
pass
else:
del docs[int(self.end):]
del docs[:int(self.start)]
| 32.254545 | 93 | 0.559752 | __copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Iterable
from .. import QuerySetReader, BaseRecursiveDriver
if False:
from ...proto import jina_pb2
class SliceQL(QuerySetReader, BaseRecursiveDriver):
def __init__(self, start: int, end: int = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._start = int(start)
self._end = int(end)
self.is_apply = False
def _apply_all(self, docs: Iterable['jina_pb2.Document'], *args, **kwargs):
if self.start <= 0 and (self.end is None or self.end >= len(docs)):
pass
else:
del docs[int(self.end):]
del docs[:int(self.start)]
| true | true |
f71bbc336e9b9e428d917d26e1d743874331530d | 9,514 | py | Python | build/PureCloudPlatformClientV2/models/outbound_route_base_entity_listing.py | cjohnson-ctl/platform-client-sdk-python | 38ce53bb8012b66e8a43cc8bd6ff00cf6cc99100 | [
"MIT"
] | 1 | 2021-10-08T20:46:45.000Z | 2021-10-08T20:46:45.000Z | libs/PureCloudPlatformClientV2/models/outbound_route_base_entity_listing.py | rocketbot-cl/genesysCloud | dd9d9b5ebb90a82bab98c0d88b9585c22c91f333 | [
"MIT"
] | null | null | null | libs/PureCloudPlatformClientV2/models/outbound_route_base_entity_listing.py | rocketbot-cl/genesysCloud | dd9d9b5ebb90a82bab98c0d88b9585c22c91f333 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Copyright 2016 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class OutboundRouteBaseEntityListing(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
OutboundRouteBaseEntityListing - a model defined in Swagger
: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 = {
'entities': 'list[OutboundRouteBase]',
'page_size': 'int',
'page_number': 'int',
'total': 'int',
'first_uri': 'str',
'self_uri': 'str',
'next_uri': 'str',
'last_uri': 'str',
'previous_uri': 'str',
'page_count': 'int'
}
self.attribute_map = {
'entities': 'entities',
'page_size': 'pageSize',
'page_number': 'pageNumber',
'total': 'total',
'first_uri': 'firstUri',
'self_uri': 'selfUri',
'next_uri': 'nextUri',
'last_uri': 'lastUri',
'previous_uri': 'previousUri',
'page_count': 'pageCount'
}
self._entities = None
self._page_size = None
self._page_number = None
self._total = None
self._first_uri = None
self._self_uri = None
self._next_uri = None
self._last_uri = None
self._previous_uri = None
self._page_count = None
@property
def entities(self):
"""
Gets the entities of this OutboundRouteBaseEntityListing.
:return: The entities of this OutboundRouteBaseEntityListing.
:rtype: list[OutboundRouteBase]
"""
return self._entities
@entities.setter
def entities(self, entities):
"""
Sets the entities of this OutboundRouteBaseEntityListing.
:param entities: The entities of this OutboundRouteBaseEntityListing.
:type: list[OutboundRouteBase]
"""
self._entities = entities
@property
def page_size(self):
"""
Gets the page_size of this OutboundRouteBaseEntityListing.
:return: The page_size of this OutboundRouteBaseEntityListing.
:rtype: int
"""
return self._page_size
@page_size.setter
def page_size(self, page_size):
"""
Sets the page_size of this OutboundRouteBaseEntityListing.
:param page_size: The page_size of this OutboundRouteBaseEntityListing.
:type: int
"""
self._page_size = page_size
@property
def page_number(self):
"""
Gets the page_number of this OutboundRouteBaseEntityListing.
:return: The page_number of this OutboundRouteBaseEntityListing.
:rtype: int
"""
return self._page_number
@page_number.setter
def page_number(self, page_number):
"""
Sets the page_number of this OutboundRouteBaseEntityListing.
:param page_number: The page_number of this OutboundRouteBaseEntityListing.
:type: int
"""
self._page_number = page_number
@property
def total(self):
"""
Gets the total of this OutboundRouteBaseEntityListing.
:return: The total of this OutboundRouteBaseEntityListing.
:rtype: int
"""
return self._total
@total.setter
def total(self, total):
"""
Sets the total of this OutboundRouteBaseEntityListing.
:param total: The total of this OutboundRouteBaseEntityListing.
:type: int
"""
self._total = total
@property
def first_uri(self):
"""
Gets the first_uri of this OutboundRouteBaseEntityListing.
:return: The first_uri of this OutboundRouteBaseEntityListing.
:rtype: str
"""
return self._first_uri
@first_uri.setter
def first_uri(self, first_uri):
"""
Sets the first_uri of this OutboundRouteBaseEntityListing.
:param first_uri: The first_uri of this OutboundRouteBaseEntityListing.
:type: str
"""
self._first_uri = first_uri
@property
def self_uri(self):
"""
Gets the self_uri of this OutboundRouteBaseEntityListing.
:return: The self_uri of this OutboundRouteBaseEntityListing.
:rtype: str
"""
return self._self_uri
@self_uri.setter
def self_uri(self, self_uri):
"""
Sets the self_uri of this OutboundRouteBaseEntityListing.
:param self_uri: The self_uri of this OutboundRouteBaseEntityListing.
:type: str
"""
self._self_uri = self_uri
@property
def next_uri(self):
"""
Gets the next_uri of this OutboundRouteBaseEntityListing.
:return: The next_uri of this OutboundRouteBaseEntityListing.
:rtype: str
"""
return self._next_uri
@next_uri.setter
def next_uri(self, next_uri):
"""
Sets the next_uri of this OutboundRouteBaseEntityListing.
:param next_uri: The next_uri of this OutboundRouteBaseEntityListing.
:type: str
"""
self._next_uri = next_uri
@property
def last_uri(self):
"""
Gets the last_uri of this OutboundRouteBaseEntityListing.
:return: The last_uri of this OutboundRouteBaseEntityListing.
:rtype: str
"""
return self._last_uri
@last_uri.setter
def last_uri(self, last_uri):
"""
Sets the last_uri of this OutboundRouteBaseEntityListing.
:param last_uri: The last_uri of this OutboundRouteBaseEntityListing.
:type: str
"""
self._last_uri = last_uri
@property
def previous_uri(self):
"""
Gets the previous_uri of this OutboundRouteBaseEntityListing.
:return: The previous_uri of this OutboundRouteBaseEntityListing.
:rtype: str
"""
return self._previous_uri
@previous_uri.setter
def previous_uri(self, previous_uri):
"""
Sets the previous_uri of this OutboundRouteBaseEntityListing.
:param previous_uri: The previous_uri of this OutboundRouteBaseEntityListing.
:type: str
"""
self._previous_uri = previous_uri
@property
def page_count(self):
"""
Gets the page_count of this OutboundRouteBaseEntityListing.
:return: The page_count of this OutboundRouteBaseEntityListing.
:rtype: int
"""
return self._page_count
@page_count.setter
def page_count(self, page_count):
"""
Sets the page_count of this OutboundRouteBaseEntityListing.
:param page_count: The page_count of this OutboundRouteBaseEntityListing.
:type: int
"""
self._page_count = page_count
def to_dict(self):
"""
Returns the model properties as a 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()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
"""
Returns the model as raw JSON
"""
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 26.065753 | 85 | 0.590814 |
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class OutboundRouteBaseEntityListing(object):
def __init__(self):
self.swagger_types = {
'entities': 'list[OutboundRouteBase]',
'page_size': 'int',
'page_number': 'int',
'total': 'int',
'first_uri': 'str',
'self_uri': 'str',
'next_uri': 'str',
'last_uri': 'str',
'previous_uri': 'str',
'page_count': 'int'
}
self.attribute_map = {
'entities': 'entities',
'page_size': 'pageSize',
'page_number': 'pageNumber',
'total': 'total',
'first_uri': 'firstUri',
'self_uri': 'selfUri',
'next_uri': 'nextUri',
'last_uri': 'lastUri',
'previous_uri': 'previousUri',
'page_count': 'pageCount'
}
self._entities = None
self._page_size = None
self._page_number = None
self._total = None
self._first_uri = None
self._self_uri = None
self._next_uri = None
self._last_uri = None
self._previous_uri = None
self._page_count = None
@property
def entities(self):
return self._entities
@entities.setter
def entities(self, entities):
self._entities = entities
@property
def page_size(self):
return self._page_size
@page_size.setter
def page_size(self, page_size):
self._page_size = page_size
@property
def page_number(self):
return self._page_number
@page_number.setter
def page_number(self, page_number):
self._page_number = page_number
@property
def total(self):
return self._total
@total.setter
def total(self, total):
self._total = total
@property
def first_uri(self):
return self._first_uri
@first_uri.setter
def first_uri(self, first_uri):
self._first_uri = first_uri
@property
def self_uri(self):
return self._self_uri
@self_uri.setter
def self_uri(self, self_uri):
self._self_uri = self_uri
@property
def next_uri(self):
return self._next_uri
@next_uri.setter
def next_uri(self, next_uri):
self._next_uri = next_uri
@property
def last_uri(self):
return self._last_uri
@last_uri.setter
def last_uri(self, last_uri):
self._last_uri = last_uri
@property
def previous_uri(self):
return self._previous_uri
@previous_uri.setter
def previous_uri(self, previous_uri):
self._previous_uri = previous_uri
@property
def page_count(self):
return self._page_count
@page_count.setter
def page_count(self, page_count):
self._page_count = page_count
def to_dict(self):
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()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f71bbce66ac31c7a95044b6cdf45b22688c6321e | 10,895 | py | Python | salt/transport/road/raet/behaving.py | thinkbox/salt | 35c7c52a89eb98d7a1b6b2c59596d4fe19ab6db3 | [
"Apache-2.0"
] | 1 | 2019-06-27T13:03:07.000Z | 2019-06-27T13:03:07.000Z | salt/transport/road/raet/behaving.py | thinkbox/salt | 35c7c52a89eb98d7a1b6b2c59596d4fe19ab6db3 | [
"Apache-2.0"
] | null | null | null | salt/transport/road/raet/behaving.py | thinkbox/salt | 35c7c52a89eb98d7a1b6b2c59596d4fe19ab6db3 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
behaving.py raet ioflo behaviors
See raeting.py for data format and packet field details.
Layout in DataStore
raet.udp.stack.stack
value StackUdp
raet.udp.stack.txmsgs
value deque()
raet.udp.stack.rxmsgs
value deque()
raet.udp.stack.local
name host port sigkey prikey
raet.udp.stack.status
joined allowed idle
raet.udp.stack.destination
value deid
'''
# pylint: skip-file
# pylint: disable=W0611
# Import Python libs
from collections import deque
try:
import simplejson as json
except ImportError:
import json
# Import ioflo libs
from ioflo.base.odicting import odict
from ioflo.base.globaling import *
from ioflo.base import aiding
from ioflo.base import storing
from ioflo.base import deeding
from ioflo.base.consoling import getConsole
console = getConsole()
from . import raeting, packeting, estating, yarding, stacking
class StackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
StackUdpRaet initialize and run raet udp stack
'''
Ioinits = odict(
inode="raet.udp.stack.",
stack='stack',
txmsgs=odict(ipath='txmsgs', ival=deque()),
rxmsgs=odict(ipath='rxmsgs', ival=deque()),
local=odict(ipath='local', ival=odict( name='master',
eid=0,
host='0.0.0.0',
port=raeting.RAET_PORT,
sigkey=None,
prikey=None)),)
def postinitio(self):
'''
Setup stack instance
'''
sigkey = self.local.data.sigkey
prikey = self.local.data.prikey
ha = (self.local.data.host, self.local.data.port)
name = self.local.data.name
eid = self.local.data.eid
estate = estating.LocalEstate( eid=eid,
name=name,
ha=ha,
sigkey=sigkey,
prikey=prikey,)
txMsgs = self.txmsgs.value
rxMsgs = self.rxmsgs.value
self.stack.value = stacking.StackUdp(estate=estate,
store=self.store,
name=name,
txMsgs=txMsgs,
rxMsgs=rxMsgs, )
def action(self, **kwa):
'''
Service all the deques for the stack
'''
self.stack.value.serviceAll()
class CloserStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
CloserStackUdpRaet closes stack server socket connection
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack', )
def action(self, **kwa):
'''
Close udp socket
'''
if self.stack.value and isinstance(self.stack.value, stacking.StackUdp):
self.stack.value.serverUdp.close()
class JoinerStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Initiates join transaction with master
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',)
def action(self, **kwa):
'''
'''
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
stack.join()
class JoinedStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Updates status with .joined of zeroth remote estate (master)
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
'''
Update .status share
'''
stack = self.stack.value
joined = False
if stack and isinstance(stack, stacking.StackUdp):
if stack.estates:
joined = stack.estates.values()[0].joined
self.status.update(joined=joined)
class AllowerStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Initiates allow (CurveCP handshake) transaction with master
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack', )
def action(self, **kwa):
'''
Receive any udp packets on server socket and put in rxes
Send any packets in txes
'''
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
stack.allow()
return None
class AllowedStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Updates status with .allowed of zeroth remote estate (master)
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
'''
Update .status share
'''
stack = self.stack.value
allowed = False
if stack and isinstance(stack, stacking.StackUdp):
if stack.estates:
allowed = stack.estates.values()[0].allowed
self.status.update(allowed=allowed)
class IdledStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Updates idle status to true if there are no oustanding transactions in stack
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
'''
Update .status share
'''
stack = self.stack.value
idled = False
if stack and isinstance(stack, stacking.StackUdp):
if not stack.transactions:
idled = True
self.status.update(idled=idled)
class MessengerStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Puts message on txMsgs deque sent to deid
Message is composed fields that are parameters to action method
and is sent to remote estate deid
'''
Ioinits = odict(
inode=".raet.udp.stack.",
stack="stack",
destination="destination",)
def action(self, **kwa):
'''
Queue up message
'''
if kwa:
msg = odict(kwa)
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
deid = self.destination.value
stack.txMsg(msg=msg, deid=deid)
class PrinterStackUdpRaet(deeding.Deed): # pylint: disable=W0232
'''
Prints out messages on rxMsgs queue
'''
Ioinits = odict(
inode=".raet.udp.stack.",
rxmsgs=odict(ipath='rxmsgs', ival=deque()),)
def action(self, **kwa):
'''
Queue up message
'''
rxMsgs = self.rxmsgs.value
while rxMsgs:
msg = rxMsgs.popleft()
console.terse("\nReceived....\n{0}\n".format(msg))
class StackUxdRaet(deeding.Deed): # pylint: disable=W0232
'''
StackUxdRaet initialize and run raet uxd stack
'''
Ioinits = odict(
inode="raet.uxd.stack.",
stack='stack',
txmsgs=odict(ipath='txmsgs', ival=deque()),
rxmsgs=odict(ipath='rxmsgs', ival=deque()),
local=odict(ipath='local', ival=odict(name='minion',
yardname="",
lane="maple")),)
def postinitio(self):
'''
Setup stack instance
'''
name = self.local.data.name
yardname = self.local.data.yardname
lane = self.local.data.lane
txMsgs = self.txmsgs.value
rxMsgs = self.rxmsgs.value
self.stack.value = stacking.StackUxd(
store=self.store,
name=name,
yardname=yardname,
lanename=lane,
txMsgs=txMsgs,
rxMsgs=rxMsgs, )
def action(self, **kwa):
'''
Service all the deques for the stack
'''
self.stack.value.serviceAll()
class CloserStackUxdRaet(deeding.Deed): # pylint: disable=W0232
'''
CloserStackUxdRaet closes stack server socket connection
'''
Ioinits = odict(
inode=".raet.uxd.stack.",
stack='stack',)
def action(self, **kwa):
'''
Close uxd socket
'''
if self.stack.value and isinstance(self.stack.value, stacking.StackUxd):
self.stack.value.serverUxd.close()
class AddYardStackUxdRaet(deeding.Deed): # pylint: disable=W0232
'''
AddYardStackUxdRaet closes stack server socket connection
'''
Ioinits = odict(
inode=".raet.uxd.stack.",
stack='stack',
yard='yard',
local=odict(ipath='local', ival=odict(name=None, lane="maple")),)
def action(self, lane="lane", name=None, **kwa):
'''
Adds new yard to stack on lane with yid
'''
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUxd):
yard = yarding.Yard(stack=stack, prefix=lane, name=name)
stack.addRemoteYard(yard)
self.yard.value = yard
class TransmitStackUxdRaet(deeding.Deed): # pylint: disable=W0232
'''
Puts message on txMsgs deque sent to deid
Message is composed fields that are parameters to action method
and is sent to remote estate deid
'''
Ioinits = odict(
inode=".raet.uxd.stack.",
stack="stack",
dest="dest",)
def action(self, **kwa):
'''
Queue up message
'''
if kwa:
msg = odict(kwa)
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUxd):
name = self.dest.value #destination yard name
stack.transmit(msg=msg, name=name)
class PrinterStackUxdRaet(deeding.Deed): # pylint: disable=W0232
'''
Prints out messages on rxMsgs queue
'''
Ioinits = odict(
inode=".raet.uxd.stack.",
stack="stack",
rxmsgs=odict(ipath='rxmsgs', ival=deque()),)
def action(self, **kwa):
'''
Queue up message
'''
rxMsgs = self.rxmsgs.value
stack = self.stack.value
while rxMsgs:
msg = rxMsgs.popleft()
console.terse("\n{0} Received....\n{1}\n".format(stack.name, msg))
| 29.76776 | 80 | 0.536485 |
from collections import deque
try:
import simplejson as json
except ImportError:
import json
from ioflo.base.odicting import odict
from ioflo.base.globaling import *
from ioflo.base import aiding
from ioflo.base import storing
from ioflo.base import deeding
from ioflo.base.consoling import getConsole
console = getConsole()
from . import raeting, packeting, estating, yarding, stacking
class StackUdpRaet(deeding.Deed):
Ioinits = odict(
inode="raet.udp.stack.",
stack='stack',
txmsgs=odict(ipath='txmsgs', ival=deque()),
rxmsgs=odict(ipath='rxmsgs', ival=deque()),
local=odict(ipath='local', ival=odict( name='master',
eid=0,
host='0.0.0.0',
port=raeting.RAET_PORT,
sigkey=None,
prikey=None)),)
def postinitio(self):
sigkey = self.local.data.sigkey
prikey = self.local.data.prikey
ha = (self.local.data.host, self.local.data.port)
name = self.local.data.name
eid = self.local.data.eid
estate = estating.LocalEstate( eid=eid,
name=name,
ha=ha,
sigkey=sigkey,
prikey=prikey,)
txMsgs = self.txmsgs.value
rxMsgs = self.rxmsgs.value
self.stack.value = stacking.StackUdp(estate=estate,
store=self.store,
name=name,
txMsgs=txMsgs,
rxMsgs=rxMsgs, )
def action(self, **kwa):
self.stack.value.serviceAll()
class CloserStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack', )
def action(self, **kwa):
if self.stack.value and isinstance(self.stack.value, stacking.StackUdp):
self.stack.value.serverUdp.close()
class JoinerStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',)
def action(self, **kwa):
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
stack.join()
class JoinedStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
stack = self.stack.value
joined = False
if stack and isinstance(stack, stacking.StackUdp):
if stack.estates:
joined = stack.estates.values()[0].joined
self.status.update(joined=joined)
class AllowerStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack', )
def action(self, **kwa):
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
stack.allow()
return None
class AllowedStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
stack = self.stack.value
allowed = False
if stack and isinstance(stack, stacking.StackUdp):
if stack.estates:
allowed = stack.estates.values()[0].allowed
self.status.update(allowed=allowed)
class IdledStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack='stack',
status=odict(ipath='status', ival=odict(joined=False,
allowed=False,
idle=False, )))
def action(self, **kwa):
stack = self.stack.value
idled = False
if stack and isinstance(stack, stacking.StackUdp):
if not stack.transactions:
idled = True
self.status.update(idled=idled)
class MessengerStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
stack="stack",
destination="destination",)
def action(self, **kwa):
if kwa:
msg = odict(kwa)
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUdp):
deid = self.destination.value
stack.txMsg(msg=msg, deid=deid)
class PrinterStackUdpRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.udp.stack.",
rxmsgs=odict(ipath='rxmsgs', ival=deque()),)
def action(self, **kwa):
rxMsgs = self.rxmsgs.value
while rxMsgs:
msg = rxMsgs.popleft()
console.terse("\nReceived....\n{0}\n".format(msg))
class StackUxdRaet(deeding.Deed):
Ioinits = odict(
inode="raet.uxd.stack.",
stack='stack',
txmsgs=odict(ipath='txmsgs', ival=deque()),
rxmsgs=odict(ipath='rxmsgs', ival=deque()),
local=odict(ipath='local', ival=odict(name='minion',
yardname="",
lane="maple")),)
def postinitio(self):
name = self.local.data.name
yardname = self.local.data.yardname
lane = self.local.data.lane
txMsgs = self.txmsgs.value
rxMsgs = self.rxmsgs.value
self.stack.value = stacking.StackUxd(
store=self.store,
name=name,
yardname=yardname,
lanename=lane,
txMsgs=txMsgs,
rxMsgs=rxMsgs, )
def action(self, **kwa):
self.stack.value.serviceAll()
class CloserStackUxdRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.uxd.stack.",
stack='stack',)
def action(self, **kwa):
if self.stack.value and isinstance(self.stack.value, stacking.StackUxd):
self.stack.value.serverUxd.close()
class AddYardStackUxdRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.uxd.stack.",
stack='stack',
yard='yard',
local=odict(ipath='local', ival=odict(name=None, lane="maple")),)
def action(self, lane="lane", name=None, **kwa):
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUxd):
yard = yarding.Yard(stack=stack, prefix=lane, name=name)
stack.addRemoteYard(yard)
self.yard.value = yard
class TransmitStackUxdRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.uxd.stack.",
stack="stack",
dest="dest",)
def action(self, **kwa):
if kwa:
msg = odict(kwa)
stack = self.stack.value
if stack and isinstance(stack, stacking.StackUxd):
name = self.dest.value
stack.transmit(msg=msg, name=name)
class PrinterStackUxdRaet(deeding.Deed):
Ioinits = odict(
inode=".raet.uxd.stack.",
stack="stack",
rxmsgs=odict(ipath='rxmsgs', ival=deque()),)
def action(self, **kwa):
rxMsgs = self.rxmsgs.value
stack = self.stack.value
while rxMsgs:
msg = rxMsgs.popleft()
console.terse("\n{0} Received....\n{1}\n".format(stack.name, msg))
| true | true |
f71bbd57b2470bbde34e554ff23f62fc28873ebf | 2,314 | py | Python | loss_functions/loss_oracle.py | konstmish/opt_methods | ae73d9bd89ae5c463e70328d73cbd190175df98c | [
"MIT"
] | 13 | 2020-07-19T12:02:43.000Z | 2022-03-02T14:34:03.000Z | loss_functions/loss_oracle.py | konstmish/opt_methods | ae73d9bd89ae5c463e70328d73cbd190175df98c | [
"MIT"
] | 1 | 2020-12-25T02:05:00.000Z | 2021-01-01T11:24:51.000Z | loss_functions/loss_oracle.py | konstmish/opt_methods | ae73d9bd89ae5c463e70328d73cbd190175df98c | [
"MIT"
] | 2 | 2020-07-17T08:45:48.000Z | 2021-12-10T03:24:57.000Z | import copy
import numpy as np
import warnings
from .regularizer import Regularizer
class Oracle():
"""
Base class for all objectives. Can provide objective values,
gradients and its Hessians as functions that take parameters as input.
Takes as input the values of l1 and l2 regularization.
"""
def __init__(self, l1=0, l2=0, l2_in_prox=False, regularizer=None, seed=42):
if l1 < 0.0:
raise ValueError("Invalid value for l1 regularization: {}".format(l1))
if l2 < 0.0:
raise ValueError("Invalid value for l2 regularization: {}".format(l2))
if l2 == 0. and l2_in_prox:
warnings.warn("The value of l2 is set to 0, so l2_in_prox is changed to False.")
l2_in_prox = False
self.l1 = l1
self.l2 = 0 if l2_in_prox else l2
self.l2_in_prox = l2_in_prox
self.x_opt = None
self.f_opt = np.inf
self.regularizer = regularizer
self.seed = seed
if (l1 > 0 or l2_in_prox) and regularizer is None:
l2_prox = l2 if l2_in_prox else 0
self.regularizer = Regularizer(l1=l1, l2=l2_prox)
self.rng = np.random.default_rng(seed)
self._smoothness = None
self._max_smoothness = None
self._ave_smoothness = None
self._importance_probs = None
self._individ_smoothness = None
def value(self, x):
value = self._value(x)
if self.regularizer is not None:
value += self.regularizer(x)
if value < self.f_opt:
self.x_opt = copy.deepcopy(x)
self.f_opt = value
return value
def gradient(self, x):
pass
def hessian(self, x):
pass
def hess_vec_prod(self, x, v, grad_dif=False, eps=None):
pass
@property
def smoothness(self):
pass
@property
def max_smoothness(self):
pass
@property
def average_smoothness(self):
pass
def batch_smoothness(self, batch_size):
pass
@staticmethod
def norm(x):
pass
@staticmethod
def inner_prod(x, y):
pass
@staticmethod
def outer_prod(x, y):
pass
@staticmethod
def is_equal(x, y):
pass
| 26.295455 | 92 | 0.583838 | import copy
import numpy as np
import warnings
from .regularizer import Regularizer
class Oracle():
def __init__(self, l1=0, l2=0, l2_in_prox=False, regularizer=None, seed=42):
if l1 < 0.0:
raise ValueError("Invalid value for l1 regularization: {}".format(l1))
if l2 < 0.0:
raise ValueError("Invalid value for l2 regularization: {}".format(l2))
if l2 == 0. and l2_in_prox:
warnings.warn("The value of l2 is set to 0, so l2_in_prox is changed to False.")
l2_in_prox = False
self.l1 = l1
self.l2 = 0 if l2_in_prox else l2
self.l2_in_prox = l2_in_prox
self.x_opt = None
self.f_opt = np.inf
self.regularizer = regularizer
self.seed = seed
if (l1 > 0 or l2_in_prox) and regularizer is None:
l2_prox = l2 if l2_in_prox else 0
self.regularizer = Regularizer(l1=l1, l2=l2_prox)
self.rng = np.random.default_rng(seed)
self._smoothness = None
self._max_smoothness = None
self._ave_smoothness = None
self._importance_probs = None
self._individ_smoothness = None
def value(self, x):
value = self._value(x)
if self.regularizer is not None:
value += self.regularizer(x)
if value < self.f_opt:
self.x_opt = copy.deepcopy(x)
self.f_opt = value
return value
def gradient(self, x):
pass
def hessian(self, x):
pass
def hess_vec_prod(self, x, v, grad_dif=False, eps=None):
pass
@property
def smoothness(self):
pass
@property
def max_smoothness(self):
pass
@property
def average_smoothness(self):
pass
def batch_smoothness(self, batch_size):
pass
@staticmethod
def norm(x):
pass
@staticmethod
def inner_prod(x, y):
pass
@staticmethod
def outer_prod(x, y):
pass
@staticmethod
def is_equal(x, y):
pass
| true | true |
f71bbe3d8e47628a35517152c6c8c4ac6e8bf38e | 1,192 | py | Python | setup.py | avictor0826/bigsuds | a4cfd622ab38a3b8fd65cccdcccc117691a7c091 | [
"MIT"
] | 33 | 2015-08-23T21:32:34.000Z | 2019-07-03T16:14:26.000Z | setup.py | avictor0826/bigsuds | a4cfd622ab38a3b8fd65cccdcccc117691a7c091 | [
"MIT"
] | 9 | 2015-09-28T18:22:16.000Z | 2022-03-26T00:22:51.000Z | setup.py | avictor0826/bigsuds | a4cfd622ab38a3b8fd65cccdcccc117691a7c091 | [
"MIT"
] | 22 | 2015-09-25T22:47:28.000Z | 2022-03-28T12:54:59.000Z | from setuptools import setup
import re
def extract_version(filename):
contents = open(filename).read()
match = re.search('^__version__\s+=\s+[\'"](.*)[\'"]\s*$', contents, re.MULTILINE)
if match is not None:
return match.group(1)
setup(
name="bigsuds",
version=extract_version('bigsuds.py'),
description='Library for F5 Networks iControl API',
license='https://devcentral.f5.com/resources/devcentral-eula',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='f5 icontrol',
author='F5 Networks, Inc.',
author_email='devcentral@f5.com',
url='http://devcentral.f5.com',
install_requires=['suds-jurko>=0.6'],
py_modules=['bigsuds'],
test_suite='nose.collector',
tests_require=['nose', 'mock', 'mox'],
)
| 33.111111 | 86 | 0.618289 | from setuptools import setup
import re
def extract_version(filename):
contents = open(filename).read()
match = re.search('^__version__\s+=\s+[\'"](.*)[\'"]\s*$', contents, re.MULTILINE)
if match is not None:
return match.group(1)
setup(
name="bigsuds",
version=extract_version('bigsuds.py'),
description='Library for F5 Networks iControl API',
license='https://devcentral.f5.com/resources/devcentral-eula',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='f5 icontrol',
author='F5 Networks, Inc.',
author_email='devcentral@f5.com',
url='http://devcentral.f5.com',
install_requires=['suds-jurko>=0.6'],
py_modules=['bigsuds'],
test_suite='nose.collector',
tests_require=['nose', 'mock', 'mox'],
)
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.