text
stringlengths 6
947k
| repo_name
stringlengths 5
100
| path
stringlengths 4
231
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
947k
| score
float64 0
0.34
|
---|---|---|---|---|---|---|
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Revision $Id$
from __future__ import print_function
from __future__ import with_statement
import os
import itertools
import socket
import sys
import time
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
import rospkg.environment
import rosgraph
import rosgraph.rosenv
import rosgraph.network
import rosnode
import rosservice
from roswtf.context import WtfException
from roswtf.environment import paths, is_executable
from roswtf.model import WtfWarning, WtfError
from roswtf.rules import warning_rule, error_rule
def _businfo(ctx, node, bus_info):
# [[connectionId1, destinationId1, direction1, transport1, ...]... ]
edges = []
for info in bus_info:
#connection_id = info[0]
dest_id = info[1]
if dest_id.startswith('http://'):
if dest_id in ctx.uri_node_map:
dest_id = ctx.uri_node_map[dest_id]
else:
dest_id = 'unknown (%s)'%dest_id
direction = info[2]
#transport = info[3]
topic = info[4]
if len(info) > 5:
connected = info[5]
else:
connected = True #backwards compatibility
if connected:
if direction == 'i':
edges.append((topic, dest_id, node))
elif direction == 'o':
edges.append((topic, node, dest_id))
elif direction == 'b':
print("cannot handle bidirectional edges", file=sys.stderr)
else:
raise Exception()
return edges
def unexpected_edges(ctx):
if not ctx.system_state or not ctx.nodes:
return
unexpected = set(ctx.actual_edges) - set(ctx.expected_edges)
return ["%s->%s (%s)"%(p, s, t) for (t, p, s) in unexpected]
def missing_edges(ctx):
if not ctx.system_state or not ctx.nodes:
return
missing = set(ctx.expected_edges) - set(ctx.actual_edges)
return ["%s->%s (%s)"%(p, s, t) for (t, p, s) in missing]
def ping_check(ctx):
if not ctx.system_state or not ctx.nodes:
return
_, unpinged = rosnode.rosnode_ping_all()
return unpinged
def simtime_check(ctx):
if ctx.use_sim_time:
master = rosgraph.Master('/roswtf')
try:
pubtopics = master.getPublishedTopics('/')
except rosgraph.MasterException:
ctx.errors.append(WtfError("Cannot talk to ROS master"))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
for topic, _ in pubtopics:
if topic in ['/time', '/clock']:
return
return True
## contact each service and make sure it returns a header
def probe_all_services(ctx):
master = rosgraph.Master('/roswtf')
errors = []
for service_name in ctx.services:
try:
service_uri = master.lookupService(service_name)
except:
ctx.errors.append(WtfError("cannot contact ROS Master at %s"%rosgraph.rosenv.get_master_uri()))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
try:
headers = rosservice.get_service_headers(service_name, service_uri)
if not headers:
errors.append("service [%s] did not return service headers"%service_name)
except rosgraph.network.ROSHandshakeException as e:
errors.append("service [%s] appears to be malfunctioning"%service_name)
except Exception as e:
errors.append("service [%s] appears to be malfunctioning: %s"%(service_name, e))
return errors
def unconnected_subscriptions(ctx):
ret = ''
whitelist = ['/reset_time']
if ctx.use_sim_time:
for sub, l in ctx.unconnected_subscriptions.items():
l = [t for t in l if t not in whitelist]
if l:
ret += ' * %s:\n'%sub
ret += ''.join([" * %s\n"%t for t in l])
else:
for sub, l in ctx.unconnected_subscriptions.items():
l = [t for t in l if t not in ['/time', '/clock']]
if l:
ret += ' * %s:\n'%sub
ret += ''.join([" * %s\n"%t for t in l])
return ret
graph_warnings = [
(unconnected_subscriptions, "The following node subscriptions are unconnected:\n"),
(unexpected_edges, "The following nodes are unexpectedly connected:"),
]
graph_errors = [
(simtime_check, "/use_simtime is set but no publisher of /clock is present"),
(ping_check, "Could not contact the following nodes:"),
(missing_edges, "The following nodes should be connected but aren't:"),
(probe_all_services, "Errors connecting to the following services:"),
]
def topic_timestamp_drift(ctx, t):
#TODO: get msg_class, if msg_class has header, receive a message
# and compare its time to ros time
if 0:
rospy.Subscriber(t, msg_class)
#TODO: these are mainly future enhancements. It's unclear to me whether or not this will be
#useful as most of the generic rules are capable of targetting these problems as well.
#The only rule that in particular seems useful is the timestamp drift. It may be too
#expensive otherwise to run, though it would be interesting to attempt to receive a
#message from every single topic.
#TODO: parameter audit?
service_errors = [
]
service_warnings = [
]
topic_errors = [
(topic_timestamp_drift, "Timestamp drift:")
]
topic_warnings = [
]
node_errors = [
]
node_warnings = [
]
## cache sim_time calculation sot that multiple rules can use
def _compute_sim_time(ctx):
param_server = rosgraph.Master('/roswtf')
ctx.use_sim_time = False
try:
val = simtime = param_server.getParam('/use_sim_time')
if val:
ctx.use_sim_time = True
except:
pass
def _compute_system_state(ctx):
socket.setdefaulttimeout(3.0)
master = rosgraph.Master('/roswtf')
# store system state
try:
val = master.getSystemState()
except rosgraph.MasterException:
return
ctx.system_state = val
pubs, subs, srvs = val
# compute list of topics and services
topics = []
for t, _ in itertools.chain(pubs, subs):
topics.append(t)
services = []
service_providers = []
for s, l in srvs:
services.append(s)
service_providers.extend(l)
ctx.topics = topics
ctx.services = services
ctx.service_providers = service_providers
# compute list of nodes
nodes = []
for s in val:
for t, l in s:
nodes.extend(l)
ctx.nodes = list(set(nodes)) #uniq
# - compute reverse mapping of URI->nodename
count = 0
start = time.time()
for n in ctx.nodes:
count += 1
try:
val = master.lookupNode(n)
except socket.error:
ctx.errors.append(WtfError("cannot contact ROS Master at %s"%rosgraph.rosenv.get_master_uri()))
raise WtfException("roswtf lost connection to the ROS Master at %s"%rosgraph.rosenv.get_master_uri())
ctx.uri_node_map[val] = n
end = time.time()
# - time thresholds currently very arbitrary
if count:
if ((end - start) / count) > 1.:
ctx.warnings.append(WtfError("Communication with master is very slow (>1s average)"))
elif (end - start) / count > .5:
ctx.warnings.append(WtfWarning("Communication with master is very slow (>0.5s average)"))
import threading
class NodeInfoThread(threading.Thread):
def __init__(self, n, ctx, master, actual_edges, lock):
threading.Thread.__init__(self)
self.master = master
self.actual_edges = actual_edges
self.lock = lock
self.n = n
self.done = False
self.ctx = ctx
def run(self):
ctx = self.ctx
master = self.master
actual_edges = self.actual_edges
lock = self.lock
n = self.n
try:
socket.setdefaulttimeout(3.0)
with lock: #Apparently get_api_uri is not thread safe...
node_api = rosnode.get_api_uri(master, n)
if not node_api:
with lock:
ctx.errors.append(WtfError("Master does not have lookup information for node [%s]"%n))
return
node = ServerProxy(node_api)
start = time.time()
socket.setdefaulttimeout(3.0)
code, msg, bus_info = node.getBusInfo('/roswtf')
end = time.time()
with lock:
if (end-start) > 1.:
ctx.warnings.append(WtfWarning("Communication with node [%s] is very slow"%n))
if code != 1:
ctx.warnings.append(WtfWarning("Node [%s] would not return bus info"%n))
elif not bus_info:
if not n in ctx.service_providers:
ctx.warnings.append(WtfWarning("Node [%s] is not connected to anything"%n))
else:
edges = _businfo(ctx, n, bus_info)
actual_edges.extend(edges)
except socket.error:
pass #ignore as we have rules to catch this
except Exception as e:
ctx.errors.append(WtfError("Communication with [%s] raised an error: %s"%(n, str(e))))
finally:
self.done = True
## retrieve graph state from master and related nodes once so we don't overload
## the network
def _compute_connectivity(ctx):
socket.setdefaulttimeout(3.0)
master = rosgraph.Master('/roswtf')
# Compute list of expected edges and unconnected subscriptions
pubs, subs, _ = ctx.system_state
expected_edges = [] # [(topic, publisher, subscriber),]
unconnected_subscriptions = {} # { subscriber : [topics] }
# - build up a dictionary of publishers keyed by topic
pub_dict = {}
for t, pub_list in pubs:
pub_dict[t] = pub_list
# - iterate through subscribers and add edge to each publisher of topic
for t, sub_list in subs:
for sub in sub_list:
if t in pub_dict:
expected_edges.extend([(t, pub, sub) for pub in pub_dict[t]])
elif sub in unconnected_subscriptions:
unconnected_subscriptions[sub].append(t)
else:
unconnected_subscriptions[sub] = [t]
# compute actual edges
actual_edges = []
lock = threading.Lock()
threads = []
for n in ctx.nodes:
t =NodeInfoThread(n, ctx, master, actual_edges, lock)
threads.append(t)
t.start()
# spend up to a minute waiting for threads to complete. each
# thread has a 3-second timeout, but this will spike load
timeout_t = time.time() + 60.0
while time.time() < timeout_t and [t for t in threads if not t.done]:
time.sleep(0.5)
ctx.expected_edges = expected_edges
ctx.actual_edges = actual_edges
ctx.unconnected_subscriptions = unconnected_subscriptions
def _compute_online_context(ctx):
# have to compute sim time first
_compute_sim_time(ctx)
_compute_system_state(ctx)
_compute_connectivity(ctx)
def wtf_check_graph(ctx, names=None):
master_uri = ctx.ros_master_uri
#TODO: master rules
# - check for stale master state
# TODO: get the type for each topic from each publisher and see if they match up
master = rosgraph.Master('/roswtf')
try:
master.getPid()
except rospkg.MasterException:
warning_rule((True, "Cannot communicate with master, ignoring online checks"), True, ctx)
return
# fill in ctx info so we only have to compute once
print("analyzing graph...")
_compute_online_context(ctx)
print("... done analyzing graph")
if names:
check_topics = [t for t in names if t in ctx.topics]
check_services = [t for t in names if t in ctx.services]
check_nodes = [t for t in names if t in ctx.nodes]
unknown = [t for t in names if t not in check_topics + check_services + check_nodes]
if unknown:
raise WtfException("The following names were not found in the list of nodes, topics, or services:\n%s"%(''.join([" * %s\n"%t for t in unknown])))
for t in check_topics:
for r in topic_warnings:
warning_rule(r, r[0](ctx, t), ctx)
for r in topic_errors:
error_rule(r, r[0](ctx, t), ctx)
for s in check_services:
for r in service_warnings:
warning_rule(r, r[0](ctx, s), ctx)
for r in service_errors:
error_rule(r, r[0](ctx, s), ctx)
for n in check_nodes:
for r in node_warnings:
warning_rule(r, r[0](ctx, n), ctx)
for r in node_errors:
error_rule(r, r[0](ctx, n), ctx)
print("running graph rules...")
for r in graph_warnings:
warning_rule(r, r[0](ctx), ctx)
for r in graph_errors:
error_rule(r, r[0](ctx), ctx)
print("... done running graph rules")
|
MangoMangoDevelopment/neptune
|
lib/ros_comm-1.12.0/utilities/roswtf/src/roswtf/graph.py
|
Python
|
bsd-3-clause
| 14,968 | 0.008485 |
import opendbpy as odb
import helper
import odbUnitTest
class TestWireCodec(odbUnitTest.TestCase):
#This Function is called before each of the test cases defined below
def setUp(self):
self.db, self.tech, self.m1, self.m2, self.m3, self.v12, self.v23 = helper.createMultiLayerDB()
self.chip = odb.dbChip_create(self.db)
self.block = odb.dbBlock_create(self.chip, "chip")
self.net = odb.dbNet_create(self.block, "net")
self.wire = odb.dbWire_create(self.net)
self.pathsEnums = ["PATH", "JUNCTION", "SHORT", "VWIRE", "POINT", "POINT_EXT", "VIA", "TECH_VIA", "RECT", "ITERM", "BTERM", "RULE", "END_DECODE"]
#this function is called after each of the test cases
def tearDown(self):
self.db.destroy(self.db)
def test_decoder(self):
encoder = odb.dbWireEncoder()
encoder.begin(self.wire)
encoder.newPath(self.m1, "ROUTED")
encoder.addPoint(2000, 2000)
j1 = encoder.addPoint(10000, 2000)
encoder.addPoint(18000, 2000)
encoder.newPath(j1)
encoder.addTechVia(self.v12)
j2 = encoder.addPoint(10000, 10000)
encoder.addPoint(10000, 18000)
encoder.newPath(j2)
j3 = encoder.addTechVia(self.v12)
encoder.addPoint(23000, 10000, 4000)
encoder.newPath(j3)
encoder.addPoint(3000, 10000)
encoder.addTechVia(self.v12)
encoder.addTechVia(self.v23)
encoder.addPoint(3000, 10000, 4000)
encoder.addPoint(3000, 18000, 6000)
encoder.end()
decoder = odb.dbWireDecoder()
decoder.begin(self.wire)
# Encoding started with a path
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.PATH
# Check first point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [2000, 2000]
# Check second point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 2000]
# Check third point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [18000, 2000]
# Check first junction id
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.JUNCTION
jid = decoder.getJunctionValue()
assert jid == j1
# Check junction point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 2000]
# Check tech via
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.TECH_VIA
tchVia = decoder.getTechVia()
assert tchVia.getName() == self.v12.getName()
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 10000]
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 18000]
# Check second junction id
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.JUNCTION
jid = decoder.getJunctionValue()
assert jid == j2
# Check junction point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 10000]
# Check tech via
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.TECH_VIA
tchVia = decoder.getTechVia()
assert tchVia.getName() == self.v12.getName()
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT_EXT
point = decoder.getPoint_ext()
assert point == [23000, 10000, 4000]
# Check third junction id
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.JUNCTION
jid = decoder.getJunctionValue()
assert jid == j3
# Check junction point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [10000, 10000]
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT
point = decoder.getPoint()
assert point == [3000, 10000]
# Check tech via
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.TECH_VIA
tchVia = decoder.getTechVia()
assert tchVia.getName() == self.v12.getName()
# Check tech via
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.TECH_VIA
tchVia = decoder.getTechVia()
assert tchVia.getName() == self.v23.getName()
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT_EXT
point = decoder.getPoint_ext()
assert point == [3000, 10000, 4000]
# Check next point
nextOp = decoder.next()
assert nextOp == odb.dbWireDecoder.POINT_EXT
point = decoder.getPoint_ext()
assert point == [3000, 18000, 6000]
if __name__=='__main__':
odbUnitTest.mainParallel(TestWireCodec)
|
The-OpenROAD-Project/OpenROAD
|
src/odb/test/unitTestsPython/TestWireCodec.py
|
Python
|
bsd-3-clause
| 5,470 | 0.005484 |
import os
import sys
import argparse
import ConfigParser
import testcase_service
from bantorra.util import define
from bantorra.util.log import LOG as L
class TestCase_Base(testcase_service.TestCaseUnit):
config = {}
"""
TestCase_Base.
- Parse Command Line Argument.
- Create Service's Instance.
- Read Config File and get value.
"""
def __init__(self, *args, **kwargs):
super(TestCase_Base, self).__init__(*args, **kwargs)
self.parse()
self.get_config()
self.service_check()
self.get_service()
@classmethod
def set(cls, name, value):
cls.config[name] = value
@classmethod
def get(cls, name):
return cls.config[name]
def parse(self):
"""
Parse Command Line Arguments.
"""
return None
@classmethod
def get_service(cls):
"""
Get Service.
in the wifi branch, Used service is there.
"""
cls.core = cls.service["core"].get()
cls.picture = cls.service["picture"].get()
@classmethod
def get_config(cls, conf=""):
"""
Get Config File.
:arg string conf: config file path.
"""
cls.config = {}
if conf == "":
conf = os.path.join(define.APP_SCRIPT, "config.ini")
try:
config = ConfigParser.ConfigParser()
config.read(conf)
for section in config.sections():
for option in config.options(section):
cls.config["%s.%s" % (section, option)] = config.get(section, option)
except Exception as e:
L.warning('error: could not read config file: %s' % e)
|
TE-ToshiakiTanaka/bantorra.old
|
script/testcase_base.py
|
Python
|
mit
| 1,751 | 0.001142 |
self.description = "incoming package replaces symlink with directory (order 1)"
lp = pmpkg("pkg1")
lp.files = ["usr/lib/foo",
"lib -> usr/lib"]
self.addpkg2db("local", lp)
p1 = pmpkg("pkg1", "1.0-2")
p1.files = ["usr/lib/foo"]
self.addpkg2db("sync", p1)
p2 = pmpkg("pkg2")
p2.files = ["lib/bar"]
self.addpkg2db("sync", p2)
self.args = "-S pkg1 pkg2"
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_VERSION=pkg1|1.0-2")
self.addrule("PKG_EXIST=pkg2")
self.addrule("FILE_TYPE=lib|dir")
|
kylon/pacman-fakeroot
|
test/pacman/tests/sync701.py
|
Python
|
gpl-2.0
| 504 | 0 |
# Learn Python -- level 2 logic
# Copyright (C) 2013 Cornell FB Hackathon Team.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
player1._position = [5, 6]
_world.grid[player1._position[1]][player1._position[0]] = player1
player2._position = [14, 6]
_world.grid[player2._position[1]][player2._position[0]] = player2
items = [Item("bread", [0, 2]),
Item("mushroom", [11, 9]),
Item("scepter", [5, 4]),
Item("banana", [17, 3]),
Item("bread", [10, 1]),
Item("sword", [8, 9])]
def at_end():
if (player1.inventory.count() != 3 or
player2.inventory.count() != 3):
raise Exception("Failure")
|
pniedzielski/fb-hackathon-2013-11-21
|
src/py/level3.py
|
Python
|
agpl-3.0
| 1,260 | 0.001587 |
from __future__ import absolute_import
__all__ = ('get_auth_header',)
def get_auth_header(client, api_key=None, secret_key=None):
header = [
('sentry_client', client),
('sentry_version', '5'),
]
if api_key:
header.append(('sentry_key', api_key))
if secret_key:
header.append(('sentry_secret', secret_key))
return 'Sentry %s' % ', '.join('%s=%s' % (k, v) for k, v in header)
|
jokey2k/sentry
|
src/sentry/testutils/helpers/auth_header.py
|
Python
|
bsd-3-clause
| 431 | 0 |
"""Code representing a query."""
import six
from ichnaea.api.locate.constants import (
DataAccuracy,
MIN_WIFIS_IN_QUERY,
)
from ichnaea.api.locate.schema import (
CellAreaLookup,
CellLookup,
FallbackLookup,
WifiLookup,
)
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
if six.PY2: # pragma: no cover
from ipaddr import IPAddress as ip_address # NOQA
else: # pragma: no cover
from ipaddress import ip_address
METRIC_MAPPING = {
0: 'none',
1: 'one',
2: 'many',
}
class Query(object):
_country = None
_fallback = None
_geoip = None
_ip = None
def __init__(self, fallback=None, ip=None, cell=None, wifi=None,
api_key=None, api_type=None, session=None,
http_session=None, geoip_db=None, stats_client=None):
"""
A class representing a concrete query.
:param fallback: A dictionary of fallback options.
:type fallback: dict
:param ip: An IP address, e.g. 127.0.0.1.
:type ip: str
:param cell: A list of cell query dicts.
:type cell: list
:param wifi: A list of wifi query dicts.
:type wifi: list
:param api_key: An ApiKey instance for the current query.
:type api_key: :class:`ichnaea.models.api.ApiKey`
:param api_type: The type of query API, for example `locate`.
:type api_type: str
:param session: An open database session.
:param http_session: An open HTTP/S session.
:param geoip_db: A geoip database.
:type geoip_db: :class:`~ichnaea.geoip.GeoIPWrapper`
:param stats_client: A stats client.
:type stats_client: :class:`~ichnaea.log.StatsClient`
"""
self.geoip_db = geoip_db
self.http_session = http_session
self.session = session
self.stats_client = stats_client
self.fallback = fallback
self.ip = ip
self.cell = cell
self.wifi = wifi
self.api_key = api_key
if api_type not in (None, 'country', 'locate'):
raise ValueError('Invalid api_type.')
self.api_type = api_type
@property
def fallback(self):
"""
A validated
:class:`~ichnaea.api.locate.schema.FallbackLookup` instance.
"""
return self._fallback
@fallback.setter
def fallback(self, values):
if not values:
values = {}
valid = FallbackLookup.create(**values)
if valid is None: # pragma: no cover
valid = FallbackLookup.create()
self._fallback = valid
@property
def country(self):
"""
The two letter country code of origin for this query.
Can return None, if no country could be determined.
"""
return self._country
@property
def geoip(self):
"""
A GeoIP database entry for the originating IP address.
Can return None if no database match could be found.
"""
return self._geoip
@property
def ip(self):
"""The validated IP address."""
return self._ip
@ip.setter
def ip(self, value):
if not value:
value = None
try:
valid = str(ip_address(value))
except ValueError:
valid = None
self._ip = valid
if valid:
country = None
geoip = None
if self.geoip_db:
geoip = self.geoip_db.geoip_lookup(valid)
if geoip:
country = geoip.get('country_code')
if country:
country = country.upper()
self._geoip = geoip
self._country = country
@property
def cell(self):
"""
The validated list of
:class:`~ichnaea.api.locate.schema.CellLookup` instances.
If the same cell network is supplied multiple times, this chooses only
the best entry for each unique network.
"""
return self._cell
@property
def cell_area(self):
"""
The validated list of
:class:`~ichnaea.api.locate.schema.CellAreaLookup` instances.
If the same cell area is supplied multiple times, this chooses only
the best entry for each unique area.
"""
if self.fallback.lacf:
return self._cell_area
return []
@cell.setter
def cell(self, values):
if not values:
values = []
values = list(values)
self._cell_unvalidated = values
filtered_areas = OrderedDict()
filtered_cells = OrderedDict()
for value in values:
valid_area = CellAreaLookup.create(**value)
if valid_area:
existing = filtered_areas.get(valid_area.hashkey())
if existing is not None and existing.better(valid_area):
pass
else:
filtered_areas[valid_area.hashkey()] = valid_area
valid_cell = CellLookup.create(**value)
if valid_cell:
existing = filtered_cells.get(valid_cell.hashkey())
if existing is not None and existing.better(valid_cell):
pass
else:
filtered_cells[valid_cell.hashkey()] = valid_cell
self._cell_area = list(filtered_areas.values())
self._cell = list(filtered_cells.values())
@property
def wifi(self):
"""
The validated list of
:class:`~ichnaea.api.locate.schema.WifiLookup` instances.
If the same Wifi network is supplied multiple times, this chooses only
the best entry for each unique network.
If fewer than :data:`~ichnaea.api.locate.constants.MIN_WIFIS_IN_QUERY`
unique valid Wifi networks are found, returns an empty list.
"""
return self._wifi
@wifi.setter
def wifi(self, values):
if not values:
values = []
values = list(values)
self._wifi_unvalidated = values
filtered = OrderedDict()
for value in values:
valid_wifi = WifiLookup.create(**value)
if valid_wifi:
existing = filtered.get(valid_wifi.mac)
if existing is not None and existing.better(valid_wifi):
pass
else:
filtered[valid_wifi.mac] = valid_wifi
if len(filtered) < MIN_WIFIS_IN_QUERY:
filtered = {}
self._wifi = list(filtered.values())
@property
def expected_accuracy(self):
accuracies = [DataAccuracy.none]
if self.wifi:
if self.api_type == 'country':
accuracies.append(DataAccuracy.none)
else:
accuracies.append(DataAccuracy.high)
if self.cell:
if self.api_type == 'country':
accuracies.append(DataAccuracy.low)
else:
accuracies.append(DataAccuracy.medium)
if ((self.cell_area and self.fallback.lacf) or
(self.ip and self.fallback.ipf)):
accuracies.append(DataAccuracy.low)
# return the best possible (smallest) accuracy
return min(accuracies)
def result_status(self, result):
"""
Returns either hit or miss, depending on whether the result
matched the expected query accuracy.
"""
if result.data_accuracy <= self.expected_accuracy:
# equal or better / smaller accuracy
return 'hit'
return 'miss'
def internal_query(self):
"""Returns a dictionary of this query in our internal format."""
result = {}
if self.cell:
result['cell'] = []
for cell in self.cell:
cell_data = {}
for field in cell._fields:
cell_data[field] = getattr(cell, field)
result['cell'].append(cell_data)
if self.wifi:
result['wifi'] = []
for wifi in self.wifi:
wifi_data = {}
for field in wifi._fields:
wifi_data[field] = getattr(wifi, field)
result['wifi'].append(wifi_data)
if self.fallback:
fallback_data = {}
for field in self.fallback._fields:
fallback_data[field] = getattr(self.fallback, field)
result['fallbacks'] = fallback_data
return result
def collect_metrics(self):
"""Should detailed metrics be collected for this query?"""
allowed = bool(self.api_key and self.api_key.log and self.api_type)
# don't report stats if there is no data at all in the query
possible_result = bool(self.expected_accuracy != DataAccuracy.none)
return (allowed and possible_result)
def _emit_country_stat(self, metric, extra_tags):
country = self.country
if not country:
country = 'none'
metric = '%s.%s' % (self.api_type, metric)
tags = [
'key:%s' % self.api_key.name,
'country:%s' % country,
]
self.stats_client.incr(metric, tags=tags + extra_tags)
def emit_query_stats(self):
"""Emit stats about the data contained in this query."""
if not self.collect_metrics():
return
cells = len(self.cell)
wifis = len(self._wifi_unvalidated)
tags = []
if not self.ip:
tags.append('geoip:false')
for name, length in (('cell', cells), ('wifi', wifis)):
num = METRIC_MAPPING[min(length, 2)]
tags.append('{name}:{num}'.format(name=name, num=num))
self._emit_country_stat('query', tags)
def emit_result_stats(self, result):
"""Emit stats about how well the result satisfied the query."""
if not self.collect_metrics():
return
status = self.result_status(result)
tags = [
'accuracy:%s' % self.expected_accuracy.name,
'status:%s' % status,
]
if status == 'hit' and result.source:
tags.append('source:%s' % result.source.name)
self._emit_country_stat('result', tags)
def emit_source_stats(self, source, result):
"""Emit stats about how well the source satisfied the query."""
if not self.collect_metrics():
return
status = self.result_status(result)
tags = [
'source:%s' % source.name,
'accuracy:%s' % self.expected_accuracy.name,
'status:%s' % status,
]
self._emit_country_stat('source', tags)
|
therewillbecode/ichnaea
|
ichnaea/api/locate/query.py
|
Python
|
apache-2.0
| 10,806 | 0 |
"""Defines serializers used by the Team API."""
from copy import deepcopy
from django.contrib.auth.models import User
from django.db.models import Count
from django.conf import settings
from django_countries import countries
from rest_framework import serializers
from openedx.core.lib.api.serializers import CollapsedReferenceSerializer
from openedx.core.lib.api.fields import ExpandableField
from openedx.core.djangoapps.user_api.accounts.serializers import UserReadOnlySerializer
from lms.djangoapps.teams.models import CourseTeam, CourseTeamMembership
class CountryField(serializers.Field):
"""
Field to serialize a country code.
"""
COUNTRY_CODES = dict(countries).keys()
def to_representation(self, obj):
"""
Represent the country as a 2-character unicode identifier.
"""
return unicode(obj)
def to_internal_value(self, data):
"""
Check that the code is a valid country code.
We leave the data in its original format so that the Django model's
CountryField can convert it to the internal representation used
by the django-countries library.
"""
if data and data not in self.COUNTRY_CODES:
raise serializers.ValidationError(
u"{code} is not a valid country code".format(code=data)
)
return data
class UserMembershipSerializer(serializers.ModelSerializer):
"""Serializes CourseTeamMemberships with only user and date_joined
Used for listing team members.
"""
profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION)
profile_configuration['shareable_fields'].append('url')
profile_configuration['public_fields'].append('url')
user = ExpandableField(
collapsed_serializer=CollapsedReferenceSerializer(
model_class=User,
id_source='username',
view_name='accounts_api',
read_only=True,
),
expanded_serializer=UserReadOnlySerializer(configuration=profile_configuration),
)
class Meta(object):
model = CourseTeamMembership
fields = ("user", "date_joined", "last_activity_at")
read_only_fields = ("date_joined", "last_activity_at")
class CourseTeamSerializer(serializers.ModelSerializer):
"""Serializes a CourseTeam with membership information."""
id = serializers.CharField(source='team_id', read_only=True) # pylint: disable=invalid-name
membership = UserMembershipSerializer(many=True, read_only=True)
country = CountryField()
class Meta(object):
model = CourseTeam
fields = (
"id",
"discussion_topic_id",
"name",
"course_id",
"topic_id",
"date_created",
"description",
"country",
"language",
"last_activity_at",
"membership",
)
read_only_fields = ("course_id", "date_created", "discussion_topic_id", "last_activity_at")
class CourseTeamCreationSerializer(serializers.ModelSerializer):
"""Deserializes a CourseTeam for creation."""
country = CountryField(required=False)
class Meta(object):
model = CourseTeam
fields = (
"name",
"course_id",
"description",
"topic_id",
"country",
"language",
)
def create(self, validated_data):
team = CourseTeam.create(
name=validated_data.get("name", ''),
course_id=validated_data.get("course_id"),
description=validated_data.get("description", ''),
topic_id=validated_data.get("topic_id", ''),
country=validated_data.get("country", ''),
language=validated_data.get("language", ''),
)
team.save()
return team
class CourseTeamSerializerWithoutMembership(CourseTeamSerializer):
"""The same as the `CourseTeamSerializer`, but elides the membership field.
Intended to be used as a sub-serializer for serializing team
memberships, since the membership field is redundant in that case.
"""
def __init__(self, *args, **kwargs):
super(CourseTeamSerializerWithoutMembership, self).__init__(*args, **kwargs)
del self.fields['membership']
class MembershipSerializer(serializers.ModelSerializer):
"""Serializes CourseTeamMemberships with information about both teams and users."""
profile_configuration = deepcopy(settings.ACCOUNT_VISIBILITY_CONFIGURATION)
profile_configuration['shareable_fields'].append('url')
profile_configuration['public_fields'].append('url')
user = ExpandableField(
collapsed_serializer=CollapsedReferenceSerializer(
model_class=User,
id_source='username',
view_name='accounts_api',
read_only=True,
),
expanded_serializer=UserReadOnlySerializer(configuration=profile_configuration)
)
team = ExpandableField(
collapsed_serializer=CollapsedReferenceSerializer(
model_class=CourseTeam,
id_source='team_id',
view_name='teams_detail',
read_only=True,
),
expanded_serializer=CourseTeamSerializerWithoutMembership(read_only=True),
)
class Meta(object):
model = CourseTeamMembership
fields = ("user", "team", "date_joined", "last_activity_at")
read_only_fields = ("date_joined", "last_activity_at")
class BaseTopicSerializer(serializers.Serializer):
"""Serializes a topic without team_count."""
description = serializers.CharField()
name = serializers.CharField()
id = serializers.CharField() # pylint: disable=invalid-name
class TopicSerializer(BaseTopicSerializer):
"""
Adds team_count to the basic topic serializer, checking if team_count
is already present in the topic data, and if not, querying the CourseTeam
model to get the count. Requires that `context` is provided with a valid course_id
in order to filter teams within the course.
"""
team_count = serializers.SerializerMethodField()
def get_team_count(self, topic):
"""Get the number of teams associated with this topic"""
# If team_count is already present (possible if topic data was pre-processed for sorting), return it.
if 'team_count' in topic:
return topic['team_count']
else:
return CourseTeam.objects.filter(course_id=self.context['course_id'], topic_id=topic['id']).count()
class BulkTeamCountTopicListSerializer(serializers.ListSerializer): # pylint: disable=abstract-method
"""
List serializer for efficiently serializing a set of topics.
"""
def to_representation(self, obj):
"""Adds team_count to each topic. """
data = super(BulkTeamCountTopicListSerializer, self).to_representation(obj)
add_team_count(data, self.context["course_id"])
return data
class BulkTeamCountTopicSerializer(BaseTopicSerializer): # pylint: disable=abstract-method
"""
Serializes a set of topics, adding the team_count field to each topic as a bulk operation.
Requires that `context` is provided with a valid course_id in order to filter teams within the course.
"""
class Meta(object):
list_serializer_class = BulkTeamCountTopicListSerializer
def add_team_count(topics, course_id):
"""
Helper method to add team_count for a list of topics.
This allows for a more efficient single query.
"""
topic_ids = [topic['id'] for topic in topics]
teams_per_topic = CourseTeam.objects.filter(
course_id=course_id,
topic_id__in=topic_ids
).values('topic_id').annotate(team_count=Count('topic_id'))
topics_to_team_count = {d['topic_id']: d['team_count'] for d in teams_per_topic}
for topic in topics:
topic['team_count'] = topics_to_team_count.get(topic['id'], 0)
|
solashirai/edx-platform
|
lms/djangoapps/teams/serializers.py
|
Python
|
agpl-3.0
| 7,981 | 0.00213 |
import argparse
from getpass import getpass
import json
import sys
import textwrap
import zmq
import colorama
from colorama import Fore
def execute(code):
ctx = zmq.Context.instance()
ctx.setsockopt(zmq.LINGER, 50)
repl_in = ctx.socket(zmq.PUSH)
repl_in.connect('tcp://127.0.0.1:2000')
repl_out = ctx.socket(zmq.PULL)
repl_out.connect('tcp://127.0.0.1:2001')
with repl_in, repl_out:
msg = (b'xcode1', code.encode('utf8'))
repl_in.send_multipart(msg)
while True:
data = repl_out.recv_multipart()
msg_type = data[0].decode('ascii')
msg_data = data[1].decode('utf8')
if msg_type == 'finished':
print('--- finished ---')
break
elif msg_type == 'stdout':
print(msg_data, end='')
sys.stdout.flush()
elif msg_type == 'stderr':
print(Fore.RED + msg_data + Fore.RESET, end='', file=sys.stderr)
sys.stderr.flush()
elif msg_type == 'waiting-input':
opts = json.loads(msg_data)
if opts['is_password']:
t = getpass(prompt='')
else:
t = input()
repl_in.send_multipart([b'input', t.encode('utf8')])
else:
print('--- other msg ---')
print(msg_type)
print(msg_data)
sources = {
'interleaving': '''
import sys
print('asdf', end='', file=sys.stderr)
print('qwer', end='', file=sys.stdout)
print('zxcv', file=sys.stderr)
''',
'long_running': '''
import time
for i in range(10):
time.sleep(1)
print(i)
''',
'user_input': '''
import hashlib
import getpass
print('Please type your name.')
name = input('>> ')
print('Hello, {0}'.format(name))
print('Please type your password.')
pw = getpass.getpass()
m = hashlib.sha256()
m.update(pw.encode('utf8'))
print('Your password hash is {0}'.format(m.hexdigest()))
''',
'early_exception': '''a = wrong-+****syntax''',
'runtime_error': '''
def x():
raise RuntimeError('asdf')
def s():
x()
if __name__ == '__main__':
s()
''',
'tensorflow': '''
import tensorflow as tf
print('TensorFlow version:', tf.__version__)
print(tf.test.is_gpu_available())
print('ok')'''
}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('program_name')
args =parser.parse_args()
src = sources[args.program_name]
print('Test code:')
print(textwrap.indent(src, ' '))
print()
print('Execution log:')
execute(src)
if __name__ == '__main__':
colorama.init()
main()
|
lablup/sorna-repl
|
python-tensorflow/test_run.py
|
Python
|
lgpl-3.0
| 2,665 | 0.001876 |
# This program 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.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# $Id: WindowManager.py 30 2009-04-20 05:16:40Z patryn $
#*****************************************************************************
# -*- coding: utf-8 -*-
import PyQt4
import sys
from PyQt4 import QtGui, QtCore
from Ui_MainWindow import Ui_MainWindow
from Ui_TableWindow import Ui_TableWindow
from Ui_PortDialog import Ui_PortDialog
from Ui_ParamDialog import Ui_ParamDialog
from Ui_AboutWindow import Ui_AboutDialog
from Ui_SimSettingsWindow import Ui_SimSettingsWindow
from CreateOutput import *
from Common import *
ROW_ADD, ROW_EDIT = range(2)
#--------------------------------------------------------------------
class WindowManagerClass:
def __init__(self, MainWindow):
self.MainWindow = MainWindow
self.Settings = DataHolderClass()
self.WindowIndex = MAIN_WINDOW
self.Ui = None
Screen = QtGui.QDesktopWidget().screenGeometry()
Size = self.MainWindow.geometry()
self.MainWindow.move((Screen.width() - Size.width()) / 2, (Screen.height() - Size.height()) / 2)
def ShowAbout(self):
AboutDialog = QtGui.QDialog()
Ui = Ui_AboutDialog()
Ui.setupUi(AboutDialog)
AboutDialog.exec_()
def ShowAboutQt(self):
QtGui.QMessageBox.aboutQt(None)
#---------------------- Main Window -------------------
def CreateMainWindow(self):
self.Ui.setupUi(self.MainWindow)
self.Ui.lineEditName.setText(self.Settings.sfunctionName)
self.Ui.comboBoxSampleTime.addItems(SampleTimesList)
self.Ui.comboBoxSampleTime.setEditText(self.Settings.sfunctionSampleTime)
self.Ui.comboBoxOffsetTime.addItems(OffsetTimesList)
self.Ui.comboBoxOffsetTime.setEditText(self.Settings.sfunctionOffsetTime)
self.Ui.comboBoxCont.addItems(StatesList)
self.Ui.comboBoxCont.setEditText(self.Settings.sfunctionContStateNum)
self.Ui.comboBoxDisc.addItems(StatesList)
self.Ui.comboBoxDisc.setEditText(self.Settings.sfunctionDiscStateNum)
QtCore.QObject.connect(self.Ui.pushButtonNext, QtCore.SIGNAL('clicked()'), self.NextWindow)
def ProcessMainWindowValues(self):
self.Settings.sfunctionName = self.Ui.lineEditName.text()
self.Settings.sfunctionSampleTime = self.Ui.comboBoxSampleTime.currentText()
self.Settings.sfunctionOffsetTime = self.Ui.comboBoxOffsetTime.currentText()
self.Settings.sfunctionContStateNum = self.Ui.comboBoxCont.currentText()
self.Settings.sfunctionDiscStateNum = self.Ui.comboBoxDisc.currentText()
if not IsValidName(self.Settings.sfunctionName):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid sfunction Name", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
if (not IsValidNumber(self.Settings.sfunctionSampleTime)) and (self.Settings.sfunctionSampleTime not in SampleTimesList):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid Sample Time", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
if (not IsValidNumber(self.Settings.sfunctionOffsetTime)) and (self.Settings.sfunctionOffsetTime not in OffsetTimesList):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid Offset Time", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
if (not IsValidNumber(self.Settings.sfunctionContStateNum)) and (self.Settings.sfunctionContStateNum not in StatesList):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid number of Continuous States", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
if (not IsValidNumber(self.Settings.sfunctionDiscStateNum)) and (self.Settings.sfunctionDiscStateNum not in StatesList):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid number of Discrete States", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
return True
#---------------------- Ports, Parameters and PWork Windows -------------------
def ReadTableRow(self, CurrentRow):
ValuesList = []
if(self.WindowIndex == PORTS_WINDOW):
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PORT_NAME_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PORT_DIR_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PORT_TYPE_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PORT_WIDTH_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PORT_COUNT_COL).text())
if(self.WindowIndex == PARAMS_WINDOW):
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PARAM_NAME_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PARAM_TYPE_COL).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PARAM_MDLINIT).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PARAM_MDLSTART).text())
ValuesList.append(self.Ui.tableWidgetTable.item(CurrentRow, PARAM_MDLOUTPUTS).text())
return ValuesList
def ShowInputDialog(self):
InputDialog = QtGui.QDialog()
if(self.WindowIndex == PORTS_WINDOW):
self.InputUi = Ui_PortDialog()
self.InputUi.setupUi(InputDialog)
self.InputUi.comboBoxDirection.addItems(PortDirectonList)
self.InputUi.comboBoxType.addItems(PortTypeList)
if (self.TableAction == ROW_EDIT):
CurrentRow = self.Ui.tableWidgetTable.currentRow()
ValuesList = self.ReadTableRow(CurrentRow)
self.InputUi.lineEditPortName.setText(ValuesList[PORT_NAME_COL])
self.InputUi.comboBoxDirection.setCurrentIndex(PortDirectonList.index(ValuesList[PORT_DIR_COL]))
self.InputUi.comboBoxType.setCurrentIndex(PortTypeList.index(ValuesList[PORT_TYPE_COL]))
self.InputUi.spinBoxWidth.setValue(int(ValuesList[PORT_WIDTH_COL]))
self.InputUi.spinBoxCount.setValue(int(ValuesList[PORT_COUNT_COL]))
elif (self.WindowIndex == PARAMS_WINDOW):
self.InputUi = Ui_ParamDialog()
self.InputUi.setupUi(InputDialog)
self.InputUi.comboBoxType.addItems(ParamTypeList)
if (self.TableAction == ROW_EDIT):
CurrentRow = self.Ui.tableWidgetTable.currentRow()
ValuesList = self.ReadTableRow(CurrentRow)
self.InputUi.lineEditParamName.setText(ValuesList[PARAM_NAME_COL])
self.InputUi.comboBoxType.setCurrentIndex(ParamTypeList.index(ValuesList[PARAM_TYPE_COL]))
if (ValuesList[PARAM_MDLINIT] == "Yes"):
self.InputUi.checkBoxmdlInitializeSizes.setCheckState(QtCore.Qt.Checked)
else:
self.InputUi.checkBoxmdlInitializeSizes.setCheckState(QtCore.Qt.Unchecked)
if (ValuesList[PARAM_MDLSTART] == "Yes"):
self.InputUi.checkBoxmdlStart.setCheckState(QtCore.Qt.Checked)
else:
self.InputUi.checkBoxmdlStart.setCheckState(QtCore.Qt.Unchecked)
if (ValuesList[PARAM_MDLOUTPUTS] == "Yes"):
self.InputUi.checkBoxmdlOutputs.setCheckState(QtCore.Qt.Checked)
else:
self.InputUi.checkBoxmdlOutputs.setCheckState(QtCore.Qt.Unchecked)
QtCore.QObject.connect(self.InputUi.buttonBox, QtCore.SIGNAL('accepted()'), self.ItemAdded)
InputDialog.exec_()
def TableWindowAddItem(self):
self.TableAction = ROW_ADD
self.ShowInputDialog()
def TableWindowEditItem(self):
if (self.Ui.tableWidgetTable.currentRow() == -1):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Select a row to edit", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return
self.TableAction = ROW_EDIT
self.ShowInputDialog()
def TableWindowRemoveItem(self):
if (self.Ui.tableWidgetTable.currentRow() == -1):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Select a row to remove", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return
CurrentRow = self.Ui.tableWidgetTable.currentRow()
self.Ui.tableWidgetTable.removeRow(CurrentRow)
self.Ui.tableWidgetTable.setCurrentCell(CurrentRow - 1, 0)
def ItemMoveUp(self):
CurrentRow = self.Ui.tableWidgetTable.currentRow()
if (CurrentRow == -1):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Select a row to move up", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return
if(CurrentRow == 0):
return
Items = self.ReadTableRow(CurrentRow)
self.Ui.tableWidgetTable.insertRow(CurrentRow - 1)
for Index, Item in enumerate(Items):
self.Ui.tableWidgetTable.setItem(CurrentRow - 1, Index, QtGui.QTableWidgetItem(str(Item)))
self.Ui.tableWidgetTable.removeRow(CurrentRow + 1)
self.Ui.tableWidgetTable.setCurrentCell(CurrentRow - 1, 0)
def ItemMoveDown(self):
CurrentRow = self.Ui.tableWidgetTable.currentRow()
if (CurrentRow == -1):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Select a row to move down", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return
if(CurrentRow == self.Ui.tableWidgetTable.rowCount() - 1):
return
Items = self.ReadTableRow(CurrentRow)
self.Ui.tableWidgetTable.insertRow(CurrentRow + 2)
for Index, Item in enumerate(Items):
self.Ui.tableWidgetTable.setItem(CurrentRow + 2, Index, QtGui.QTableWidgetItem(str(Item)))
self.Ui.tableWidgetTable.removeRow(CurrentRow)
self.Ui.tableWidgetTable.setCurrentCell(CurrentRow + 1, 0)
def ItemAdded(self):
if(self.WindowIndex == PORTS_WINDOW):
if not IsValidName(self.InputUi.lineEditPortName.text()):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid Port Name", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
Port = []
Port.append(self.InputUi.lineEditPortName.text())
Port.append(self.InputUi.comboBoxDirection.currentText())
Port.append(self.InputUi.comboBoxType.currentText())
Port.append(self.InputUi.spinBoxWidth.value())
Port.append(self.InputUi.spinBoxCount.value())
if (self.TableAction == ROW_ADD):
self.Ui.tableWidgetTable.insertRow(self.Ui.tableWidgetTable.rowCount())
Row = self.Ui.tableWidgetTable.rowCount() - 1
else:
Row = self.Ui.tableWidgetTable.currentRow()
for Index, Item in enumerate(Port):
self.Ui.tableWidgetTable.setItem(Row, Index, QtGui.QTableWidgetItem(str(Item)))
elif(self.WindowIndex == PARAMS_WINDOW):
if not IsValidName(self.InputUi.lineEditParamName.text()):
QtGui.QMessageBox.critical(self.MainWindow, "Error", "Invalid Parameter Name", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return False
Param = []
Param.append(self.InputUi.lineEditParamName.text())
Param.append(self.InputUi.comboBoxType.currentText())
if (self.InputUi.checkBoxmdlInitializeSizes.checkState() == 2):
Param.append("Yes")
else:
Param.append("No")
if (self.InputUi.checkBoxmdlStart.checkState() == 2):
Param.append("Yes")
else:
Param.append("No")
if (self.InputUi.checkBoxmdlOutputs.checkState() == 2):
Param.append("Yes")
else:
Param.append("No")
if (self.TableAction == ROW_ADD):
self.Ui.tableWidgetTable.insertRow(self.Ui.tableWidgetTable.rowCount())
Row = self.Ui.tableWidgetTable.rowCount() - 1
else:
Row = self.Ui.tableWidgetTable.currentRow()
for Index, Item in enumerate(Param):
self.Ui.tableWidgetTable.setItem(Row, Index, QtGui.QTableWidgetItem(str(Item)))
self.Ui.tableWidgetTable.resizeColumnsToContents()
def CreateTableWindow(self):
self.Ui.setupUi(self.MainWindow)
self.Ui.tableWidgetTable.setRowCount(0)
if(self.WindowIndex == PORTS_WINDOW):
self.MainWindow.setWindowTitle("Simulink sfunction Generation Wizard - Step 2")
self.Ui.groupBoxGroup.setTitle("Ports Settings")
self.Ui.tableWidgetTable.setColumnCount(5)
self.Ui.tableWidgetTable.setHorizontalHeaderLabels(["Port Name", "Direction", "Type", "Width", "Count"])
InitList = self.Settings.PortList
elif (self.WindowIndex == PARAMS_WINDOW):
self.MainWindow.setWindowTitle("Simulink sfunction Wizard - Step 3")
self.Ui.groupBoxGroup.setTitle("sfunction Parameters")
self.Ui.tableWidgetTable.setColumnCount(5)
self.Ui.tableWidgetTable.setHorizontalHeaderLabels(["Parameter", "Type", "mdlInitSizes()", "mdlStart()", "mdlOutputs()"])
InitList = self.Settings.ParamList
for ListItem in InitList:
self.Ui.tableWidgetTable.insertRow(self.Ui.tableWidgetTable.rowCount())
Row = self.Ui.tableWidgetTable.rowCount() - 1
for Index, Item in enumerate(ListItem):
self.Ui.tableWidgetTable.setItem(Row, Index, QtGui.QTableWidgetItem(str(Item)))
self.Ui.tableWidgetTable.resizeColumnsToContents()
QtCore.QObject.connect(self.Ui.pushButtonNext, QtCore.SIGNAL('clicked()'), self.NextWindow)
QtCore.QObject.connect(self.Ui.pushButtonBack, QtCore.SIGNAL('clicked()'), self.PreviousWindow)
QtCore.QObject.connect(self.Ui.pushButtonAdd, QtCore.SIGNAL('clicked()'), self.TableWindowAddItem)
QtCore.QObject.connect(self.Ui.pushButtonEdit, QtCore.SIGNAL('clicked()'), self.TableWindowEditItem)
QtCore.QObject.connect(self.Ui.pushButtonRemove, QtCore.SIGNAL('clicked()'), self.TableWindowRemoveItem)
QtCore.QObject.connect(self.Ui.pushButtonUp, QtCore.SIGNAL('clicked()'), self.ItemMoveUp)
QtCore.QObject.connect(self.Ui.pushButtonDown, QtCore.SIGNAL('clicked()'), self.ItemMoveDown)
def ProcessTableValues(self):
ResultList = []
for I in range(0, self.Ui.tableWidgetTable.rowCount()):
PortValues = self.ReadTableRow(I)
ResultList.append(PortValues)
if(self.WindowIndex == PORTS_WINDOW):
self.Settings.PortList = ResultList
elif (self.WindowIndex == PARAMS_WINDOW):
self.Settings.ParamList = ResultList
return True
#---------------------- Simulation settings Window -------------------
def CreateSimSettingsWindow(self):
self.Ui.setupUi(self.MainWindow)
self.CheckBoxList = []
self.CheckBoxList.append(self.Ui.checkBoxOpt_1); self.CheckBoxList.append(self.Ui.checkBoxOpt_2); self.CheckBoxList.append(self.Ui.checkBoxOpt_3)
self.CheckBoxList.append(self.Ui.checkBoxOpt_4); self.CheckBoxList.append(self.Ui.checkBoxOpt_5); self.CheckBoxList.append(self.Ui.checkBoxOpt_6)
self.CheckBoxList.append(self.Ui.checkBoxOpt_7); self.CheckBoxList.append(self.Ui.checkBoxOpt_8); self.CheckBoxList.append(self.Ui.checkBoxOpt_9)
self.CheckBoxList.append(self.Ui.checkBoxOpt_10); self.CheckBoxList.append(self.Ui.checkBoxOpt_11); self.CheckBoxList.append(self.Ui.checkBoxOpt_12)
self.CheckBoxList.append(self.Ui.checkBoxOpt_13); self.CheckBoxList.append(self.Ui.checkBoxOpt_14); self.CheckBoxList.append(self.Ui.checkBoxOpt_15)
self.CheckBoxList.append(self.Ui.checkBoxOpt_16); self.CheckBoxList.append(self.Ui.checkBoxOpt_17); self.CheckBoxList.append(self.Ui.checkBoxOpt_18)
self.CheckBoxList.append(self.Ui.checkBoxOpt_19); self.CheckBoxList.append(self.Ui.checkBoxOpt_20); self.CheckBoxList.append(self.Ui.checkBoxOpt_21)
self.CheckBoxList.append(self.Ui.checkBoxOpt_22)
for Index, Item in enumerate(self.CheckBoxList):
Item.setText(OptionsList[Index])
Item.setCheckState(self.Settings.SimSettings[Index])
QtCore.QObject.connect(self.Ui.pushButtonFinish, QtCore.SIGNAL('clicked()'), self.Finish)
QtCore.QObject.connect(self.Ui.pushButtonBack, QtCore.SIGNAL('clicked()'), self.PreviousWindow)
def ProcessSimSettingsValues(self):
for Index, Item in enumerate(self.CheckBoxList):
self.Settings.SimSettings[Index] = Item.checkState()
return True
#---------------------- Generic Window Management -------------------
def ProcessValues(self):
if(self.WindowIndex == MAIN_WINDOW):
return self.ProcessMainWindowValues()
elif(self.WindowIndex == PORTS_WINDOW) or (self.WindowIndex == PARAMS_WINDOW):
return self.ProcessTableValues()
elif(self.WindowIndex == SIMULATION_SETTINGS_WINDOW):
return self.ProcessSimSettingsValues()
return True
def NextWindow(self):
if not self.ProcessValues():
return False
self.WindowIndex = self.WindowIndex + 1
self.CreateWindow()
def PreviousWindow(self):
if not self.ProcessValues():
return False
self.WindowIndex = self.WindowIndex - 1
self.CreateWindow()
def Finish(self):
if not self.ProcessValues():
return False
CreateFiles(self.Settings)
QtGui.QMessageBox.information(self.MainWindow, "Done!", "Output files created successfully.", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
def CreateWindow(self):
if(self.WindowIndex == MAIN_WINDOW):
self.Ui=Ui_MainWindow()
self.CreateMainWindow()
elif(self.WindowIndex == PORTS_WINDOW) or (self.WindowIndex == PARAMS_WINDOW):
self.Ui=Ui_TableWindow()
self.CreateTableWindow()
elif(self.WindowIndex == SIMULATION_SETTINGS_WINDOW):
self.Ui=Ui_SimSettingsWindow()
self.CreateSimSettingsWindow()
QtCore.QObject.connect(self.Ui.actionAbout, QtCore.SIGNAL('activated()'), self.ShowAbout)
QtCore.QObject.connect(self.Ui.actionAbout_Qt, QtCore.SIGNAL('activated()'), self.ShowAboutQt)
|
Gorbeh/sf
|
src/WindowManager.py
|
Python
|
agpl-3.0
| 16,966 | 0.0234 |
import numpy as np
import gelato
import pytest
@pytest.fixture()
def seeded():
gelato.set_tt_rng(42)
np.random.seed(42)
|
ferrine/gelato
|
gelato/tests/conftest.py
|
Python
|
mit
| 130 | 0 |
import subprocess
import json
import math
import re
import lizard
from jinja2 import Environment, FileSystemLoader
from xml.dom import minidom
from decimal import Decimal
from analyzr.settings import CONFIG_PATH, PROJECT_PATH, LAMBDA
XML_ILLEGAL = u'([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'
RE_XML_ILLEGAL = XML_ILLEGAL % (
unichr(0xd800),
unichr(0xdbff),
unichr(0xdc00),
unichr(0xdfff),
unichr(0xd800),
unichr(0xdbff),
unichr(0xdc00),
unichr(0xdfff),
unichr(0xd800),
unichr(0xdbff),
unichr(0xdc00),
unichr(0xdfff)
)
class CheckerException(Exception):
def __init__(self, checker, cmd, stdout="", stderr=""):
self.checker = checker
self.cmd = cmd
self.stdout = stdout
self.stderr = stderr
super(CheckerException, self).__init__()
def __str__(self):
value = "STDOUT:\n%s\n\nSTDERR:\n%s" % (self.stdout, self.stderr)
return "%s raised an error while running command:\n\n%s\n\n%s" % (
self.checker,
" ".join(self.cmd),
value
)
def __unicode__(self):
return self.__str__()
def __repr__(self):
return self.__unicode__()
class Checker(object):
def __init__(self, config_path, result_path):
self.measures = {}
self.env = Environment(loader=FileSystemLoader(CONFIG_PATH))
self.config_path = config_path
self.result_path = result_path
self.files = []
def __str__(self):
return self.__unicode__()
def includes(self, filename):
for f in self.files:
if f.endswith(filename):
return True
return False
def get_decimal(self, value):
return Decimal("%s" % round(float(value), 2))
def execute(self, cmd):
# close_fds must be true as python would otherwise reuse created
# file handles. this would cause a serious memory leak.
# btw: the file handles are craeted because we pipe stdout and
# stderr to them.
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
stdout, stderr = proc.communicate()
if not proc.returncode == 0:
raise CheckerException(self, cmd, stdout=stdout, stderr=stderr)
return stdout
def stub(self):
return {
"cyclomatic_complexity": 0,
"halstead_volume": 0,
"halstead_difficulty": 0,
"fan_in": 0,
"fan_out": 0,
"sloc_absolute": 0,
"sloc": 0
}
def set(self, filename, key, value):
if not filename in self.measures:
self.measures[filename] = self.stub()
self.measures[filename][key] = self.get_decimal(value)
def get_value_in_range(self, value, low, high):
high = high * 1.0
low = low * 1.0
if value <= low:
return 3.0
if value >= high:
return 0.0
return 3.0 - 3.0 * (value / high)
def squale(self, marks):
sum_marks = math.fsum([math.pow(LAMBDA, -1.0 * mark) for mark in marks])
return -1.0 * math.log(sum_marks / (1.0 * len(marks)), LAMBDA)
def get_hv_mark(self, value):
return self.get_value_in_range(value, 20, 1000)
def get_hd_mark(self, value):
return self.get_value_in_range(value, 10, 50)
def get_cc_mark(self, value):
if value <= 2:
return 3.0
if value >= 20:
return 0.0
return math.pow(2, (7 - value) / 3.5)
def get_sloc_mark(self, value):
if value <= 37:
return 3.0
if value >= 162:
return 0.0
return math.pow(2, (70 - value) / 21.0)
def get_fan_in_mark(self, value):
if value <= 19:
return 3.0
if value >= 60:
return 0.0
return math.pow(2, (30 - value) / 7.0)
def get_fan_out_mark(self, value):
if value <= 6:
return 3.0
if value >= 19:
return 0.0
return math.pow(2, (10 - value) / 2.0)
def configure(self, files, revision, connector):
raise NotImplementedError
def run(self):
raise NotImplementedError
def parse(self, connector):
raise NotImplementedError
class JHawk(Checker):
# determines how many files are analyzed at once
# this is important as for revisions with a lot of files the
# generated report might not fit into main memory or can't
# be parsed.
FILE_BATCH_SIZE = 50
def __init__(self, config_path, result_path):
super(JHawk, self).__init__(config_path, result_path)
self.name = "jhawk"
self.files = []
self.configurations = []
self.results = []
def config_file(self, revision, part):
return "%s/%s_%d.xml" % (self.config_path, revision.identifier, part)
def result_file(self, revision, part):
return "%s/%s_%d" % (self.result_path, revision.identifier, part)
def configure(self, files, revision, connector):
for f in files:
self.files.append(f.full_path())
self.measures = {}
self.configurations = []
self.results = []
template = self.env.get_template("%s.xml" % self.name)
file_count = len(files)
chunks = int(math.ceil(file_count / self.FILE_BATCH_SIZE))
if not file_count % self.FILE_BATCH_SIZE == 0:
chunks = chunks + 1
for i in range(chunks):
start = i * self.FILE_BATCH_SIZE
end = min((i + 1) * self.FILE_BATCH_SIZE, file_count)
chunk = files[start:end]
filename = self.config_file(revision, i)
result_file = self.result_file(revision, i)
options = {
"checker": self.name,
"project_path": PROJECT_PATH,
"base_path": connector.get_repo_path(),
"target": result_file,
"filepattern": "|".join([".*/%s" % f.name for f in chunk])
}
with open(filename, "wb") as f:
f.write(template.render(options))
self.configurations.append(filename)
self.results.append(result_file)
self.revision = revision
def run(self):
for configuration in self.configurations:
cmd = [
"ant",
"-lib", "%s/lib/%s/JHawkCommandLine.jar" % (PROJECT_PATH, self.name),
"-f", configuration
]
self.execute(cmd)
# Don't allow multiple runs with the same configuration
self.configurations = []
return True
def get_metrics(self, parent):
for node in parent.childNodes:
if node.localName == "Metrics":
return node
def get_node_value(self, parent, node_name):
for node in parent.childNodes:
if node.localName == node_name:
return node.firstChild.nodeValue
def get_number(self, parent, node_name):
return float(self.get_node_value(parent, node_name))
def get_name(self, parent):
return self.get_node_value(parent, "Name")
def get_sloc_squale(self, methods):
marks = []
for method in methods:
metrics = self.get_metrics(method)
marks.append(self.get_sloc_mark(self.get_number(metrics, "loc")))
return self.squale(marks)
def get_hv_squale(self, methods):
marks = []
for method in methods:
metrics = self.get_metrics(method)
marks.append(self.get_hv_mark(self.get_number(metrics, "halsteadVolume")))
return self.squale(marks)
def add_halstead_metrics(self, filename, methods):
marks = []
for method in methods:
metrics = self.get_metrics(method)
volume = self.get_number(metrics, "halsteadVolume")
effort = self.get_number(metrics, "halsteadEffort")
difficulty = effort / volume
marks.append(self.get_hd_mark(difficulty))
self.set(filename, "halstead_difficulty", self.squale(marks))
self.set(filename, "halstead_volume", self.get_hv_squale(methods))
def get_cc_squale(self, methods):
marks = []
for method in methods:
metrics = self.get_metrics(method)
marks.append(self.get_cc_mark(self.get_number(metrics, "cyclomaticComplexity")))
return self.squale(marks)
def mark_faults(self, processed):
for f in self.files:
found = False
for p in processed:
if found:
continue
if f.endswith(p):
found = True
continue
if not found:
# All files should have been processed but weren't must contain
# some kind of error
error = self.revision.get_file(f)
error.faulty = True
error.save()
def parse(self, connector):
processed = []
for result in self.results:
with open("%s.xml" % result, "r") as f:
content = f.read()
content = re.sub(RE_XML_ILLEGAL, "?", content)
xml_doc = minidom.parseString(content.encode("utf-8"))
packages = xml_doc.getElementsByTagName("Package")
for package in packages:
name = self.get_name(package)
classes = package.getElementsByTagName("Class")
path = name.replace(".", "/")
for cls in classes:
class_metrics = self.get_metrics(cls)
class_name = self.get_node_value(cls, "ClassName")
if "$" in class_name:
# private class inside of class
# ignore!
continue
filename = "%s/%s.java" % (path, class_name)
if not self.includes(filename):
continue
processed.append(filename)
methods = cls.getElementsByTagName("Method")
if len(methods) == 0:
continue
self.add_halstead_metrics(filename, methods)
self.set(filename, "cyclomatic_complexity", self.get_cc_squale(methods))
self.set(filename, "sloc", self.get_sloc_squale(methods))
self.set(filename, "sloc_absolute", self.get_node_value(class_metrics, "loc"))
fan_in = self.get_number(class_metrics, "fanIn")
fan_out = self.get_number(class_metrics, "fanOut")
self.set(filename, "fan_in", self.get_fan_in_mark(fan_in))
self.set(filename, "fan_out", self.get_fan_out_mark(fan_out))
self.mark_faults(processed)
return self.measures
def __unicode__(self):
return "JHawk Java Checker"
class ComplexityReport(Checker):
def __init__(self, config_path, result_path):
super(ComplexityReport, self).__init__(config_path, result_path)
self.files = []
def __unicode__(self):
return "Complexity Report JavaScript Checker"
def result_file(self, revision):
return "%s/%s" % (self.result_path, revision.identifier)
def configure(self, files, revision, connector):
self.result = self.result_file(revision)
self.files = files
self.base_path = connector.get_repo_path()
def get_file_path(self, f):
return "%s/%s" % (self.base_path, f.full_path())
def run(self):
self.failed = []
for f in self.files:
path = self.get_file_path(f)
result = "%s_%s.json" % (self.result, f.get_identifier())
cmd = ["cr", "-f", "json", "-o", result, path]
try:
self.execute(cmd)
except CheckerException, e:
if not e.stdout.startswith("Fatal error") and not e.stderr.startswith("Fatal error"):
raise e
# Ignore syntax errors in checked files
self.failed.append(f.get_identifier())
# mark file as faulty
f.faulty = True
f.save()
return True
def get_cc_squale(self, functions):
marks = []
for function in functions:
marks.append(self.get_cc_mark(function["cyclomatic"]))
return self.squale(marks)
def get_hv_squale(self, functions):
marks = []
for function in functions:
marks.append(self.get_hv_mark(function["halstead"]["volume"]))
return self.squale(marks)
def get_hd_squale(self, functions):
marks = []
for function in functions:
marks.append(self.get_hd_mark(function["halstead"]["difficulty"]))
return self.squale(marks)
def get_sloc_squale(self, functions):
marks = []
for function in functions:
marks.append(self.get_sloc_mark(function["sloc"]["logical"]))
return self.squale(marks)
def parse(self, connector):
for f in self.files:
identifier = f.get_identifier()
if identifier in self.failed:
continue
path = "%s_%s.json" % (self.result, identifier)
with open(path) as result:
contents = json.load(result)
if not contents or not "reports" in contents or not contents["reports"]:
continue
data = contents["reports"][0]
if len(data["functions"]) == 0:
continue
filename = f.full_path()
functions = data["functions"]
self.set(filename, "cyclomatic_complexity", self.get_cc_squale(functions))
self.set(filename, "halstead_volume", self.get_hv_squale(functions))
self.set(filename, "halstead_difficulty", self.get_hd_squale(functions))
self.set(filename, "sloc", self.get_sloc_squale(functions))
self.set(filename, "sloc_absolute", data["aggregate"]["sloc"]["logical"])
return self.measures
class Lizard(Checker):
def __init__(self, config_path, result_path):
self.files = []
super(Lizard, self).__init__(config_path, result_path)
def configure(self, files, revision, connector):
self.files = files
self.path = connector.get_repo_path()
def run(self):
for f in self.files:
result = lizard.analyze_file("%s/%s" % (self.path, f.full_path()))
self.set(f.full_path(), "sloc", result.nloc)
self.set(f.full_path(), "cyclomatic_complexity", result.average_CCN)
def average(self, functions):
if len(functions) == 0:
return 0
return sum([function.cyclomatic_complexity for function in functions]) / len(functions)
def parse(self, connector):
return self.measures
|
frontendphil/analyzr
|
parsr/checkers.py
|
Python
|
mit
| 15,240 | 0.001247 |
def json_headers(f):
def wrapped(*args, **kwargs):
resp = f(*args, **kwargs)
resp.headers['Content-Type'] = 'application/json'
return resp
return wrapped
def max_age_headers(f):
def wrapped(*args, **kwargs):
resp = f(*args, **kwargs)
resp.headers['Access-Control-Max-Age'] = 9999999
return resp
return wrapped
|
ryepdx/scale_proxy_server
|
header_decorators.py
|
Python
|
agpl-3.0
| 376 | 0.005319 |
from __future__ import unicode_literals
from datetime import date, time, datetime
import django
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
from custard.conf import (CUSTOM_TYPE_TEXT, CUSTOM_TYPE_INTEGER,
CUSTOM_TYPE_BOOLEAN, CUSTOM_TYPE_FLOAT,
CUSTOM_TYPE_DATE, CUSTOM_TYPE_DATETIME,
CUSTOM_TYPE_TIME, settings)
from custard.builder import CustomFieldsBuilder
from custard.utils import import_class
from .models import (SimpleModelWithManager, SimpleModelWithoutManager,
CustomFieldsModel, CustomValuesModel, builder,
SimpleModelUnique, CustomFieldsUniqueModel, CustomValuesUniqueModel, builder_unique)
#==============================================================================
class SimpleModelWithManagerForm(builder.create_modelform()):
class Meta:
model = SimpleModelWithManager
fields = '__all__'
#class ExampleAdmin(admin.ModelAdmin):
# form = ExampleForm
# search_fields = ('name',)
#
# def get_search_results(self, request, queryset, search_term):
# queryset, use_distinct = super(ExampleAdmin, self).get_search_results(request, queryset, search_term)
# queryset |= self.model.objects.search(search_term)
# return queryset, use_distinct
#
# admin.site.register(Example, ExampleAdmin)
#==============================================================================
class CustomModelsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.simple_with_manager_ct = ContentType.objects.get_for_model(SimpleModelWithManager)
self.simple_without_manager_ct = ContentType.objects.get_for_model(SimpleModelWithoutManager)
self.simple_unique = ContentType.objects.get_for_model(SimpleModelUnique)
self.cf = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='text_field',
label="Text field",
data_type=CUSTOM_TYPE_TEXT)
self.cf.save()
self.cf2 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='another_text_field',
label="Text field 2",
data_type=CUSTOM_TYPE_TEXT,
required=True,
searchable=False)
self.cf2.clean()
self.cf2.save()
self.cf3 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='int_field', label="Integer field",
data_type=CUSTOM_TYPE_INTEGER)
self.cf3.save()
self.cf4 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='boolean_field', label="Boolean field",
data_type=CUSTOM_TYPE_BOOLEAN)
self.cf4.save()
self.cf5 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='float_field', label="Float field",
data_type=CUSTOM_TYPE_FLOAT)
self.cf5.save()
self.cf6 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='date_field', label="Date field",
data_type=CUSTOM_TYPE_DATE)
self.cf6.save()
self.cf7 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='datetime_field', label="Datetime field",
data_type=CUSTOM_TYPE_DATETIME)
self.cf7.save()
self.cf8 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='time_field', label="Time field",
data_type=CUSTOM_TYPE_TIME)
self.cf8.save()
self.obj = SimpleModelWithManager.objects.create(name='old test')
self.obj.save()
def tearDown(self):
CustomFieldsModel.objects.all().delete()
def test_import_class(self):
self.assertEqual(import_class('custard.builder.CustomFieldsBuilder'), CustomFieldsBuilder)
def test_model_repr(self):
self.assertEqual(repr(self.cf), "<CustomFieldsModel: text_field>")
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="abcdefg")
val.save()
self.assertEqual(repr(val), "<CustomValuesModel: text_field: abcdefg>")
@override_settings(CUSTOM_CONTENT_TYPES=['tests.SimpleModelWithManager'])
def test_field_creation(self):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel',
'tests.CustomValuesModel',
settings.CUSTOM_CONTENT_TYPES)
class TestCustomFieldsModel(builder2.create_fields()):
class Meta:
app_label = 'tests'
self.assertQuerysetEqual(ContentType.objects.filter(builder2.content_types_query),
ContentType.objects.filter(Q(app_label__in=['tests'],
model__in=['SimpleModelWithManager'])))
def test_mixin(self):
self.assertIn(self.cf, self.obj.get_custom_fields())
self.assertIn(self.cf, SimpleModelWithManager.get_model_custom_fields())
with self.assertRaises(ObjectDoesNotExist):
self.obj.get_custom_value(self.cf2)
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="123456")
val.save()
self.assertEqual("123456", self.obj.get_custom_value(self.cf).value)
self.obj.set_custom_value(self.cf, "abcdefg")
self.assertEqual("abcdefg", self.obj.get_custom_value(self.cf).value)
val.delete()
def test_field_model_clean(self):
cf = CustomFieldsUniqueModel.objects.create(content_type=self.simple_unique,
name='xxx',
label="Field not present anywhere",
data_type=CUSTOM_TYPE_TEXT)
cf.full_clean()
cf.save()
cf = CustomFieldsUniqueModel.objects.create(content_type=self.simple_unique,
name='xxx',
label="Field already in custom fields",
data_type=CUSTOM_TYPE_TEXT)
with self.assertRaises(ValidationError):
cf.full_clean()
cf = CustomFieldsUniqueModel.objects.create(content_type=self.simple_unique,
name='name',
label="Field already present in model",
data_type=CUSTOM_TYPE_INTEGER)
with self.assertRaises(ValidationError):
cf.full_clean()
def test_value_model_clean(self):
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk)
val.value = "qwertyuiop"
val.save()
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk)
val.value = "qwertyuiop"
with self.assertRaises(ValidationError):
val.full_clean()
def test_value_types_accessor(self):
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk,
value="xxxxxxxxxxxxx")
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf3,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf3,
object_id=self.obj.pk,
value=1)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf4,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf4,
object_id=self.obj.pk,
value=True)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf5,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf5,
object_id=self.obj.pk,
value=3.1456)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf6,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf6,
object_id=self.obj.pk,
value=date.today())
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf7,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf7,
object_id=self.obj.pk,
value=datetime.now())
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf8,
object_id=self.obj.pk)
val.save()
val = val.value
val = CustomValuesModel.objects.create(custom_field=self.cf8,
object_id=self.obj.pk,
value=datetime.now().time())
val.save()
val = val.value
def test_value_creation(self):
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="qwertyuiop")
val.save()
self.assertEqual(val.content_type, self.simple_with_manager_ct)
self.assertEqual(val.content_type, val.custom_field.content_type)
self.assertEqual(val.value_text, "qwertyuiop")
self.assertEqual(val.value, "qwertyuiop")
def test_value_search(self):
newobj = SimpleModelWithManager.objects.create(name='new simple')
newobj.save()
v1 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="qwertyuiop")
v1.save()
v2 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=newobj.pk,
value="qwertyuiop")
v2.save()
v3 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=newobj.pk,
value="000asdf123")
v3.save()
qs1 = SimpleModelWithManager.objects.search("asdf")
self.assertQuerysetEqual(qs1, [repr(newobj)])
qs2 = SimpleModelWithManager.objects.search("qwerty")
self.assertQuerysetEqual(qs2, [repr(self.obj), repr(newobj)], ordered=False)
def test_value_search_not_searchable_field(self):
v1 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="12345")
v1.save()
v2 = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk,
value="67890")
v2.save()
qs1 = SimpleModelWithManager.objects.search("12345")
self.assertQuerysetEqual(qs1, [repr(self.obj)])
qs2 = SimpleModelWithManager.objects.search("67890")
self.assertQuerysetEqual(qs2, [])
def test_get_formfield_for_field(self):
with self.settings(CUSTOM_FIELD_TYPES={CUSTOM_TYPE_TEXT: 'django.forms.fields.EmailField'}):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel', 'tests.CustomValuesModel')
class SimpleModelWithManagerForm2(builder2.create_modelform(field_types=settings.CUSTOM_FIELD_TYPES)):
class Meta:
model = SimpleModelWithManager
fields = '__all__'
form = SimpleModelWithManagerForm2(data={}, instance=self.obj)
self.assertIsNotNone(form.get_formfield_for_field(self.cf))
self.assertEqual(django.forms.fields.EmailField, form.get_formfield_for_field(self.cf).__class__)
def test_get_widget_for_field(self):
with self.settings(CUSTOM_WIDGET_TYPES={CUSTOM_TYPE_TEXT: 'django.forms.widgets.CheckboxInput'}):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel', 'tests.CustomValuesModel')
class SimpleModelWithManagerForm2(builder2.create_modelform(widget_types=settings.CUSTOM_WIDGET_TYPES)):
class Meta:
fields = '__all__'
model = SimpleModelWithManager
form = SimpleModelWithManagerForm2(data={}, instance=self.obj)
self.assertIsNotNone(form.get_widget_for_field(self.cf))
self.assertEqual(django.forms.widgets.CheckboxInput, form.get_widget_for_field(self.cf).__class__)
def test_form(self):
class TestForm(builder.create_modelform()):
custom_name = 'My Custom Fields'
custom_description = 'Edit the Example custom fields here'
custom_classes = 'zzzap-class'
class Meta:
fields = '__all__'
model = SimpleModelWithManager
request = self.factory.post('/', { 'text_field': '123' })
form = TestForm(request.POST, instance=self.obj)
self.assertFalse(form.is_valid())
self.assertIn('another_text_field', form.errors)
self.assertRaises(ValueError, lambda: form.save())
request = self.factory.post('/', { 'id': self.obj.pk,
'name': 'xxx',
'text_field': '000111222333',
'another_text_field': 'wwwzzzyyyxxx' })
form = TestForm(request.POST, instance=self.obj)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(self.obj.get_custom_value(self.cf).value, '000111222333')
self.assertEqual(self.obj.get_custom_value(self.cf2).value, 'wwwzzzyyyxxx')
self.assertEqual(self.obj.name, 'xxx')
request = self.factory.post('/', { 'id': self.obj.pk,
'name': 'aaa',
'another_text_field': 'qqqwwweeerrrtttyyyy'})
form = TestForm(request.POST, instance=self.obj)
self.assertTrue(form.is_valid())
obj = form.save(commit=False)
obj.save()
self.assertEqual(self.obj.get_custom_value(self.cf2).value, 'wwwzzzyyyxxx')
form.save_m2m()
form.save_custom_fields()
self.assertEqual(self.obj.get_custom_value(self.cf2).value, 'qqqwwweeerrrtttyyyy')
self.assertEqual(obj.name, 'aaa')
#self.assertInHTML(TestForm.custom_name, form.as_p())
#self.assertInHTML(TestForm.custom_description, form.as_p())
#self.assertInHTML(TestForm.custom_classes, form.as_p())
def test_admin(self):
modeladmin_class = builder.create_modeladmin()
#c = Client()
#if c.login(username='fred', password='secret'):
# response = c.get('/admin/', follow=True)
# print(response)
|
pombredanne/django-custard
|
custard/tests/test.py
|
Python
|
mit
| 17,657 | 0.003908 |
# BurnMan - a lower mantle toolkit
# Copyright (C) 2012-2014, Myhill, R., Heister, T., Unterborn, C., Rose, I. and Cottaar, S.
# Released under GPL v2 or later.
# This is a standalone program that converts a tabulated version of the Stixrude and Lithgow-Bertelloni data format into the standard burnman format (printed to stdout)
import sys
def read_dataset(datafile):
f=open(datafile,'r')
ds=[]
for line in f:
ds.append(line.decode('utf-8').split())
return ds
ds=read_dataset('HHPH2013_endmembers.dat')
print '# BurnMan - a lower mantle toolkit'
print '# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.'
print '# Released under GPL v2 or later.'
print ''
print '"""'
print 'HHPH_2013'
print 'Minerals from Holland et al 2013 and references therein'
print 'The values in this document are all in S.I. units,'
print 'unlike those in the original paper'
print 'File autogenerated using HHPHdata_to_burnman.py'
print '"""'
print ''
print 'from burnman.mineral import Mineral'
print 'from burnman.solidsolution import SolidSolution'
print 'from burnman.solutionmodel import *'
print 'from burnman.processchemistry import read_masses, dictionarize_formula, formula_mass'
print ''
print 'atomic_masses=read_masses()'
print ''
print '"""'
print 'ENDMEMBERS'
print '"""'
print ''
param_scales = [ -1., -1., #not nubmers, so we won't scale
1.e3, 1.e3, #kJ -> J
1.0, # J/K/mol
1.e-5, # kJ/kbar/mol -> m^3/mol
1.e3, 1.e-2, 1.e3, 1.e3, # kJ -> J and table conversion for b
1.e-5, # table conversion
1.e8, # kbar -> Pa
1.0, # no scale for K'0
1.e-8] #GPa -> Pa # no scale for eta_s
formula='0'
for idx, m in enumerate(ds):
if idx == 0:
param_names=m
else:
print 'class', m[0].lower(), '(Mineral):'
print ' def __init__(self):'
print ''.join([' formula=\'',m[1],'\''])
print ' formula = dictionarize_formula(formula)'
print ' self.params = {'
print ''.join([' \'name\': \'', m[0], '\','])
print ' \'formula\': formula,'
print ' \'equation_of_state\': \'hp_tmt\','
for pid, param in enumerate(m):
if pid > 1 and pid != 3 and pid<6:
print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ','
print ' \'Cp\':', [round(float(m[i])*param_scales[i],10) for i in [6, 7, 8, 9]], ','
for pid, param in enumerate(m):
if pid > 9:
print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ','
print ' \'n\': sum(formula.values()),'
print ' \'molar_mass\': formula_mass(formula, atomic_masses)}'
print ''
print ' self.uncertainties = {'
print ' \''+param_names[3]+'\':', float(m[3])*param_scales[3], '}'
print ' Mineral.__init__(self)'
print ''
|
QuLogic/burnman
|
burnman/data/input_raw_endmember_datasets/HHPH2013data_to_burnman.py
|
Python
|
gpl-2.0
| 3,130 | 0.01246 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/7 17:13
# @Author : Zhiwei Yang
# @File : call_str_repr.py.py
class print_name(object):
def __init__(self,name):
self.name = name
class print_name_pro(object):
def __int__(self,name):
self.name = name
def __str__(self):
return "%s" % self.name
if __name__ == '__main__':
a = print_name("yang")
print (a) # 这样打印不好看,所以请看类B
b = print_name_pro("zhi")
print (b)
|
tencrance/cool-config
|
python_tricks/call_str_repr.py
|
Python
|
mit
| 510 | 0.018595 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Clione Software
# Copyright (c) 2010-2013 Cidadania S. Coop. Galega
#
# 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 datetime import datetime
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from core.spaces.file_validation import ContentTypeRestrictedFileField
from fields import StdImageField
from allowed_types import ALLOWED_CONTENT_TYPES
class Space(models.Model):
"""
Spaces model. This model stores a "space" or "place" also known as a
participative process in reality. Every place has a minimum set of
settings for customization.
There are three main permission roles in every space: administrator
(admins), moderators (mods) and regular users (users).
"""
name = models.CharField(_('Name'), max_length=250, unique=True,
help_text=_('Max: 250 characters'))
url = models.CharField(_('URL'), max_length=100, unique=True,
validators=[RegexValidator(regex='^[a-z0-9_]+$',
message='Invalid characters in the space URL.')],
help_text=_('Valid characters are lowercase, digits and \
underscore. This will be the accesible URL'))
description = models.TextField(_('Description'),
default=_('Write here your description.'))
pub_date = models.DateTimeField(_('Date of creation'), auto_now_add=True)
author = models.ForeignKey(User, blank=True, null=True,
verbose_name=_('Space creator'), help_text=_('Select a user that \
will be marked as creator of the space'))
logo = StdImageField(upload_to='spaces/logos', size=(100, 75, False),
help_text = _('Valid extensions are jpg, jpeg, png and gif'))
banner = StdImageField(upload_to='spaces/banners', size=(500, 75, False),
help_text = _('Valid extensions are jpg, jpeg, png and gif'))
public = models.BooleanField(_('Public space'), help_text=_("This will \
make the space visible to everyone, but registration will be \
necessary to participate."))
# Modules
mod_debate = models.BooleanField(_('Debate'))
mod_proposals = models.BooleanField(_('Proposals'))
mod_news = models.BooleanField(_('News'))
mod_cal = models.BooleanField(_('Calendar'))
mod_docs = models.BooleanField(_('Documents'))
mod_voting = models.BooleanField(_('Voting'))
class Meta:
ordering = ['name']
verbose_name = _('Space')
verbose_name_plural = _('Spaces')
get_latest_by = 'pub_date'
permissions = (
('view_space', 'Can view this space.'),
('admin_space', 'Can administrate this space.'),
('mod_space', 'Can moderate this space.')
)
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('space-index', (), {
'space_url': self.url})
class Entity(models.Model):
"""
This model stores the name of the entities responsible for the creation
of the space or supporting it.
"""
name = models.CharField(_('Name'), max_length=100, unique=True)
website = models.CharField(_('Website'), max_length=100, null=True,
blank=True)
logo = models.ImageField(upload_to='spaces/logos', verbose_name=_('Logo'),
blank=True, null=True)
space = models.ForeignKey(Space, blank=True, null=True)
class Meta:
ordering = ['name']
verbose_name = _('Entity')
verbose_name_plural = _('Entities')
def __unicode__(self):
return self.name
class Document(models.Model):
"""
This models stores documents for the space, like a document repository,
There is no restriction in what a user can upload to the space.
:methods: get_file_ext, get_file_size
"""
title = models.CharField(_('Document title'), max_length=100,
help_text=_('Max: 100 characters'))
space = models.ForeignKey(Space, blank=True, null=True,
help_text=_('Change the space to whom belongs this document'))
docfile = ContentTypeRestrictedFileField(_('File'),
upload_to='spaces/documents/%Y/%m/%d',
content_types=ALLOWED_CONTENT_TYPES,
max_upload_size=26214400,
help_text=_('Permitted file types: DOC, DOCX, PPT, ODT, ODF, ODP, \
PDF, RST, TXT.'))
pub_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, verbose_name=_('Author'), blank=True,
null=True, help_text=_('Change the user that will figure as the \
author'))
def get_file_ext(self):
filename = self.docfile.name
extension = filename.split('.')
return extension[1].upper()
def get_file_size(self):
if self.docfile.size < 1023:
return str(self.docfile.size) + " Bytes"
elif self.docfile.size >= 1024 and self.docfile.size <= 1048575:
return str(round(self.docfile.size / 1024.0, 2)) + " KB"
elif self.docfile.size >= 1048576:
return str(round(self.docfile.size / 1024000.0, 2)) + " MB"
class Meta:
ordering = ['pub_date']
verbose_name = _('Document')
verbose_name_plural = _('Documents')
get_latest_by = 'pub_date'
# There is no 'view-document' view, so I'll leave the get_absolute_url
# method without permalink. Remember that the document files are accesed
# through the url() method in templates.
def get_absolute_url(self):
return '/spaces/%s/docs/%s' % (self.space.url, self.id)
class Event(models.Model):
"""
Meeting data model. Every space (process) has N meetings. This will
keep record of the assistants, meeting name, etc.
"""
title = models.CharField(_('Event name'), max_length=250,
help_text="Max: 250 characters")
space = models.ForeignKey(Space, blank=True, null=True)
user = models.ManyToManyField(User, verbose_name=_('Users'),
help_text=_('List of the users that will assist or assisted to the \
event.'))
pub_date = models.DateTimeField(auto_now_add=True)
event_author = models.ForeignKey(User, verbose_name=_('Created by'),
blank=True, null=True, related_name='meeting_author',
help_text=_('Select the user that will be designated as author.'))
event_date = models.DateTimeField(verbose_name=_('Event date'),
help_text=_('Select the date where the event is celebrated.'))
description = models.TextField(_('Description'), blank=True, null=True)
location = models.TextField(_('Location'), blank=True, null=True)
latitude = models.DecimalField(_('Latitude'), blank=True, null=True,
max_digits=17, decimal_places=15, help_text=_('Specify it in decimal'))
longitude = models.DecimalField(_('Longitude'), blank=True, null=True,
max_digits=17, decimal_places=15, help_text=_('Specify it in decimal'))
def is_due(self):
if self.event_date < datetime.now():
return True
else:
return False
class Meta:
ordering = ['event_date']
verbose_name = _('Event')
verbose_name_plural = _('Events')
get_latest_by = 'event_date'
permissions = (
('view_event', 'Can view this event'),
('admin_event', 'Can administrate this event'),
('mod_event', 'Can moderate this event'),
)
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('view-event', (), {
'space_url': self.space.url,
'event_id': str(self.id)})
class Intent(models.Model):
"""
Intent data model. Intent stores the reference of a user-token when a user
asks entering in a restricted space.
.. versionadded: 0.1.5
"""
user = models.ForeignKey(User)
space = models.ForeignKey(Space)
token = models.CharField(max_length=32)
requested_on = models.DateTimeField(auto_now_add=True)
def get_approve_url(self):
site = Site.objects.all()[0]
return "http://%s%sintent/approve/%s" % (site.domain, self.space.get_absolute_url(), self.token)
|
cidadania/e-cidadania
|
src/core/spaces/models.py
|
Python
|
apache-2.0
| 8,796 | 0.003183 |
# Copyright 2014-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
# 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.
"""
Resource class and its manager for volume backup on Block Storage V2 API
"""
from osclient2 import base
from osclient2 import mapper
from . import volume_transfer
ATTRIBUTE_MAPPING = [
('id', 'id', mapper.Noop),
('name', 'display_name', mapper.Noop),
('description', 'description', mapper.Noop),
('availability_zone', 'availability_zone',
mapper.Resource('availability_zone')),
('source_volume', 'volume_id', mapper.Resource('cinder.volume')),
('size', 'size', mapper.Noop),
('object_count', 'object_count', mapper.Noop),
('container', 'container', mapper.Noop),
('created_at', 'created_at', mapper.DateTime),
('updated_at', 'updated_at', mapper.DateTime),
('status', 'status', mapper.Noop),
('fail_reason', 'fail_reason', mapper.Noop),
('has_dependent_backups', 'has_dependent_backups', mapper.Noop),
('is_incremental', 'incremental', mapper.Noop),
('is_incremental', 'is_incremental', mapper.Noop),
]
class Resource(base.Resource):
"""resource class for volume backups on Block Storage V2 API"""
_stable_state = ['available', 'error', 'error_deleting']
def restore(self, volume=None, transfer=None):
"""
Restore a volume from a volume backup
@keyword volume: Destination volume
@type volume: osclient2.cinder.v2.volume.Resource
@keyword transfer: Volume transfer
@type transfer: osclient2.cinder.v2.volume_transfer.Resource
@rtype: None
"""
transfer_name = None
if isinstance(transfer, volume_transfer.Resource):
transfer_name = transfer.name
self._http.post(self._url_resource_path, self._id, 'restore',
data=utils.get_json_body("restore",
volume=volume.get_id(),
name=transfer_name))
def delete(self, force=False):
"""
Delete a volume backup
@keyword force: Whether the deletion is forced
@type force: bool
@rtype: None
"""
if not force:
super(Resource. self).delete()
return
self._http.post(self._url_resource_path, self._id, 'action',
data=utils.get_json_body("os-force_delete"))
class Manager(base.Manager):
"""manager class for volume backups on Block Storage V2 API"""
resource_class = Resource
service_type = 'volume'
_attr_mapping = ATTRIBUTE_MAPPING
_json_resource_key = 'backup'
_json_resources_key = 'backups'
_hidden_methods = ["update"]
_url_resource_list_path = '/backups/detail'
_url_resource_path = '/backups'
def create(self, name=None, description=None, source_volume=None,
container=None, is_incremental=False):
"""
Create a backup of a volume
@keyword name: Snapshot name
@type name: str
@keyword description: Description
@type description: str
@keyword source_volume: Source volume
@type source_volume: osclient2.cinder.v2.volume.Resource
@keyword container: Container for store a volume backup
@type source_volume: str
@keyword is_incremental: Whether the backup is incremental
@type is_incremental: bool
@return: Created volume object
@rtype: osclient2.cinder.v2.snapshot.Resource
"""
return super(Manager, self).create(name=name,
description=description,
source_volume=source_volume,
container=container,
is_incremental=is_incremental)
|
yosshy/osclient2
|
osclient2/cinder/v2/volume_backup.py
|
Python
|
apache-2.0
| 4,420 | 0 |
"""
Example: parse JSON.
"""
from peglet import Parser, hug, join, attempt
literals = dict(true=True,
false=False,
null=None)
mk_literal = literals.get
mk_object = lambda *pairs: dict(pairs)
escape = lambda s: s.decode('unicode-escape')
mk_number = float
# Following http://www.json.org/
json_parse = Parser(r"""
start = _ value
object = { _ members } _ mk_object
| { _ } _ mk_object
members = pair , _ members
| pair
pair = string : _ value hug
array = \[ _ elements \] _ hug
| \[ _ \] _ hug
elements = value , _ elements
| value
value = string | number
| object | array
| (true|false|null)\b _ mk_literal
string = " chars " _ join
chars = char chars
|
char = ([^\x00-\x1f"\\])
| \\(["/\\])
| (\\[bfnrt]) escape
| (\\u) xd xd xd xd join escape
xd = ([0-9a-fA-F])
number = int frac exp _ join mk_number
| int frac _ join mk_number
| int exp _ join mk_number
| int _ join mk_number
int = (-?) (0) !\d
| (-?) ([1-9]\d*)
frac = ([.]\d+)
exp = ([eE][+-]?\d+)
_ = \s*
""", **globals())
# XXX The spec says "whitespace may be inserted between any pair of
# tokens, but leaves open just what's a token. So is the '-' in '-1' a
# token? Should I allow whitespace there?
## json_parse('[1,1]')
#. ((1.0, 1.0),)
## json_parse('true')
#. (True,)
## json_parse(r'"hey \b\n \u01ab o hai"')
#. (u'hey \x08\n \u01ab o hai',)
## json_parse('{"hey": true}')
#. ({'hey': True},)
## json_parse('[{"hey": true}]')
#. (({'hey': True},),)
## json_parse('[{"hey": true}, [-12.34]]')
#. (({'hey': True}, (-12.34,)),)
## json_parse('0')
#. (0.0,)
## json_parse('0.125e-2')
#. (0.00125,)
## attempt(json_parse, '0377')
## attempt(json_parse, '{"hi"]')
# Udacity CS212 problem 3.1:
## json_parse('["testing", 1, 2, 3]')
#. (('testing', 1.0, 2.0, 3.0),)
## json_parse('-123.456e+789')
#. (-inf,)
## json_parse('{"age": 21, "state":"CO","occupation":"rides the rodeo"}')
#. ({'age': 21.0, 'state': 'CO', 'occupation': 'rides the rodeo'},)
|
JaDogg/__py_playground
|
reference/peglet/examples/json.py
|
Python
|
mit
| 2,243 | 0.012929 |
# -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import sys
import datetime
from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT
from core.transmissionrpc.utils import Field, format_timedelta
from six import integer_types, string_types, text_type, iteritems
def get_status_old(code):
"""Get the torrent status using old status codes"""
mapping = {
(1 << 0): 'check pending',
(1 << 1): 'checking',
(1 << 2): 'downloading',
(1 << 3): 'seeding',
(1 << 4): 'stopped',
}
return mapping[code]
def get_status_new(code):
"""Get the torrent status using new status codes"""
mapping = {
0: 'stopped',
1: 'check pending',
2: 'checking',
3: 'download pending',
4: 'downloading',
5: 'seed pending',
6: 'seeding',
}
return mapping[code]
class Torrent(object):
"""
Torrent is a class holding the data received from Transmission regarding a bittorrent transfer.
All fetched torrent fields are accessible through this class using attributes.
This class has a few convenience properties using the torrent data.
"""
def __init__(self, client, fields):
if 'id' not in fields:
raise ValueError('Torrent requires an id')
self._fields = {}
self._update_fields(fields)
self._incoming_pending = False
self._outgoing_pending = False
self._client = client
def _get_name_string(self, codec=None):
"""Get the name"""
if codec is None:
codec = sys.getdefaultencoding()
name = None
# try to find name
if 'name' in self._fields:
name = self._fields['name'].value
# if name is unicode, try to decode
if isinstance(name, text_type):
try:
name = name.encode(codec)
except UnicodeError:
name = None
return name
def __repr__(self):
tid = self._fields['id'].value
name = self._get_name_string()
if isinstance(name, str):
return '<Torrent {0:d} \"{1}\">'.format(tid, name)
else:
return '<Torrent {0:d}>'.format(tid)
def __str__(self):
name = self._get_name_string()
if isinstance(name, str):
return 'Torrent \"{0}\"'.format(name)
else:
return 'Torrent'
def __copy__(self):
return Torrent(self._client, self._fields)
def __getattr__(self, name):
try:
return self._fields[name].value
except KeyError:
raise AttributeError('No attribute {0}'.format(name))
def _rpc_version(self):
"""Get the Transmission RPC API version."""
if self._client:
return self._client.rpc_version
return 2
def _dirty_fields(self):
"""Enumerate changed fields"""
outgoing_keys = ['bandwidthPriority', 'downloadLimit', 'downloadLimited', 'peer_limit', 'queuePosition',
'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'uploadLimit',
'uploadLimited']
fields = []
for key in outgoing_keys:
if key in self._fields and self._fields[key].dirty:
fields.append(key)
return fields
def _push(self):
"""Push changed fields to the server"""
dirty = self._dirty_fields()
args = {}
for key in dirty:
args[key] = self._fields[key].value
self._fields[key] = self._fields[key]._replace(dirty=False)
if len(args) > 0:
self._client.change_torrent(self.id, **args)
def _update_fields(self, other):
"""
Update the torrent data from a Transmission JSON-RPC arguments dictionary
"""
if isinstance(other, dict):
for key, value in iteritems(other):
self._fields[key.replace('-', '_')] = Field(value, False)
elif isinstance(other, Torrent):
for key in list(other._fields.keys()):
self._fields[key] = Field(other._fields[key].value, False)
else:
raise ValueError('Cannot update with supplied data')
self._incoming_pending = False
def _status(self):
"""Get the torrent status"""
code = self._fields['status'].value
if self._rpc_version() >= 14:
return get_status_new(code)
else:
return get_status_old(code)
def files(self):
"""
Get list of files for this torrent.
This function returns a dictionary with file information for each file.
The file information is has following fields:
::
{
<file id>: {
'name': <file name>,
'size': <file size in bytes>,
'completed': <bytes completed>,
'priority': <priority ('high'|'normal'|'low')>,
'selected': <selected for download>
}
...
}
"""
result = {}
if 'files' in self._fields:
files = self._fields['files'].value
indices = range(len(files))
priorities = self._fields['priorities'].value
wanted = self._fields['wanted'].value
for item in zip(indices, files, priorities, wanted):
selected = True if item[3] else False
priority = PRIORITY[item[2]]
result[item[0]] = {
'selected': selected,
'priority': priority,
'size': item[1]['length'],
'name': item[1]['name'],
'completed': item[1]['bytesCompleted']}
return result
@property
def status(self):
"""
Returns the torrent status. Is either one of 'check pending', 'checking',
'downloading', 'seeding' or 'stopped'. The first two is related to
verification.
"""
return self._status()
@property
def progress(self):
"""Get the download progress in percent."""
try:
size = self._fields['sizeWhenDone'].value
left = self._fields['leftUntilDone'].value
return 100.0 * (size - left) / float(size)
except ZeroDivisionError:
return 0.0
@property
def ratio(self):
"""Get the upload/download ratio."""
return float(self._fields['uploadRatio'].value)
@property
def eta(self):
"""Get the "eta" as datetime.timedelta."""
eta = self._fields['eta'].value
if eta >= 0:
return datetime.timedelta(seconds=eta)
else:
raise ValueError('eta not valid')
@property
def date_active(self):
"""Get the attribute "activityDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['activityDate'].value)
@property
def date_added(self):
"""Get the attribute "addedDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['addedDate'].value)
@property
def date_started(self):
"""Get the attribute "startDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['startDate'].value)
@property
def date_done(self):
"""Get the attribute "doneDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['doneDate'].value)
def format_eta(self):
"""
Returns the attribute *eta* formatted as a string.
* If eta is -1 the result is 'not available'
* If eta is -2 the result is 'unknown'
* Otherwise eta is formatted as <days> <hours>:<minutes>:<seconds>.
"""
eta = self._fields['eta'].value
if eta == -1:
return 'not available'
elif eta == -2:
return 'unknown'
else:
return format_timedelta(self.eta)
def _get_download_limit(self):
"""
Get the download limit.
Can be a number or None.
"""
if self._fields['downloadLimited'].value:
return self._fields['downloadLimit'].value
else:
return None
def _set_download_limit(self, limit):
"""
Get the download limit.
Can be a number, 'session' or None.
"""
if isinstance(limit, integer_types):
self._fields['downloadLimited'] = Field(True, True)
self._fields['downloadLimit'] = Field(limit, True)
self._push()
elif limit is None:
self._fields['downloadLimited'] = Field(False, True)
self._push()
else:
raise ValueError("Not a valid limit")
download_limit = property(_get_download_limit, _set_download_limit, None,
"Download limit in Kbps or None. This is a mutator.")
def _get_peer_limit(self):
"""
Get the peer limit.
"""
return self._fields['peer_limit'].value
def _set_peer_limit(self, limit):
"""
Set the peer limit.
"""
if isinstance(limit, integer_types):
self._fields['peer_limit'] = Field(limit, True)
self._push()
else:
raise ValueError("Not a valid limit")
peer_limit = property(_get_peer_limit, _set_peer_limit, None, "Peer limit. This is a mutator.")
def _get_priority(self):
"""
Get the priority as string.
Can be one of 'low', 'normal', 'high'.
"""
return PRIORITY[self._fields['bandwidthPriority'].value]
def _set_priority(self, priority):
"""
Set the priority as string.
Can be one of 'low', 'normal', 'high'.
"""
if isinstance(priority, string_types):
self._fields['bandwidthPriority'] = Field(PRIORITY[priority], True)
self._push()
priority = property(_get_priority, _set_priority, None
, "Bandwidth priority as string. Can be one of 'low', 'normal', 'high'. This is a mutator.")
def _get_seed_idle_limit(self):
"""
Get the seed idle limit in minutes.
"""
return self._fields['seedIdleLimit'].value
def _set_seed_idle_limit(self, limit):
"""
Set the seed idle limit in minutes.
"""
if isinstance(limit, integer_types):
self._fields['seedIdleLimit'] = Field(limit, True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_idle_limit = property(_get_seed_idle_limit, _set_seed_idle_limit, None
, "Torrent seed idle limit in minutes. Also see seed_idle_mode. This is a mutator.")
def _get_seed_idle_mode(self):
"""
Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
return IDLE_LIMIT[self._fields['seedIdleMode'].value]
def _set_seed_idle_mode(self, mode):
"""
Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
if isinstance(mode, str):
self._fields['seedIdleMode'] = Field(IDLE_LIMIT[mode], True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_idle_mode = property(_get_seed_idle_mode, _set_seed_idle_mode, None,
"""
Seed idle mode as string. Can be one of 'global', 'single' or 'unlimited'.
* global, use session seed idle limit.
* single, use torrent seed idle limit. See seed_idle_limit.
* unlimited, no seed idle limit.
This is a mutator.
"""
)
def _get_seed_ratio_limit(self):
"""
Get the seed ratio limit as float.
"""
return float(self._fields['seedRatioLimit'].value)
def _set_seed_ratio_limit(self, limit):
"""
Set the seed ratio limit as float.
"""
if isinstance(limit, (integer_types, float)) and limit >= 0.0:
self._fields['seedRatioLimit'] = Field(float(limit), True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_ratio_limit = property(_get_seed_ratio_limit, _set_seed_ratio_limit, None
, "Torrent seed ratio limit as float. Also see seed_ratio_mode. This is a mutator.")
def _get_seed_ratio_mode(self):
"""
Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
return RATIO_LIMIT[self._fields['seedRatioMode'].value]
def _set_seed_ratio_mode(self, mode):
"""
Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
if isinstance(mode, str):
self._fields['seedRatioMode'] = Field(RATIO_LIMIT[mode], True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_ratio_mode = property(_get_seed_ratio_mode, _set_seed_ratio_mode, None,
"""
Seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
* global, use session seed ratio limit.
* single, use torrent seed ratio limit. See seed_ratio_limit.
* unlimited, no seed ratio limit.
This is a mutator.
"""
)
def _get_upload_limit(self):
"""
Get the upload limit.
Can be a number or None.
"""
if self._fields['uploadLimited'].value:
return self._fields['uploadLimit'].value
else:
return None
def _set_upload_limit(self, limit):
"""
Set the upload limit.
Can be a number, 'session' or None.
"""
if isinstance(limit, integer_types):
self._fields['uploadLimited'] = Field(True, True)
self._fields['uploadLimit'] = Field(limit, True)
self._push()
elif limit is None:
self._fields['uploadLimited'] = Field(False, True)
self._push()
else:
raise ValueError("Not a valid limit")
upload_limit = property(_get_upload_limit, _set_upload_limit, None,
"Upload limit in Kbps or None. This is a mutator.")
def _get_queue_position(self):
"""Get the queue position for this torrent."""
if self._rpc_version() >= 14:
return self._fields['queuePosition'].value
else:
return 0
def _set_queue_position(self, position):
"""Set the queue position for this torrent."""
if self._rpc_version() >= 14:
if isinstance(position, integer_types):
self._fields['queuePosition'] = Field(position, True)
self._push()
else:
raise ValueError("Not a valid position")
else:
pass
queue_position = property(_get_queue_position, _set_queue_position, None, "Queue position")
def update(self, timeout=None):
"""Update the torrent information."""
self._push()
torrent = self._client.get_torrent(self.id, timeout=timeout)
self._update_fields(torrent)
def start(self, bypass_queue=False, timeout=None):
"""
Start the torrent.
"""
self._incoming_pending = True
self._client.start_torrent(self.id, bypass_queue=bypass_queue, timeout=timeout)
def stop(self, timeout=None):
"""Stop the torrent."""
self._incoming_pending = True
self._client.stop_torrent(self.id, timeout=timeout)
def move_data(self, location, timeout=None):
"""Move torrent data to location."""
self._incoming_pending = True
self._client.move_torrent_data(self.id, location, timeout=timeout)
def locate_data(self, location, timeout=None):
"""Locate torrent data at location."""
self._incoming_pending = True
self._client.locate_torrent_data(self.id, location, timeout=timeout)
|
bbsan2k/nzbToMedia
|
core/transmissionrpc/torrent.py
|
Python
|
gpl-3.0
| 16,349 | 0.001529 |
import array
import itertools
import logging
import multiprocessing
import numpy
import scipy.sparse
import sharedmem
import sppy
import time
from sandbox.misc.RandomisedSVD import RandomisedSVD
from sandbox.recommendation.AbstractRecommender import AbstractRecommender
from sandbox.recommendation.IterativeSoftImpute import IterativeSoftImpute
from sandbox.recommendation.MaxAUCTanh import MaxAUCTanh
from sandbox.recommendation.MaxAUCHinge import MaxAUCHinge
from sandbox.recommendation.MaxAUCSquare import MaxAUCSquare
from sandbox.recommendation.MaxAUCLogistic import MaxAUCLogistic
from sandbox.recommendation.MaxAUCSigmoid import MaxAUCSigmoid
from sandbox.recommendation.RecommenderUtils import computeTestMRR, computeTestF1
from sandbox.recommendation.WeightedMf import WeightedMf
from sandbox.util.MCEvaluatorCython import MCEvaluatorCython
from sandbox.util.MCEvaluator import MCEvaluator
from sandbox.util.Sampling import Sampling
from sandbox.util.SparseUtilsCython import SparseUtilsCython
from sandbox.util.SparseUtils import SparseUtils
from sklearn.grid_search import ParameterGrid
def computeObjective(args):
"""
Compute the objective for a particular parameter set. Used to set a learning rate.
"""
X, testX, maxLocalAuc = args
U, V, trainMeasures, testMeasures, iterations, totalTime = maxLocalAuc.singleLearnModel(X, verbose=True)
obj = trainMeasures[-1, 0]
logging.debug("Final objective: " + str(obj) + " with t0=" + str(maxLocalAuc.t0) + " and alpha=" + str(maxLocalAuc.alpha))
return obj
def updateUVBlock(sharedArgs, methodArgs):
"""
Compute the objective for a particular parameter set. Used to set a learning rate.
"""
rowIsFree, colIsFree, iterationsPerBlock, gradientsPerBlock, U, V, muU, muV, lock = sharedArgs
learner, rowBlockSize, colBlockSize, indPtr, colInds, permutedRowInds, permutedColInds, gi, gp, gq, normGp, normGq, pid, loopInd, omegasList = methodArgs
while (iterationsPerBlock < learner.parallelStep).any():
#Find free block
lock.acquire()
inds = numpy.argsort(numpy.ravel(iterationsPerBlock))
foundBlock = False
#Find the block with smallest number of updates which is free
for i in inds:
rowInd, colInd = numpy.unravel_index(i, iterationsPerBlock.shape)
if rowIsFree[rowInd] and colIsFree[colInd]:
rowIsFree[rowInd] = False
colIsFree[colInd] = False
foundBlock = True
break
blockRowInds = permutedRowInds[rowInd*rowBlockSize:(rowInd+1)*rowBlockSize]
blockColInds = permutedColInds[colInd*colBlockSize:(colInd+1)*colBlockSize]
ind = iterationsPerBlock[rowInd, colInd] + loopInd
sigmaU = learner.getSigma(ind, learner.alpha, muU.shape[0])
sigmaV = learner.getSigma(ind, learner.alpha, muU.shape[0])
lock.release()
#Now update U and V based on the block
if foundBlock:
ind = iterationsPerBlock[rowInd, colInd] + loopInd
sigmaU = learner.getSigma(ind, learner.alpha, muU.shape[0])
sigmaV = learner.getSigma(ind, learner.alpha, muU.shape[0])
numIterations = gradientsPerBlock[rowInd, colInd]
indPtr2, colInds2 = omegasList[colInd]
learner.updateUV(indPtr2, colInds2, U, V, muU, muV, blockRowInds, blockColInds, gp, gq, normGp, normGq, ind, sigmaU, sigmaV, numIterations)
else:
time.sleep(3)
lock.acquire()
if foundBlock:
rowIsFree[rowInd] = True
colIsFree[colInd] = True
iterationsPerBlock[rowInd, colInd] += 1
lock.release()
def restrictOmega(indPtr, colInds, colIndsSubset):
"""
Take a set of nonzero indices for a matrix and restrict the columns to colIndsSubset.
"""
m = indPtr.shape[0]-1
newIndPtr = numpy.zeros(indPtr.shape[0], indPtr.dtype)
newColInds = array.array("I")
colIndsSubset = numpy.array(colIndsSubset, numpy.int)
ptr = 0
for i in range(m):
omegai = numpy.array(colInds[indPtr[i]:indPtr[i+1]], numpy.int)
#newOmegai = numpy.intersect1d(omegai, colIndsSubset, assume_unique=True)
#This way is 60% faster
total = numpy.concatenate((omegai, colIndsSubset))
counts = numpy.bincount(total)
newOmegai = numpy.where(counts>1)[0]
newIndPtr[i] = ptr
newIndPtr[i+1] = ptr + newOmegai.shape[0]
newColInds.extend(newOmegai)
ptr += newOmegai.shape[0]
newColInds = numpy.array(newColInds, dtype=colInds.dtype)
return newIndPtr, newColInds
class MaxLocalAUC(AbstractRecommender):
def __init__(self, k, w=0.9, alpha=0.05, eps=10**-6, lmbdaU=0.1, lmbdaV=0.1, maxIterations=50, stochastic=False, numProcesses=None):
"""
Create an object for maximising the local AUC with a penalty term using the matrix
decomposition UV.T
:param k: The rank of matrices U and V
:param w: The quantile for the local AUC - e.g. 1 means takes the largest value, 0.7 means take the top 0.3
:param alpha: The (initial) learning rate
:param eps: The termination threshold for ||dU|| and ||dV||
:param lmbda: The regularistion penalty for V
:stochastic: Whether to use stochastic gradient descent or gradient descent
"""
super(MaxLocalAUC, self).__init__(numProcesses)
self.alpha = alpha #Initial learning rate
self.beta = 0.75
self.bound = False
self.delta = 0.05
self.eps = eps
self.eta = 5
self.folds = 2
self.initialAlg = "rand"
self.itemExpP = 0.0 #Sample from power law between 0 and 1
self.itemExpQ = 0.0
self.k = k
self.lmbda = (lmbdaU+lmbdaV)/2
self.maxIterations = maxIterations
self.maxNormU = 100
self.maxNormV = 100
self.maxNorms = 2.0**numpy.arange(0, 8)
self.metric = "f1"
self.normalise = True
self.numAucSamples = 10
self.numRecordAucSamples = 100
self.numRowSamples = 30
self.numRuns = 200
self.loss = "hinge"
self.p = 10
self.parallelSGD = False
self.parallelStep = 1 #Number of iterations for each parallel updateUV (smaller gives better convergence)
self.printStep = 10000
self.q = 3
self.rate = "constant"
self.recordStep = 10
self.reg = True
self.rho = 1.0
self.scaleAlpha = True
self.startAverage = 30
self.stochastic = stochastic
self.t0 = 0.1 #Convergence speed - larger means we get to 0 faster
self.validationUsers = 0.1
self.w = w
#Model selection parameters
self.ks = 2**numpy.arange(3, 8)
self.lmbdas = 2.0**-numpy.arange(1, 7)
self.rhos = numpy.array([0, 0.1, 0.5, 1.0])
self.itemExps = numpy.array([0, 0.25, 0.5, 0.75, 1.0])
#Learning rate selection
self.alphas = 2.0**-numpy.arange(1, 7)
self.t0s = 2.0**-numpy.arange(0.0, 5.0)
def __str__(self):
outputStr = "MaxLocalAUC: "
attributes = vars(self)
for key, item in sorted(attributes.iteritems()):
if isinstance(item, int) or isinstance(item, float) or isinstance(item, str) or isinstance(item, bool):
outputStr += key + "=" + str(item) + " "
return outputStr
def computeBound(self, X, U, V, trainExp, delta):
"""
Compute a lower bound on the expectation of the loss based on Rademacher
theory.
"""
m, n = X.shape
Ru = numpy.linalg.norm(U)
Rv = numpy.linalg.norm(V)
X = X.toarray()
Xs = X.sum(1)
E = (X.T / Xs).T
EBar = numpy.ones(X.shape) - X
EBar = (EBar.T / (EBar.sum(1))).T
P, sigmaM, Q = numpy.linalg.svd(E - EBar)
sigma1 = numpy.max(sigmaM)
omegaSum = 0
for i in range(m):
omegaSum += 1.0/(Xs[i] * (n-Xs[i])**2)
if self.loss in ["hinge", "square"]:
B = 4
elif self.loss in ["logistic", "sigmoid"]:
B = 1
else:
raise ValueError("Unsupported loss: " + self.loss)
rademacherTerm = 2*B*Ru*Rv*sigma1/m + numpy.sqrt((2*numpy.log(1/delta)*(n-1)**2/m**2) * omegaSum)
secondTerm = numpy.sqrt((numpy.log(1/delta)*(n-1)**2/(2*m**2)) * omegaSum)
expectationBound = trainExp + rademacherTerm + secondTerm
#print(B,Ru,Rv,m,sigma1 )
#print(trainExp, rademacherTerm, secondTerm)
return expectationBound
def computeGipq(self, X):
m, n = X.shape
gi = numpy.ones(m)/float(m)
itemProbs = (X.sum(0)+1)/float(m+1)
gp = itemProbs**self.itemExpP
gp /= gp.sum()
gq = (1-itemProbs)**self.itemExpQ
gq /= gq.sum()
return gi, gp, gq
def computeNormGpq(self, indPtr, colInds, gp, gq, m):
normGp = numpy.zeros(m)
normGq = numpy.zeros(m)
gqSum = gq.sum()
for i in range(m):
omegai = colInds[indPtr[i]:indPtr[i+1]]
normGp[i] = gp[omegai].sum()
normGq[i] = gqSum - gq[omegai].sum()
return normGp, normGq
def copy(self):
maxLocalAuc = MaxLocalAUC(k=self.k, w=self.w, lmbdaU=self.lmbdaU, lmbdaV=self.lmbdaV)
self.copyParams(maxLocalAuc)
maxLocalAuc.__dict__.update(self.__dict__)
return maxLocalAuc
def getCythonLearner(self):
if self.loss == "tanh":
learnerCython = MaxAUCTanh(self.k, self.lmbdaU, self.lmbdaV, self.normalise, self.numAucSamples, self.numRowSamples, self.startAverage, self.rho)
elif self.loss == "hinge":
learnerCython = MaxAUCHinge(self.k, self.lmbdaU, self.lmbdaV, self.normalise, self.numAucSamples, self.numRowSamples, self.startAverage, self.rho)
elif self.loss == "square":
learnerCython = MaxAUCSquare(self.k, self.lmbdaU, self.lmbdaV, self.normalise, self.numAucSamples, self.numRowSamples, self.startAverage, self.rho)
elif self.loss == "logistic":
learnerCython = MaxAUCLogistic(self.k, self.lmbdaU, self.lmbdaV, self.normalise, self.numAucSamples, self.numRowSamples, self.startAverage, self.rho)
elif self.loss == "sigmoid":
learnerCython = MaxAUCSigmoid(self.k, self.lmbdaU, self.lmbdaV, self.normalise, self.numAucSamples, self.numRowSamples, self.startAverage, self.rho)
else:
raise ValueError("Unknown objective: " + self.loss)
learnerCython.eta = self.eta
learnerCython.printStep = self.printStep
learnerCython.maxNormU = self.maxNormU
learnerCython.maxNormV = self.maxNormV
return learnerCython
def getEvaluationMethod(self):
if self.metric == "mrr":
evaluationMethod = computeTestMRR
elif self.metric == "f1":
evaluationMethod = computeTestF1
else:
raise ValueError("Invalid metric: " + self.metric)
return evaluationMethod
def getLmbdaU(self):
return self.lmbda
def getLmbdaV(self):
return self.lmbda
def getSigma(self, ind, alpha, scale):
if self.rate == "constant":
sigma = alpha
elif self.rate == "optimal":
t0 = self.t0
sigma = alpha/((1 + alpha*t0*ind)**self.beta)
else:
raise ValueError("Invalid rate: " + self.rate)
#Note that scaling by m is a bad idea
if self.scaleAlpha:
sigma *= 10**3
return sigma
def initUV(self, X):
m = X.shape[0]
n = X.shape[1]
if self.initialAlg == "rand":
U = numpy.random.randn(m, self.k)*0.1
V = numpy.random.randn(n, self.k)*0.1
elif self.initialAlg == "svd":
logging.debug("Initialising with Randomised SVD")
U, s, V = RandomisedSVD.svd(X, self.k, self.p, self.q)
U = U*s
elif self.initialAlg == "softimpute":
logging.debug("Initialising with softimpute")
trainIterator = iter([X.toScipyCsc()])
rho = 0.01
learner = IterativeSoftImpute(rho, k=self.k, svdAlg="propack", postProcess=True)
ZList = learner.learnModel(trainIterator)
U, s, V = ZList.next()
U = U*s
elif self.initialAlg == "wrmf":
logging.debug("Initialising with wrmf")
learner = WeightedMf(self.k, w=self.w)
U, V = learner.learnModel(X.toScipyCsr())
else:
raise ValueError("Unknown initialisation: " + str(self.initialAlg))
U = numpy.ascontiguousarray(U)
V = numpy.ascontiguousarray(V)
return U, V
def learnModel(self, X, verbose=False, U=None, V=None, randSeed=None):
if randSeed != None:
logging.warn("Seeding random number generator")
numpy.random.seed(randSeed)
if self.parallelSGD:
return self.parallelLearnModel(X, verbose, U, V)
else:
return self.singleLearnModel(X, verbose, U, V)
def learningRateSelect(self, X=None, meanMetrics=None):
"""
Let's set the initial learning rate.
"""
evaluationMethod = computeObjective
if self.rate == "optimal":
paramDict = {"t0": self.t0s, "alpha": self.alphas}
else:
paramDict = {"alpha": self.alphas}
if meanMetrics == None:
meanMetrics = self.parallelGridSearch(X, paramDict, evaluationMethod, minVal=True)
else:
resultDict, bestMetric = self.setBestLearner(meanMetrics, paramDict, minVal=True)
return meanMetrics, paramDict
def modelParamsStr(self):
outputStr = " lmbdaU=" + str(self.lmbdaU) + " lmbdaV=" + str(self.lmbdaV) + " maxNormU=" + str(self.maxNormU) + " maxNormV=" + str(self.maxNormV) + " k=" + str(self.k) + " rho=" + str(self.rho) + " alpha=" + str(self.alpha) + " t0=" + str(self.t0)
return outputStr
def modelSelectNorm(self, X=None, testX=None, meanMetrics=None):
"""
Perform model selection on X and return the best parameters. This time we
choose maxNorm values instead of lambdas.
"""
minVal = False
evaluationMethod = self.getEvaluationMethod()
paramDict = {"k": self.ks, "alpha": self.alphas, "maxNormU": self.maxNorms, "maxNormV": self.maxNorms}
if meanMetrics == None:
meanMetrics = self.parallelGridSearch(X, paramDict, evaluationMethod, testX, minVal=minVal)
else:
resultDict, bestMetric = self.setBestLearner(meanMetrics, paramDict, minVal)
return meanMetrics, paramDict
def modelSelectLmbda(self, X=None, testX=None, meanMetrics=None):
"""
Perform model selection on X and return the best parameters. This time we
choose maxNorms independently
"""
minVal = False
evaluationMethod = self.getEvaluationMethod()
paramDict = {"k": self.ks, "lmbda": self.lmbdas}
if meanMetrics == None:
meanMetrics = self.parallelGridSearch(X, paramDict, evaluationMethod, testX, minVal=minVal)
else:
resultDict, bestMetric = self.setBestLearner(meanMetrics, paramDict, minVal)
return meanMetrics, paramDict
def objectiveApprox(self, positiveArray, U, V, r, gi, gp, gq, allArray=None, full=False):
"""
Compute the estimated local AUC for the score functions UV^T relative to X with
quantile w. The AUC is computed using positiveArray which is a tuple (indPtr, colInds)
assuming allArray is None. If allArray is not None then positive items are chosen
from positiveArray and negative ones are chosen to complement allArray.
"""
indPtr, colInds = positiveArray
U = numpy.ascontiguousarray(U)
V = numpy.ascontiguousarray(V)
if allArray == None:
return self.learnerCython.objectiveApprox(indPtr, colInds, indPtr, colInds, U, V, gp, gq, full=full, reg=self.reg)
else:
allIndPtr, allColInds = allArray
return self.learnerCython.objectiveApprox(indPtr, colInds, allIndPtr, allColInds, U, V, gp, gq, full=full, reg=self.reg)
def parallelGridSearch(self, X, paramDict, evaluationMethod, testX=None, minVal=True):
"""
Perform parallel model selection using any learner.
"""
logging.debug("Parallel grid search with params: " + str(paramDict))
m, n = X.shape
if testX==None:
trainTestXs = Sampling.shuffleSplitRows(X, self.folds, self.validationSize)
else:
trainTestXs = [[X, testX]]
gridSize = []
gridInds = []
for key in paramDict.keys():
gridSize.append(paramDict[key].shape[0])
gridInds.append(numpy.arange(paramDict[key].shape[0]))
meanMetrics = numpy.zeros(tuple(gridSize))
paramList = []
for icv, (trainX, testX) in enumerate(trainTestXs):
indexIter = itertools.product(*gridInds)
for inds in indexIter:
learner = self.copy()
for i, (key, val) in enumerate(paramDict.items()):
setattr(learner, key, val[inds[i]])
paramList.append((trainX, testX, learner))
if self.numProcesses != 1:
pool = multiprocessing.Pool(processes=self.numProcesses, maxtasksperchild=100)
resultsIterator = pool.imap(evaluationMethod, paramList, self.chunkSize)
else:
resultsIterator = itertools.imap(evaluationMethod, paramList)
for icv, (trainX, testX) in enumerate(trainTestXs):
indexIter = itertools.product(*gridInds)
for inds in indexIter:
metric = resultsIterator.next()
meanMetrics[inds] += metric/float(self.folds)
if self.numProcesses != 1:
pool.terminate()
resultDict, bestMetric = self.setBestLearner(meanMetrics, paramDict, minVal)
return meanMetrics
def parallelLearnModel(self, X, verbose=False, U=None, V=None):
"""
Max local AUC with Frobenius norm penalty on V. Solve with parallel (stochastic) gradient descent.
The input is a sparse array.
"""
#Convert to a csarray for faster access
if scipy.sparse.issparse(X):
logging.debug("Converting to csarray")
X2 = sppy.csarray(X, storagetype="row")
X = X2
m, n = X.shape
#We keep a validation set in order to determine when to stop
if self.validationUsers != 0:
numValidationUsers = int(m*self.validationUsers)
trainX, testX, rowSamples = Sampling.shuffleSplitRows(X, 1, self.validationSize, numRows=numValidationUsers)[0]
testIndPtr, testColInds = SparseUtils.getOmegaListPtr(testX)
else:
trainX = X
testX = None
rowSamples = None
testIndPtr, testColInds = None, None
#Not that to compute the test AUC we pick i \in X and j \notin X \cup testX
indPtr, colInds = SparseUtils.getOmegaListPtr(trainX)
allIndPtr, allColInds = SparseUtils.getOmegaListPtr(X)
if U==None or V==None:
U, V = self.initUV(trainX)
if self.metric == "f1":
metricInd = 2
elif self.metric == "mrr":
metricInd = 3
else:
raise ValueError("Unknown metric: " + self.metric)
bestMetric = 0
bestU = 0
bestV = 0
trainMeasures = []
testMeasures = []
loopInd = 0
lastObj = 0
currentObj = lastObj - 2*self.eps
numBlocks = self.numProcesses+1
gi, gp, gq = self.computeGipq(X)
normGp, normGq = self.computeNormGpq(indPtr, colInds, gp, gq, m)
#Some shared variables
rowIsFree = sharedmem.ones(numBlocks, dtype=numpy.bool)
colIsFree = sharedmem.ones(numBlocks, dtype=numpy.bool)
#Create shared factors
U2 = sharedmem.zeros((m, self.k))
V2 = sharedmem.zeros((n, self.k))
muU2 = sharedmem.zeros((m, self.k))
muV2 = sharedmem.zeros((n, self.k))
U2[:] = U[:]
V2[:] = V[:]
muU2[:] = U[:]
muV2[:] = V[:]
del U, V
rowBlockSize = int(numpy.ceil(float(m)/numBlocks))
colBlockSize = int(numpy.ceil(float(n)/numBlocks))
lock = multiprocessing.Lock()
startTime = time.time()
loopInd = 0
iterationsPerBlock = sharedmem.zeros((numBlocks, numBlocks))
self.learnerCython = self.getCythonLearner()
nextRecord = 0
while loopInd < self.maxIterations and abs(lastObj - currentObj) > self.eps:
if loopInd >= nextRecord:
if loopInd != 0:
print("")
printStr = self.recordResults(muU2, muV2, trainMeasures, testMeasures, loopInd, rowSamples, indPtr, colInds, testIndPtr, testColInds, allIndPtr, allColInds, gi, gp, gq, trainX, startTime)
logging.debug(printStr)
if testIndPtr is not None and testMeasures[-1][metricInd] >= bestMetric:
bestMetric = testMeasures[-1][metricInd]
bestU = muU2.copy()
bestV = muV2.copy()
elif testIndPtr is None:
bestU = muU2.copy()
bestV = muV2.copy()
#Compute objective averaged over last 5 recorded steps
trainMeasuresArr = numpy.array(trainMeasures)
lastObj = currentObj
currentObj = numpy.mean(trainMeasuresArr[-5:, 0])
nextRecord += self.recordStep
iterationsPerBlock = sharedmem.zeros((numBlocks, numBlocks))
self.parallelUpdateUV(X, U2, V2, muU2, muV2, numBlocks, rowBlockSize, colBlockSize, rowIsFree, colIsFree, indPtr, colInds, lock, gi, gp, gq, normGp, normGq, iterationsPerBlock, loopInd)
loopInd += numpy.floor(iterationsPerBlock.mean())
totalTime = time.time() - startTime
#Compute quantities for last U and V
print("")
totalTime = time.time() - startTime
printStr = "Finished, time=" + str('%.1f' % totalTime) + " "
printStr += self.recordResults(muU2, muV2, trainMeasures, testMeasures, loopInd, rowSamples, indPtr, colInds, testIndPtr, testColInds, allIndPtr, allColInds, gi, gp, gq, trainX, startTime)
printStr += " delta obj" + "%.3e" % abs(lastObj - currentObj)
logging.debug(printStr)
self.U = bestU
self.V = bestV
self.gi = gi
self.gp = gp
self.gq = gq
if verbose:
return self.U, self.V, numpy.array(trainMeasures), numpy.array(testMeasures), loopInd, totalTime
else:
return self.U, self.V
def parallelUpdateUV(self, X, U, V, muU, muV, numBlocks, rowBlockSize, colBlockSize, rowIsFree, colIsFree, indPtr, colInds, lock, gi, gp, gq, normGp, normGq, iterationsPerBlock, loopInd):
m, n = X.shape
gradientsPerBlock = sharedmem.zeros((numBlocks, numBlocks))
#Set up order of indices for stochastic methods
permutedRowInds = numpy.array(numpy.random.permutation(m), numpy.uint32)
permutedColInds = numpy.array(numpy.random.permutation(n), numpy.uint32)
for i in range(numBlocks):
for j in range(numBlocks):
gradientsPerBlock[i, j] = numpy.ceil(float(max(m, n))/(numBlocks**2))
assert gradientsPerBlock.sum() >= max(m,n)
#print(gradientsPerBlock.sum())
#Compute omega for each col block
omegasList = []
for i in range(numBlocks):
blockColInds = permutedColInds[i*colBlockSize:(i+1)*colBlockSize]
omegasList.append(restrictOmega(indPtr, colInds, blockColInds))
processList = []
if self.numProcesses != 1:
for i in range(self.numProcesses):
learner = self.copy()
learner.learnerCython = self.getCythonLearner()
sharedArgs = rowIsFree, colIsFree, iterationsPerBlock, gradientsPerBlock, U, V, muU, muV, lock
methodArgs = learner, rowBlockSize, colBlockSize, indPtr, colInds, permutedRowInds, permutedColInds, gi, gp, gq, normGp, normGq, i, loopInd, omegasList
process = multiprocessing.Process(target=updateUVBlock, args=(sharedArgs, methodArgs))
process.start()
processList.append(process)
for process in processList:
process.join()
else:
learner = self.copy()
learner.learnerCython = self.getCythonLearner()
sharedArgs = rowIsFree, colIsFree, iterationsPerBlock, gradientsPerBlock, U, V, muU, muV, lock
methodArgs = learner, rowBlockSize, colBlockSize, indPtr, colInds, permutedRowInds, permutedColInds, gi, gp, gq, normGp, normGq, 0, loopInd, omegasList
updateUVBlock(sharedArgs, methodArgs)
def predict(self, maxItems):
return MCEvaluator.recommendAtk(self.U, self.V, maxItems)
def recordResults(self, muU, muV, trainMeasures, testMeasures, loopInd, rowSamples, indPtr, colInds, testIndPtr, testColInds, allIndPtr, allColInds, gi, gp, gq, trainX, startTime):
sigmaU = self.getSigma(loopInd, self.alpha, muU.shape[0])
sigmaV = self.getSigma(loopInd, self.alpha, muU.shape[0])
r = SparseUtilsCython.computeR(muU, muV, self.w, self.numRecordAucSamples)
objArr = self.objectiveApprox((indPtr, colInds), muU, muV, r, gi, gp, gq, full=True)
if trainMeasures == None:
trainMeasures = []
trainMeasures.append([objArr.sum(), MCEvaluator.localAUCApprox((indPtr, colInds), muU, muV, self.w, self.numRecordAucSamples, r), time.time()-startTime, loopInd])
printStr = "iter " + str(loopInd) + ":"
printStr += " sigmaU=" + str('%.4f' % sigmaU)
printStr += " sigmaV=" + str('%.4f' % sigmaV)
printStr += " train: obj~" + str('%.4f' % trainMeasures[-1][0])
printStr += " LAUC~" + str('%.4f' % trainMeasures[-1][1])
if testIndPtr is not None:
testMeasuresRow = []
testMeasuresRow.append(self.objectiveApprox((testIndPtr, testColInds), muU, muV, r, gi, gp, gq, allArray=(allIndPtr, allColInds)))
testMeasuresRow.append(MCEvaluator.localAUCApprox((testIndPtr, testColInds), muU, muV, self.w, self.numRecordAucSamples, r, allArray=(allIndPtr, allColInds)))
testOrderedItems = MCEvaluatorCython.recommendAtk(muU, muV, numpy.max(self.recommendSize), trainX)
printStr += " validation: obj~" + str('%.4f' % testMeasuresRow[0])
printStr += " LAUC~" + str('%.4f' % testMeasuresRow[1])
try:
for p in self.recommendSize:
f1Array, orderedItems = MCEvaluator.f1AtK((testIndPtr, testColInds), testOrderedItems, p, verbose=True)
testMeasuresRow.append(f1Array[rowSamples].mean())
except:
f1Array, orderedItems = MCEvaluator.f1AtK((testIndPtr, testColInds), testOrderedItems, self.recommendSize, verbose=True)
testMeasuresRow.append(f1Array[rowSamples].mean())
printStr += " f1@" + str(self.recommendSize) + "=" + str('%.4f' % testMeasuresRow[-1])
try:
for p in self.recommendSize:
mrr, orderedItems = MCEvaluator.mrrAtK((testIndPtr, testColInds), testOrderedItems, p, verbose=True)
testMeasuresRow.append(mrr[rowSamples].mean())
except:
mrr, orderedItems = MCEvaluator.mrrAtK((testIndPtr, testColInds), testOrderedItems, self.recommendSize, verbose=True)
testMeasuresRow.append(mrr[rowSamples].mean())
printStr += " mrr@" + str(self.recommendSize) + "=" + str('%.4f' % testMeasuresRow[-1])
testMeasures.append(testMeasuresRow)
printStr += " ||U||=" + str('%.3f' % numpy.linalg.norm(muU))
printStr += " ||V||=" + str('%.3f' % numpy.linalg.norm(muV))
if self.bound:
trainObj = objArr.sum()
expectationBound = self.computeBound(trainX, muU, muV, trainObj, self.delta)
printStr += " bound=" + str('%.3f' % expectationBound)
trainMeasures[-1].append(expectationBound)
return printStr
def setBestLearner(self, meanMetrics, paramDict, minVal=True):
"""
Given a grid of errors, paramDict and examples, labels, find the
best learner.
"""
if minVal:
bestInds = numpy.unravel_index(numpy.argmin(meanMetrics), meanMetrics.shape)
else:
bestInds = numpy.unravel_index(numpy.argmax(meanMetrics), meanMetrics.shape)
resultDict = {}
for i, (key, val) in enumerate(paramDict.items()):
bestVal = val[bestInds[i]]
setattr(self, key, bestVal)
resultDict[key] = bestVal
bestMetric = meanMetrics[bestInds]
logging.debug("Param dict: " + str(paramDict))
logging.debug("Mean metrics: " + str(meanMetrics))
logging.debug("Best parameters: " + str(resultDict) + " with metric value " + str(bestMetric))
return resultDict, bestMetric
def singleLearnModel(self, X, verbose=False, U=None, V=None):
"""
Max local AUC with Frobenius norm penalty on V. Solve with (stochastic) gradient descent.
The input is a sparse array.
"""
#Convert to a csarray for faster access
if scipy.sparse.issparse(X):
logging.debug("Converting to csarray")
X2 = sppy.csarray(X, storagetype="row")
X = X2
m, n = X.shape
#We keep a validation set in order to determine when to stop
if self.validationUsers != 0:
numValidationUsers = int(m*self.validationUsers)
trainX, testX, rowSamples = Sampling.shuffleSplitRows(X, 1, self.validationSize, numRows=numValidationUsers)[0]
testIndPtr, testColInds = SparseUtils.getOmegaListPtr(testX)
logging.debug("Train X shape and nnz: " + str(trainX.shape) + " " + str(trainX.nnz))
logging.debug("Validation X shape and nnz: " + str(testX.shape) + " " + str(testX.nnz))
else:
trainX = X
testX = None
rowSamples = None
testIndPtr, testColInds = None, None
#Note that to compute the test AUC we pick i \in X and j \notin X \cup testX
indPtr, colInds = SparseUtils.getOmegaListPtr(trainX)
allIndPtr, allColInds = SparseUtils.getOmegaListPtr(X)
if type(U) != numpy.ndarray and type(V) != numpy.ndarray:
U, V = self.initUV(trainX)
if self.metric == "f1":
metricInd = 2
elif self.metric == "mrr":
metricInd = 3
else:
raise ValueError("Unknown metric: " + self.metric)
muU = U.copy()
muV = V.copy()
bestMetric = 0
bestU = 0
bestV = 0
trainMeasures = []
testMeasures = []
loopInd = 0
lastObj = 0
currentObj = lastObj - 2*self.eps
#Try alternative number of iterations
#numIterations = trainX.nnz/self.numAucSamples
numIterations = max(m, n)
self.learnerCython = self.getCythonLearner()
#Set up order of indices for stochastic methods
permutedRowInds = numpy.array(numpy.random.permutation(m), numpy.uint32)
permutedColInds = numpy.array(numpy.random.permutation(n), numpy.uint32)
startTime = time.time()
gi, gp, gq = self.computeGipq(X)
normGp, normGq = self.computeNormGpq(indPtr, colInds, gp, gq, m)
while loopInd < self.maxIterations and abs(lastObj - currentObj) > self.eps:
sigmaU = self.getSigma(loopInd, self.alpha, m)
sigmaV = self.getSigma(loopInd, self.alpha, m)
if loopInd % self.recordStep == 0:
if loopInd != 0 and self.stochastic:
print("")
printStr = self.recordResults(muU, muV, trainMeasures, testMeasures, loopInd, rowSamples, indPtr, colInds, testIndPtr, testColInds, allIndPtr, allColInds, gi, gp, gq, trainX, startTime)
logging.debug(printStr)
if testIndPtr is not None and testMeasures[-1][metricInd] >= bestMetric:
bestMetric = testMeasures[-1][metricInd]
logging.debug("Current best metric=" + str(bestMetric))
bestU = muU.copy()
bestV = muV.copy()
elif testIndPtr is None:
bestU = muU.copy()
bestV = muV.copy()
#Compute objective averaged over last 5 recorded steps
trainMeasuresArr = numpy.array(trainMeasures)
lastObj = currentObj
currentObj = numpy.mean(trainMeasuresArr[-5:, 0])
U = numpy.ascontiguousarray(U)
self.updateUV(indPtr, colInds, U, V, muU, muV, permutedRowInds, permutedColInds, gp, gq, normGp, normGq, loopInd, sigmaU, sigmaV, numIterations)
loopInd += 1
#Compute quantities for last U and V
totalTime = time.time() - startTime
printStr = "\nFinished, time=" + str('%.1f' % totalTime) + " "
printStr += self.recordResults(muU, muV, trainMeasures, testMeasures, loopInd, rowSamples, indPtr, colInds, testIndPtr, testColInds, allIndPtr, allColInds, gi, gp, gq, trainX, startTime)
printStr += " delta obj=" + "%.3e" % abs(lastObj - currentObj)
logging.debug(printStr)
self.U = bestU
self.V = bestV
self.gi = gi
self.gp = gp
self.gq = gq
trainMeasures = numpy.array(trainMeasures)
testMeasures = numpy.array(testMeasures)
if verbose:
return self.U, self.V, trainMeasures, testMeasures, loopInd, totalTime
else:
return self.U, self.V
def updateUV(self, indPtr, colInds, U, V, muU, muV, permutedRowInds, permutedColInds, gp, gq, normGp, normGq, ind, sigmaU, sigmaV, numIterations):
"""
Find the derivative with respect to V or part of it.
"""
if not self.stochastic:
self.learnerCython.updateU(indPtr, colInds, U, V, gp, gq, sigmaU)
self.learnerCython.updateV(indPtr, colInds, U, V, gp, gq, sigmaV)
muU[:] = U[:]
muV[:] = V[:]
else:
self.learnerCython.updateUVApprox(indPtr, colInds, U, V, muU, muV, permutedRowInds, permutedColInds, gp, gq, normGp, normGq, ind, numIterations, sigmaU, sigmaV)
lmbdaU = property(getLmbdaU)
lmbdaV = property(getLmbdaV)
|
charanpald/sandbox
|
sandbox/recommendation/MaxLocalAUC.py
|
Python
|
gpl-3.0
| 37,126 | 0.016134 |
try:
import traceback
import argparse
import textwrap
import glob
import os
import logging
import datetime
import multiprocessing
from libs import LasPyConverter
except ImportError as err:
print('Error {0} import module: {1}'.format(__name__, err))
traceback.print_exc()
exit(128)
script_path = __file__
header = textwrap.dedent('''LAS Diff''')
class LasPyParameters:
def __init__(self):
# predefinied paths
self.parser = argparse.ArgumentParser(prog="lasdiff",
formatter_class=argparse.RawDescriptionHelpFormatter,
description='',
epilog=textwrap.dedent('''
example:
'''))
# reguired parameters
self.parser.add_argument('-i', type=str, dest='input', required=True,
help='required: input file or folder')
self.parser.add_argument('-o', type=str, dest='output', required=True,
help='required: output file or folder (d:\lasfiles\\tests\\results)')
# optional parameters
self.parser.add_argument('-input_format', type=str, dest='input_format', required=False, choices=['las', 'laz'],
help='optional: input format (default=las, laz is not implemented (yet))')
self.parser.add_argument('-cores', type=int, dest='cores', required=False, default=1,
help='optional: cores (default=1)')
self.parser.add_argument('-v', dest='verbose', required=False,
help='optional: verbose toggle (-v=on, nothing=off)', action='store_true')
self.parser.add_argument('-version', action='version', version=self.parser.prog)
def parse(self):
self.args = self.parser.parse_args()
##defaults
if self.args.verbose:
self.args.verbose = ' -v'
else:
self.args.verbose = ''
if self.args.input_format == None:
self.args.input_format = 'las'
if self.args.cores == None:
self.args.cores = 1
# ---------PUBLIC METHODS--------------------
def get_output(self):
return self.args.output
def get_input(self):
return self.args.input
def get_input_format(self):
return self.args.input_format
def get_verbose(self):
return self.args.verbose
def get_cores(self):
return self.args.cores
def DiffLas(parameters):
# Parse incoming parameters
source_file = parameters[0]
destination_file = parameters[1]
# Get name for this process
current = multiprocessing.current_proces()
proc_name = current.name
logging.info('[%s] Starting ...' % (proc_name))
logging.info(
'[%s] Creating diff of %s LAS PointCloud file and %s LAS PointCloud file ...' % (
proc_name, source_file, destination_file))
# Opening source LAS files for read and write
lasFiles = LasPyConverter.LasPyCompare(source_file, destination_file)
# Opening destination LAS file
logging.info('[%s] Opening %s LAS PointCloud file and %s LAS PointCloud file ...' % (
proc_name, source_file, destination_file))
lasFiles.OpenReanOnly()
logging.info('[%s] Comparing %s LAS PointCloud file and %s LAS PointCloud file ...' % (
proc_name, source_file, destination_file))
lasFiles.ComparePointCloud()
logging.info('[%s] Closing %s LAS PointCloud.' % (proc_name, destination_file))
lasFiles.Close()
logging.info('[%s] %s LAS PointCloud has closed.' % (proc_name, destination_file))
return 0
def SetLogging(logfilename):
logging.basicConfig(
filename=logfilename,
filemode='w',
format='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S',
level=logging.DEBUG)
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
def main():
logfilename = 'lasdiff_' + datetime.datetime.today().strftime('%Y%m%d_%H%M%S') + '.log'
SetLogging(logfilename)
logging.info(header)
lasconverterworkflow = LasPyParameters()
lasconverterworkflow.parse()
# File/Directory handler
inputfiles = lasconverterworkflow.get_input()
inputformat = lasconverterworkflow.get_input_format()
outputfiles = lasconverterworkflow.get_output()
outputpath = os.path.normpath(outputfiles)
cores = lasconverterworkflow.get_cores()
inputisdir = False
doing = []
if os.path.isdir(inputfiles):
inputisdir = True
inputfiles = glob.glob(os.path.join(inputfiles, '*' + inputformat))
if not os.path.exists(outputfiles):
os.makedirs(outputfiles)
for workfile in inputfiles:
if os.path.isfile(workfile) and os.path.isfile(os.path.join(outputpath, os.path.basename(workfile))):
logging.info('Adding %s to the queue.' % (workfile))
doing.append([workfile, os.path.join(outputpath, os.path.basename(workfile))])
else:
logging.info('The %s is not file, or pair of comparable files. Skipping.' % (workfile))
elif os.path.isfile(inputfiles):
inputisdir = False
workfile = inputfiles
if os.path.basename(outputfiles) is not "":
doing.append([workfile, outputfiles])
else:
doing.append([workfile, os.path.join(outputpath, os.path.basename(workfile))])
logging.info('Adding %s to the queue.' % (workfile))
else:
# Not a file, not a dir
logging.error('Cannot found input LAS PointCloud file: %s' % (inputfiles))
exit(1)
# If we got one file, start only one process
if inputisdir is False:
cores = 1
if cores != 1:
pool = multiprocessing.Pool(processes=cores)
results = pool.map_async(DiffLas, doing)
pool.close()
pool.join()
else:
for d in doing:
DiffLas(d)
logging.info('Finished, exiting and go home ...')
if __name__ == '__main__':
main()
|
KAMI911/lactransformer
|
lactransformer/lasdiff.py
|
Python
|
mpl-2.0
| 6,565 | 0.003656 |
"""An implementation of Matching Layer."""
import typing
import tensorflow as tf
from keras.engine import Layer
class MatchingLayer(Layer):
"""
Layer that computes a matching matrix between samples in two tensors.
:param normalize: Whether to L2-normalize samples along the
dot product axis before taking the dot product.
If set to True, then the output of the dot product
is the cosine proximity between the two samples.
:param matching_type: the similarity function for matching
:param kwargs: Standard layer keyword arguments.
Examples:
>>> import matchzoo as mz
>>> layer = mz.layers.MatchingLayer(matching_type='dot',
... normalize=True)
>>> num_batch, left_len, right_len, num_dim = 5, 3, 2, 10
>>> layer.build([[num_batch, left_len, num_dim],
... [num_batch, right_len, num_dim]])
"""
def __init__(self, normalize: bool = False,
matching_type: str = 'dot', **kwargs):
""":class:`MatchingLayer` constructor."""
super().__init__(**kwargs)
self._normalize = normalize
self._validate_matching_type(matching_type)
self._matching_type = matching_type
self._shape1 = None
self._shape2 = None
@classmethod
def _validate_matching_type(cls, matching_type: str = 'dot'):
valid_matching_type = ['dot', 'mul', 'plus', 'minus', 'concat']
if matching_type not in valid_matching_type:
raise ValueError(f"{matching_type} is not a valid matching type, "
f"{valid_matching_type} expected.")
def build(self, input_shape: list):
"""
Build the layer.
:param input_shape: the shapes of the input tensors,
for MatchingLayer we need tow input tensors.
"""
# Used purely for shape validation.
if not isinstance(input_shape, list) or len(input_shape) != 2:
raise ValueError('A `MatchingLayer` layer should be called '
'on a list of 2 inputs.')
self._shape1 = input_shape[0]
self._shape2 = input_shape[1]
for idx in 0, 2:
if self._shape1[idx] != self._shape2[idx]:
raise ValueError(
'Incompatible dimensions: '
f'{self._shape1[idx]} != {self._shape2[idx]}.'
f'Layer shapes: {self._shape1}, {self._shape2}.'
)
def call(self, inputs: list, **kwargs) -> typing.Any:
"""
The computation logic of MatchingLayer.
:param inputs: two input tensors.
"""
x1 = inputs[0]
x2 = inputs[1]
if self._matching_type == 'dot':
if self._normalize:
x1 = tf.math.l2_normalize(x1, axis=2)
x2 = tf.math.l2_normalize(x2, axis=2)
return tf.expand_dims(tf.einsum('abd,acd->abc', x1, x2), 3)
else:
if self._matching_type == 'mul':
def func(x, y):
return x * y
elif self._matching_type == 'plus':
def func(x, y):
return x + y
elif self._matching_type == 'minus':
def func(x, y):
return x - y
elif self._matching_type == 'concat':
def func(x, y):
return tf.concat([x, y], axis=3)
else:
raise ValueError(f"Invalid matching type."
f"{self._matching_type} received."
f"Mut be in `dot`, `mul`, `plus`, "
f"`minus` and `concat`.")
x1_exp = tf.stack([x1] * self._shape2[1], 2)
x2_exp = tf.stack([x2] * self._shape1[1], 1)
return func(x1_exp, x2_exp)
def compute_output_shape(self, input_shape: list) -> tuple:
"""
Calculate the layer output shape.
:param input_shape: the shapes of the input tensors,
for MatchingLayer we need tow input tensors.
"""
if not isinstance(input_shape, list) or len(input_shape) != 2:
raise ValueError('A `MatchingLayer` layer should be called '
'on a list of 2 inputs.')
shape1 = list(input_shape[0])
shape2 = list(input_shape[1])
if len(shape1) != 3 or len(shape2) != 3:
raise ValueError('A `MatchingLayer` layer should be called '
'on 2 inputs with 3 dimensions.')
if shape1[0] != shape2[0] or shape1[2] != shape2[2]:
raise ValueError('A `MatchingLayer` layer should be called '
'on 2 inputs with same 0,2 dimensions.')
if self._matching_type in ['mul', 'plus', 'minus']:
return shape1[0], shape1[1], shape2[1], shape1[2]
elif self._matching_type == 'dot':
return shape1[0], shape1[1], shape2[1], 1
elif self._matching_type == 'concat':
return shape1[0], shape1[1], shape2[1], shape1[2] + shape2[2]
else:
raise ValueError(f"Invalid `matching_type`."
f"{self._matching_type} received."
f"Must be in `mul`, `plus`, `minus` "
f"`dot` and `concat`.")
def get_config(self) -> dict:
"""Get the config dict of MatchingLayer."""
config = {
'normalize': self._normalize,
'matching_type': self._matching_type,
}
base_config = super(MatchingLayer, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
|
faneshion/MatchZoo
|
matchzoo/layers/matching_layer.py
|
Python
|
apache-2.0
| 5,753 | 0 |
from list_node import ListNode
from instruction import Instruction, Subneg4Instruction
def sr_mult(WM, LM):
namespace_bak = WM.getNamespace(string=False)
WM.setNamespace(["sr","mult"])
c_0 = WM.const(0)
c_1 = WM.const(1)
c_m1 = WM.const(-1)
c_32 = WM.const(32)
a = WM.addDataWord(0, "arg1")
b = WM.addDataWord(0, "arg2")
ret_addr = WM.addDataPtrWord(0, "ret_addr")
temp = WM.addDataWord(0, "temp")
count = WM.addDataWord(0, "count")
hi = WM.addDataWord(0, "hi")
lo = WM.addDataWord(0, "lo")
sign = WM.addDataWord(0, "sign")
NEXT = WM.getNext()
#HALT = WM.getHalt()
LNs = (
LM.new(ListNode("sr_mult", sys = True)),
LM.new(ListNode(Subneg4Instruction(
c_1.getPtr(),
a.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L010")
)), "sr_mult_start"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L020")
))),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_0.getPtr(),
a.getPtr(),
NEXT
)),"sr_mult_L010"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_1.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_1.getPtr(),
b.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L030")
)),"sr_mult_L020"),
LM.new(ListNode(Subneg4Instruction(
c_32.getPtr(),
c_0.getPtr(),
count.getPtr(),
WM.label("sr_mult_L050")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_0.getPtr(),
b.getPtr(),
NEXT
)),"sr_mult_L030"),
LM.new(ListNode(Subneg4Instruction(
sign.getPtr(),
c_m1.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_32.getPtr(),
c_0.getPtr(),
count.getPtr(),
NEXT
)),"sr_mult_L040"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
hi.getPtr(),
NEXT
)),"sr_mult_L050"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
hi.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L100"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L110")
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L110"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
lo.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L200"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
lo.getPtr(),
lo.getPtr(),
WM.label("sr_mult_L300")
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
b.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L500")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
lo.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L500")
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
)),"sr_mult_L300"),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
lo.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
)),"sr_mult_L500"),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L800"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
a.getPtr(),
a.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
count.getPtr(),
count.getPtr(),
WM.label("sr_mult_L100")
))),
LM.new(ListNode(Subneg4Instruction(
sign.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L990")
)),"sr_mult_L900"),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_0.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
hi.getPtr(),
c_0.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
hi.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L990"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
lo.getPtr(),
temp.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
ret_addr
)))
)
WM.setNamespace(namespace_bak)
return LNs, a, b, ret_addr, lo
|
AZQ1994/s4compiler
|
sr_mult.py
|
Python
|
gpl-3.0
| 5,281 | 0.065897 |
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.conf.urls import url
from openstack_dashboard.dashboards.project.networks.ports import views
from openstack_dashboard.dashboards.project.networks.ports.extensions. \
allowed_address_pairs import views as addr_pairs_views
PORTS = r'^(?P<port_id>[^/]+)/%s$'
urlpatterns = [
url(PORTS % 'detail', views.DetailView.as_view(), name='detail'),
url(PORTS % 'addallowedaddresspairs',
addr_pairs_views.AddAllowedAddressPair.as_view(),
name='addallowedaddresspairs')
]
|
openstack/horizon
|
openstack_dashboard/dashboards/project/networks/ports/urls.py
|
Python
|
apache-2.0
| 1,111 | 0 |
# 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.
# --------------------------------------------------------------------------
from azure.core.exceptions import HttpResponseError
import msrest.serialization
class AddressSpace(msrest.serialization.Model):
"""AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network.
:param address_prefixes: A list of address blocks reserved for this virtual network in CIDR
notation.
:type address_prefixes: list[str]
"""
_attribute_map = {
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AddressSpace, self).__init__(**kwargs)
self.address_prefixes = kwargs.get('address_prefixes', None)
class Resource(msrest.serialization.Model):
"""Common resource representation.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(Resource, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.name = None
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
class ApplicationGateway(Resource):
"""Application gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param zones: A list of availability zones denoting where the resource needs to come from.
:type zones: list[str]
:param identity: The identity of the application gateway, if configured.
:type identity: ~azure.mgmt.network.v2019_04_01.models.ManagedServiceIdentity
:param sku: SKU of the application gateway resource.
:type sku: ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySku
:param ssl_policy: SSL policy of the application gateway resource.
:type ssl_policy: ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslPolicy
:ivar operational_state: Operational state of the application gateway resource. Possible values
include: "Stopped", "Starting", "Running", "Stopping".
:vartype operational_state: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayOperationalState
:param gateway_ip_configurations: Subnets of the application gateway resource. For default
limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type gateway_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayIPConfiguration]
:param authentication_certificates: Authentication certificates of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type authentication_certificates:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayAuthenticationCertificate]
:param trusted_root_certificates: Trusted Root certificates of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type trusted_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayTrustedRootCertificate]
:param ssl_certificates: SSL certificates of the application gateway resource. For default
limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type ssl_certificates:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslCertificate]
:param frontend_ip_configurations: Frontend IP addresses of the application gateway resource.
For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type frontend_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFrontendIPConfiguration]
:param frontend_ports: Frontend ports of the application gateway resource. For default limits,
see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type frontend_ports:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFrontendPort]
:param probes: Probes of the application gateway resource.
:type probes: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProbe]
:param backend_address_pools: Backend address pool of the application gateway resource. For
default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type backend_address_pools:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendAddressPool]
:param backend_http_settings_collection: Backend http settings of the application gateway
resource. For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type backend_http_settings_collection:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHttpSettings]
:param http_listeners: Http listeners of the application gateway resource. For default limits,
see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type http_listeners:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayHttpListener]
:param url_path_maps: URL path map of the application gateway resource. For default limits, see
`Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type url_path_maps: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayUrlPathMap]
:param request_routing_rules: Request routing rules of the application gateway resource.
:type request_routing_rules:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRequestRoutingRule]
:param rewrite_rule_sets: Rewrite rules for the application gateway resource.
:type rewrite_rule_sets:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRewriteRuleSet]
:param redirect_configurations: Redirect configurations of the application gateway resource.
For default limits, see `Application Gateway limits
<https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits>`_.
:type redirect_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRedirectConfiguration]
:param web_application_firewall_configuration: Web application firewall configuration.
:type web_application_firewall_configuration:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayWebApplicationFirewallConfiguration
:param firewall_policy: Reference of the FirewallPolicy resource.
:type firewall_policy: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param enable_http2: Whether HTTP2 is enabled on the application gateway resource.
:type enable_http2: bool
:param enable_fips: Whether FIPS is enabled on the application gateway resource.
:type enable_fips: bool
:param autoscale_configuration: Autoscale Configuration.
:type autoscale_configuration:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayAutoscaleConfiguration
:param resource_guid: Resource GUID property of the application gateway resource.
:type resource_guid: str
:param provisioning_state: Provisioning state of the application gateway resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param custom_error_configurations: Custom error configurations of the application gateway
resource.
:type custom_error_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayCustomError]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'operational_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'identity': {'key': 'identity', 'type': 'ManagedServiceIdentity'},
'sku': {'key': 'properties.sku', 'type': 'ApplicationGatewaySku'},
'ssl_policy': {'key': 'properties.sslPolicy', 'type': 'ApplicationGatewaySslPolicy'},
'operational_state': {'key': 'properties.operationalState', 'type': 'str'},
'gateway_ip_configurations': {'key': 'properties.gatewayIPConfigurations', 'type': '[ApplicationGatewayIPConfiguration]'},
'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[ApplicationGatewayAuthenticationCertificate]'},
'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[ApplicationGatewayTrustedRootCertificate]'},
'ssl_certificates': {'key': 'properties.sslCertificates', 'type': '[ApplicationGatewaySslCertificate]'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[ApplicationGatewayFrontendIPConfiguration]'},
'frontend_ports': {'key': 'properties.frontendPorts', 'type': '[ApplicationGatewayFrontendPort]'},
'probes': {'key': 'properties.probes', 'type': '[ApplicationGatewayProbe]'},
'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'},
'backend_http_settings_collection': {'key': 'properties.backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHttpSettings]'},
'http_listeners': {'key': 'properties.httpListeners', 'type': '[ApplicationGatewayHttpListener]'},
'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[ApplicationGatewayUrlPathMap]'},
'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[ApplicationGatewayRequestRoutingRule]'},
'rewrite_rule_sets': {'key': 'properties.rewriteRuleSets', 'type': '[ApplicationGatewayRewriteRuleSet]'},
'redirect_configurations': {'key': 'properties.redirectConfigurations', 'type': '[ApplicationGatewayRedirectConfiguration]'},
'web_application_firewall_configuration': {'key': 'properties.webApplicationFirewallConfiguration', 'type': 'ApplicationGatewayWebApplicationFirewallConfiguration'},
'firewall_policy': {'key': 'properties.firewallPolicy', 'type': 'SubResource'},
'enable_http2': {'key': 'properties.enableHttp2', 'type': 'bool'},
'enable_fips': {'key': 'properties.enableFips', 'type': 'bool'},
'autoscale_configuration': {'key': 'properties.autoscaleConfiguration', 'type': 'ApplicationGatewayAutoscaleConfiguration'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGateway, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.zones = kwargs.get('zones', None)
self.identity = kwargs.get('identity', None)
self.sku = kwargs.get('sku', None)
self.ssl_policy = kwargs.get('ssl_policy', None)
self.operational_state = None
self.gateway_ip_configurations = kwargs.get('gateway_ip_configurations', None)
self.authentication_certificates = kwargs.get('authentication_certificates', None)
self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None)
self.ssl_certificates = kwargs.get('ssl_certificates', None)
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.frontend_ports = kwargs.get('frontend_ports', None)
self.probes = kwargs.get('probes', None)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None)
self.http_listeners = kwargs.get('http_listeners', None)
self.url_path_maps = kwargs.get('url_path_maps', None)
self.request_routing_rules = kwargs.get('request_routing_rules', None)
self.rewrite_rule_sets = kwargs.get('rewrite_rule_sets', None)
self.redirect_configurations = kwargs.get('redirect_configurations', None)
self.web_application_firewall_configuration = kwargs.get('web_application_firewall_configuration', None)
self.firewall_policy = kwargs.get('firewall_policy', None)
self.enable_http2 = kwargs.get('enable_http2', None)
self.enable_fips = kwargs.get('enable_fips', None)
self.autoscale_configuration = kwargs.get('autoscale_configuration', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.custom_error_configurations = kwargs.get('custom_error_configurations', None)
class SubResource(msrest.serialization.Model):
"""Reference to another subresource.
:param id: Resource ID.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubResource, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ApplicationGatewayAuthenticationCertificate(SubResource):
"""Authentication certificates of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the authentication certificate that is unique within an Application
Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param data: Certificate public data.
:type data: str
:param provisioning_state: Provisioning state of the authentication certificate resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAuthenticationCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.data = kwargs.get('data', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayAutoscaleConfiguration(msrest.serialization.Model):
"""Application Gateway autoscale configuration.
All required parameters must be populated in order to send to Azure.
:param min_capacity: Required. Lower bound on number of Application Gateway capacity.
:type min_capacity: int
:param max_capacity: Upper bound on number of Application Gateway capacity.
:type max_capacity: int
"""
_validation = {
'min_capacity': {'required': True, 'minimum': 0},
'max_capacity': {'minimum': 2},
}
_attribute_map = {
'min_capacity': {'key': 'minCapacity', 'type': 'int'},
'max_capacity': {'key': 'maxCapacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAutoscaleConfiguration, self).__init__(**kwargs)
self.min_capacity = kwargs['min_capacity']
self.max_capacity = kwargs.get('max_capacity', None)
class ApplicationGatewayAvailableSslOptions(Resource):
"""Response for ApplicationGatewayAvailableSslOptions API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param predefined_policies: List of available Ssl predefined policy.
:type predefined_policies: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param default_policy: Name of the Ssl predefined policy applied by default to application
gateway. Possible values include: "AppGwSslPolicy20150501", "AppGwSslPolicy20170401",
"AppGwSslPolicy20170401S".
:type default_policy: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslPolicyName
:param available_cipher_suites: List of available Ssl cipher suites.
:type available_cipher_suites: list[str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslCipherSuite]
:param available_protocols: List of available Ssl protocols.
:type available_protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslProtocol]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'predefined_policies': {'key': 'properties.predefinedPolicies', 'type': '[SubResource]'},
'default_policy': {'key': 'properties.defaultPolicy', 'type': 'str'},
'available_cipher_suites': {'key': 'properties.availableCipherSuites', 'type': '[str]'},
'available_protocols': {'key': 'properties.availableProtocols', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableSslOptions, self).__init__(**kwargs)
self.predefined_policies = kwargs.get('predefined_policies', None)
self.default_policy = kwargs.get('default_policy', None)
self.available_cipher_suites = kwargs.get('available_cipher_suites', None)
self.available_protocols = kwargs.get('available_protocols', None)
class ApplicationGatewayAvailableSslPredefinedPolicies(msrest.serialization.Model):
"""Response for ApplicationGatewayAvailableSslOptions API service call.
:param value: List of available Ssl predefined policy.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslPredefinedPolicy]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGatewaySslPredefinedPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableSslPredefinedPolicies, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ApplicationGatewayAvailableWafRuleSetsResult(msrest.serialization.Model):
"""Response for ApplicationGatewayAvailableWafRuleSets API service call.
:param value: The list of application gateway rule sets.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallRuleSet]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGatewayFirewallRuleSet]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayAvailableWafRuleSetsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ApplicationGatewayBackendAddress(msrest.serialization.Model):
"""Backend address of an application gateway.
:param fqdn: Fully qualified domain name (FQDN).
:type fqdn: str
:param ip_address: IP address.
:type ip_address: str
"""
_attribute_map = {
'fqdn': {'key': 'fqdn', 'type': 'str'},
'ip_address': {'key': 'ipAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendAddress, self).__init__(**kwargs)
self.fqdn = kwargs.get('fqdn', None)
self.ip_address = kwargs.get('ip_address', None)
class ApplicationGatewayBackendAddressPool(SubResource):
"""Backend Address Pool of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the backend address pool that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param backend_ip_configurations: Collection of references to IPs defined in network
interfaces.
:type backend_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration]
:param backend_addresses: Backend addresses.
:type backend_addresses:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendAddress]
:param provisioning_state: Provisioning state of the backend address pool resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'backend_addresses': {'key': 'properties.backendAddresses', 'type': '[ApplicationGatewayBackendAddress]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendAddressPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.backend_ip_configurations = kwargs.get('backend_ip_configurations', None)
self.backend_addresses = kwargs.get('backend_addresses', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayBackendHealth(msrest.serialization.Model):
"""Response for ApplicationGatewayBackendHealth API service call.
:param backend_address_pools: A list of ApplicationGatewayBackendHealthPool resources.
:type backend_address_pools:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthPool]
"""
_attribute_map = {
'backend_address_pools': {'key': 'backendAddressPools', 'type': '[ApplicationGatewayBackendHealthPool]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealth, self).__init__(**kwargs)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
class ApplicationGatewayBackendHealthHttpSettings(msrest.serialization.Model):
"""Application gateway BackendHealthHttp settings.
:param backend_http_settings: Reference of an ApplicationGatewayBackendHttpSettings resource.
:type backend_http_settings:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHttpSettings
:param servers: List of ApplicationGatewayBackendHealthServer resources.
:type servers:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthServer]
"""
_attribute_map = {
'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'ApplicationGatewayBackendHttpSettings'},
'servers': {'key': 'servers', 'type': '[ApplicationGatewayBackendHealthServer]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthHttpSettings, self).__init__(**kwargs)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.servers = kwargs.get('servers', None)
class ApplicationGatewayBackendHealthOnDemand(msrest.serialization.Model):
"""Result of on demand test probe.
:param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource.
:type backend_address_pool:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendAddressPool
:param backend_health_http_settings: Application gateway BackendHealthHttp settings.
:type backend_health_http_settings:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthHttpSettings
"""
_attribute_map = {
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'},
'backend_health_http_settings': {'key': 'backendHealthHttpSettings', 'type': 'ApplicationGatewayBackendHealthHttpSettings'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthOnDemand, self).__init__(**kwargs)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_health_http_settings = kwargs.get('backend_health_http_settings', None)
class ApplicationGatewayBackendHealthPool(msrest.serialization.Model):
"""Application gateway BackendHealth pool.
:param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource.
:type backend_address_pool:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendAddressPool
:param backend_http_settings_collection: List of ApplicationGatewayBackendHealthHttpSettings
resources.
:type backend_http_settings_collection:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthHttpSettings]
"""
_attribute_map = {
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'},
'backend_http_settings_collection': {'key': 'backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHealthHttpSettings]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthPool, self).__init__(**kwargs)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings_collection = kwargs.get('backend_http_settings_collection', None)
class ApplicationGatewayBackendHealthServer(msrest.serialization.Model):
"""Application gateway backendhealth http settings.
:param address: IP address or FQDN of backend server.
:type address: str
:param ip_configuration: Reference of IP configuration of backend server.
:type ip_configuration: ~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration
:param health: Health of backend server. Possible values include: "Unknown", "Up", "Down",
"Partial", "Draining".
:type health: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthServerHealth
:param health_probe_log: Health Probe Log.
:type health_probe_log: str
"""
_attribute_map = {
'address': {'key': 'address', 'type': 'str'},
'ip_configuration': {'key': 'ipConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'health': {'key': 'health', 'type': 'str'},
'health_probe_log': {'key': 'healthProbeLog', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHealthServer, self).__init__(**kwargs)
self.address = kwargs.get('address', None)
self.ip_configuration = kwargs.get('ip_configuration', None)
self.health = kwargs.get('health', None)
self.health_probe_log = kwargs.get('health_probe_log', None)
class ApplicationGatewayBackendHttpSettings(SubResource):
"""Backend address pool settings of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the backend http settings that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param port: The destination port on the backend.
:type port: int
:param protocol: The protocol used to communicate with the backend. Possible values include:
"Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProtocol
:param cookie_based_affinity: Cookie based affinity. Possible values include: "Enabled",
"Disabled".
:type cookie_based_affinity: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayCookieBasedAffinity
:param request_timeout: Request timeout in seconds. Application Gateway will fail the request
if response is not received within RequestTimeout. Acceptable values are from 1 second to 86400
seconds.
:type request_timeout: int
:param probe: Probe resource of an application gateway.
:type probe: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param authentication_certificates: Array of references to application gateway authentication
certificates.
:type authentication_certificates: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param trusted_root_certificates: Array of references to application gateway trusted root
certificates.
:type trusted_root_certificates: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param connection_draining: Connection draining of the backend http settings resource.
:type connection_draining:
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayConnectionDraining
:param host_name: Host header to be sent to the backend servers.
:type host_name: str
:param pick_host_name_from_backend_address: Whether to pick host header should be picked from
the host name of the backend server. Default value is false.
:type pick_host_name_from_backend_address: bool
:param affinity_cookie_name: Cookie name to use for the affinity cookie.
:type affinity_cookie_name: str
:param probe_enabled: Whether the probe is enabled. Default value is false.
:type probe_enabled: bool
:param path: Path which should be used as a prefix for all HTTP requests. Null means no path
will be prefixed. Default value is null.
:type path: str
:param provisioning_state: Provisioning state of the backend http settings resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'cookie_based_affinity': {'key': 'properties.cookieBasedAffinity', 'type': 'str'},
'request_timeout': {'key': 'properties.requestTimeout', 'type': 'int'},
'probe': {'key': 'properties.probe', 'type': 'SubResource'},
'authentication_certificates': {'key': 'properties.authenticationCertificates', 'type': '[SubResource]'},
'trusted_root_certificates': {'key': 'properties.trustedRootCertificates', 'type': '[SubResource]'},
'connection_draining': {'key': 'properties.connectionDraining', 'type': 'ApplicationGatewayConnectionDraining'},
'host_name': {'key': 'properties.hostName', 'type': 'str'},
'pick_host_name_from_backend_address': {'key': 'properties.pickHostNameFromBackendAddress', 'type': 'bool'},
'affinity_cookie_name': {'key': 'properties.affinityCookieName', 'type': 'str'},
'probe_enabled': {'key': 'properties.probeEnabled', 'type': 'bool'},
'path': {'key': 'properties.path', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayBackendHttpSettings, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.port = kwargs.get('port', None)
self.protocol = kwargs.get('protocol', None)
self.cookie_based_affinity = kwargs.get('cookie_based_affinity', None)
self.request_timeout = kwargs.get('request_timeout', None)
self.probe = kwargs.get('probe', None)
self.authentication_certificates = kwargs.get('authentication_certificates', None)
self.trusted_root_certificates = kwargs.get('trusted_root_certificates', None)
self.connection_draining = kwargs.get('connection_draining', None)
self.host_name = kwargs.get('host_name', None)
self.pick_host_name_from_backend_address = kwargs.get('pick_host_name_from_backend_address', None)
self.affinity_cookie_name = kwargs.get('affinity_cookie_name', None)
self.probe_enabled = kwargs.get('probe_enabled', None)
self.path = kwargs.get('path', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayConnectionDraining(msrest.serialization.Model):
"""Connection draining allows open connections to a backend server to be active for a specified time after the backend server got removed from the configuration.
All required parameters must be populated in order to send to Azure.
:param enabled: Required. Whether connection draining is enabled or not.
:type enabled: bool
:param drain_timeout_in_sec: Required. The number of seconds connection draining is active.
Acceptable values are from 1 second to 3600 seconds.
:type drain_timeout_in_sec: int
"""
_validation = {
'enabled': {'required': True},
'drain_timeout_in_sec': {'required': True, 'maximum': 3600, 'minimum': 1},
}
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'drain_timeout_in_sec': {'key': 'drainTimeoutInSec', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayConnectionDraining, self).__init__(**kwargs)
self.enabled = kwargs['enabled']
self.drain_timeout_in_sec = kwargs['drain_timeout_in_sec']
class ApplicationGatewayCustomError(msrest.serialization.Model):
"""Customer error of an application gateway.
:param status_code: Status code of the application gateway customer error. Possible values
include: "HttpStatus403", "HttpStatus502".
:type status_code: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayCustomErrorStatusCode
:param custom_error_page_url: Error page URL of the application gateway customer error.
:type custom_error_page_url: str
"""
_attribute_map = {
'status_code': {'key': 'statusCode', 'type': 'str'},
'custom_error_page_url': {'key': 'customErrorPageUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayCustomError, self).__init__(**kwargs)
self.status_code = kwargs.get('status_code', None)
self.custom_error_page_url = kwargs.get('custom_error_page_url', None)
class ApplicationGatewayFirewallDisabledRuleGroup(msrest.serialization.Model):
"""Allows to disable rules within a rule group or an entire rule group.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The name of the rule group that will be disabled.
:type rule_group_name: str
:param rules: The list of rules that will be disabled. If null, all rules of the rule group
will be disabled.
:type rules: list[int]
"""
_validation = {
'rule_group_name': {'required': True},
}
_attribute_map = {
'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'},
'rules': {'key': 'rules', 'type': '[int]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallDisabledRuleGroup, self).__init__(**kwargs)
self.rule_group_name = kwargs['rule_group_name']
self.rules = kwargs.get('rules', None)
class ApplicationGatewayFirewallExclusion(msrest.serialization.Model):
"""Allow to exclude some variable satisfy the condition for the WAF check.
All required parameters must be populated in order to send to Azure.
:param match_variable: Required. The variable to be excluded.
:type match_variable: str
:param selector_match_operator: Required. When matchVariable is a collection, operate on the
selector to specify which elements in the collection this exclusion applies to.
:type selector_match_operator: str
:param selector: Required. When matchVariable is a collection, operator used to specify which
elements in the collection this exclusion applies to.
:type selector: str
"""
_validation = {
'match_variable': {'required': True},
'selector_match_operator': {'required': True},
'selector': {'required': True},
}
_attribute_map = {
'match_variable': {'key': 'matchVariable', 'type': 'str'},
'selector_match_operator': {'key': 'selectorMatchOperator', 'type': 'str'},
'selector': {'key': 'selector', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallExclusion, self).__init__(**kwargs)
self.match_variable = kwargs['match_variable']
self.selector_match_operator = kwargs['selector_match_operator']
self.selector = kwargs['selector']
class ApplicationGatewayFirewallRule(msrest.serialization.Model):
"""A web application firewall rule.
All required parameters must be populated in order to send to Azure.
:param rule_id: Required. The identifier of the web application firewall rule.
:type rule_id: int
:param description: The description of the web application firewall rule.
:type description: str
"""
_validation = {
'rule_id': {'required': True},
}
_attribute_map = {
'rule_id': {'key': 'ruleId', 'type': 'int'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRule, self).__init__(**kwargs)
self.rule_id = kwargs['rule_id']
self.description = kwargs.get('description', None)
class ApplicationGatewayFirewallRuleGroup(msrest.serialization.Model):
"""A web application firewall rule group.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The name of the web application firewall rule group.
:type rule_group_name: str
:param description: The description of the web application firewall rule group.
:type description: str
:param rules: Required. The rules of the web application firewall rule group.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallRule]
"""
_validation = {
'rule_group_name': {'required': True},
'rules': {'required': True},
}
_attribute_map = {
'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'rules': {'key': 'rules', 'type': '[ApplicationGatewayFirewallRule]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRuleGroup, self).__init__(**kwargs)
self.rule_group_name = kwargs['rule_group_name']
self.description = kwargs.get('description', None)
self.rules = kwargs['rules']
class ApplicationGatewayFirewallRuleSet(Resource):
"""A web application firewall rule set.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param provisioning_state: The provisioning state of the web application firewall rule set.
:type provisioning_state: str
:param rule_set_type: The type of the web application firewall rule set.
:type rule_set_type: str
:param rule_set_version: The version of the web application firewall rule set type.
:type rule_set_version: str
:param rule_groups: The rule groups of the web application firewall rule set.
:type rule_groups:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallRuleGroup]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'rule_set_type': {'key': 'properties.ruleSetType', 'type': 'str'},
'rule_set_version': {'key': 'properties.ruleSetVersion', 'type': 'str'},
'rule_groups': {'key': 'properties.ruleGroups', 'type': '[ApplicationGatewayFirewallRuleGroup]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFirewallRuleSet, self).__init__(**kwargs)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.rule_set_type = kwargs.get('rule_set_type', None)
self.rule_set_version = kwargs.get('rule_set_version', None)
self.rule_groups = kwargs.get('rule_groups', None)
class ApplicationGatewayFrontendIPConfiguration(SubResource):
"""Frontend IP configuration of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the frontend IP configuration that is unique within an Application
Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param private_ip_address: PrivateIPAddress of the network interface IP Configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param subnet: Reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param public_ip_address: Reference of the PublicIP resource.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Provisioning state of the public IP resource. Possible values are:
'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFrontendIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayFrontendPort(SubResource):
"""Frontend port of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the frontend port that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param port: Frontend port.
:type port: int
:param provisioning_state: Provisioning state of the frontend port resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayFrontendPort, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.port = kwargs.get('port', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayHeaderConfiguration(msrest.serialization.Model):
"""Header configuration of the Actions set in Application Gateway.
:param header_name: Header name of the header configuration.
:type header_name: str
:param header_value: Header value of the header configuration.
:type header_value: str
"""
_attribute_map = {
'header_name': {'key': 'headerName', 'type': 'str'},
'header_value': {'key': 'headerValue', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayHeaderConfiguration, self).__init__(**kwargs)
self.header_name = kwargs.get('header_name', None)
self.header_value = kwargs.get('header_value', None)
class ApplicationGatewayHttpListener(SubResource):
"""Http listener of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the HTTP listener that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param frontend_ip_configuration: Frontend IP configuration resource of an application gateway.
:type frontend_ip_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param frontend_port: Frontend port resource of an application gateway.
:type frontend_port: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param protocol: Protocol of the HTTP listener. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProtocol
:param host_name: Host name of HTTP listener.
:type host_name: str
:param ssl_certificate: SSL certificate resource of an application gateway.
:type ssl_certificate: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param require_server_name_indication: Applicable only if protocol is https. Enables SNI for
multi-hosting.
:type require_server_name_indication: bool
:param provisioning_state: Provisioning state of the HTTP listener resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param custom_error_configurations: Custom error configurations of the HTTP listener.
:type custom_error_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayCustomError]
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'host_name': {'key': 'properties.hostName', 'type': 'str'},
'ssl_certificate': {'key': 'properties.sslCertificate', 'type': 'SubResource'},
'require_server_name_indication': {'key': 'properties.requireServerNameIndication', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'custom_error_configurations': {'key': 'properties.customErrorConfigurations', 'type': '[ApplicationGatewayCustomError]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayHttpListener, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.protocol = kwargs.get('protocol', None)
self.host_name = kwargs.get('host_name', None)
self.ssl_certificate = kwargs.get('ssl_certificate', None)
self.require_server_name_indication = kwargs.get('require_server_name_indication', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.custom_error_configurations = kwargs.get('custom_error_configurations', None)
class ApplicationGatewayIPConfiguration(SubResource):
"""IP configuration of an application gateway. Currently 1 public and 1 private IP configuration is allowed.
:param id: Resource ID.
:type id: str
:param name: Name of the IP configuration that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param subnet: Reference of the subnet resource. A subnet from where application gateway gets
its private address.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Provisioning state of the application gateway subnet resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.subnet = kwargs.get('subnet', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayListResult(msrest.serialization.Model):
"""Response for ListApplicationGateways API service call.
:param value: List of an application gateways in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGateway]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ApplicationGatewayOnDemandProbe(msrest.serialization.Model):
"""Details of on demand test probe request.
:param protocol: The protocol used for the probe. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProtocol
:param host: Host name to send the probe to.
:type host: str
:param path: Relative path of probe. Valid path starts from '/'. Probe is sent to
:code:`<Protocol>`://:code:`<host>`::code:`<port>`:code:`<path>`.
:type path: str
:param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not
received with this timeout period. Acceptable values are from 1 second to 86400 seconds.
:type timeout: int
:param pick_host_name_from_backend_http_settings: Whether the host header should be picked from
the backend http settings. Default value is false.
:type pick_host_name_from_backend_http_settings: bool
:param match: Criterion for classifying a healthy probe response.
:type match: ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProbeHealthResponseMatch
:param backend_address_pool: Reference of backend pool of application gateway to which probe
request will be sent.
:type backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param backend_http_settings: Reference of backend http setting of application gateway to be
used for test probe.
:type backend_http_settings: ~azure.mgmt.network.v2019_04_01.models.SubResource
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'host': {'key': 'host', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'},
'timeout': {'key': 'timeout', 'type': 'int'},
'pick_host_name_from_backend_http_settings': {'key': 'pickHostNameFromBackendHttpSettings', 'type': 'bool'},
'match': {'key': 'match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'},
'backend_address_pool': {'key': 'backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'backendHttpSettings', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayOnDemandProbe, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', None)
self.host = kwargs.get('host', None)
self.path = kwargs.get('path', None)
self.timeout = kwargs.get('timeout', None)
self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None)
self.match = kwargs.get('match', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
class ApplicationGatewayPathRule(SubResource):
"""Path rule of URL path map of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the path rule that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param paths: Path rules of URL path map.
:type paths: list[str]
:param backend_address_pool: Backend address pool resource of URL path map path rule.
:type backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param backend_http_settings: Backend http settings resource of URL path map path rule.
:type backend_http_settings: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param redirect_configuration: Redirect configuration resource of URL path map path rule.
:type redirect_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param rewrite_rule_set: Rewrite rule set resource of URL path map path rule.
:type rewrite_rule_set: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Path rule of URL path map resource. Possible values are: 'Updating',
'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'paths': {'key': 'properties.paths', 'type': '[str]'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'},
'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'},
'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayPathRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.paths = kwargs.get('paths', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.redirect_configuration = kwargs.get('redirect_configuration', None)
self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayProbe(SubResource):
"""Probe of the application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the probe that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param protocol: The protocol used for the probe. Possible values include: "Http", "Https".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProtocol
:param host: Host name to send the probe to.
:type host: str
:param path: Relative path of probe. Valid path starts from '/'. Probe is sent to
:code:`<Protocol>`://:code:`<host>`::code:`<port>`:code:`<path>`.
:type path: str
:param interval: The probing interval in seconds. This is the time interval between two
consecutive probes. Acceptable values are from 1 second to 86400 seconds.
:type interval: int
:param timeout: The probe timeout in seconds. Probe marked as failed if valid response is not
received with this timeout period. Acceptable values are from 1 second to 86400 seconds.
:type timeout: int
:param unhealthy_threshold: The probe retry count. Backend server is marked down after
consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second
to 20.
:type unhealthy_threshold: int
:param pick_host_name_from_backend_http_settings: Whether the host header should be picked from
the backend http settings. Default value is false.
:type pick_host_name_from_backend_http_settings: bool
:param min_servers: Minimum number of servers that are always marked healthy. Default value is
0.
:type min_servers: int
:param match: Criterion for classifying a healthy probe response.
:type match: ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayProbeHealthResponseMatch
:param provisioning_state: Provisioning state of the backend http settings resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param port: Custom port which will be used for probing the backend servers. The valid value
ranges from 1 to 65535. In case not set, port from http settings will be used. This property is
valid for Standard_v2 and WAF_v2 only.
:type port: int
"""
_validation = {
'port': {'maximum': 65535, 'minimum': 1},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'host': {'key': 'properties.host', 'type': 'str'},
'path': {'key': 'properties.path', 'type': 'str'},
'interval': {'key': 'properties.interval', 'type': 'int'},
'timeout': {'key': 'properties.timeout', 'type': 'int'},
'unhealthy_threshold': {'key': 'properties.unhealthyThreshold', 'type': 'int'},
'pick_host_name_from_backend_http_settings': {'key': 'properties.pickHostNameFromBackendHttpSettings', 'type': 'bool'},
'min_servers': {'key': 'properties.minServers', 'type': 'int'},
'match': {'key': 'properties.match', 'type': 'ApplicationGatewayProbeHealthResponseMatch'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayProbe, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.protocol = kwargs.get('protocol', None)
self.host = kwargs.get('host', None)
self.path = kwargs.get('path', None)
self.interval = kwargs.get('interval', None)
self.timeout = kwargs.get('timeout', None)
self.unhealthy_threshold = kwargs.get('unhealthy_threshold', None)
self.pick_host_name_from_backend_http_settings = kwargs.get('pick_host_name_from_backend_http_settings', None)
self.min_servers = kwargs.get('min_servers', None)
self.match = kwargs.get('match', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.port = kwargs.get('port', None)
class ApplicationGatewayProbeHealthResponseMatch(msrest.serialization.Model):
"""Application gateway probe health response match.
:param body: Body that must be contained in the health response. Default value is empty.
:type body: str
:param status_codes: Allowed ranges of healthy status codes. Default range of healthy status
codes is 200-399.
:type status_codes: list[str]
"""
_attribute_map = {
'body': {'key': 'body', 'type': 'str'},
'status_codes': {'key': 'statusCodes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayProbeHealthResponseMatch, self).__init__(**kwargs)
self.body = kwargs.get('body', None)
self.status_codes = kwargs.get('status_codes', None)
class ApplicationGatewayRedirectConfiguration(SubResource):
"""Redirect configuration of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the redirect configuration that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param redirect_type: HTTP redirection type. Possible values include: "Permanent", "Found",
"SeeOther", "Temporary".
:type redirect_type: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRedirectType
:param target_listener: Reference to a listener to redirect the request to.
:type target_listener: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param target_url: Url to redirect the request to.
:type target_url: str
:param include_path: Include path in the redirected url.
:type include_path: bool
:param include_query_string: Include query string in the redirected url.
:type include_query_string: bool
:param request_routing_rules: Request routing specifying redirect configuration.
:type request_routing_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param url_path_maps: Url path maps specifying default redirect configuration.
:type url_path_maps: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param path_rules: Path rules specifying redirect configuration.
:type path_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'redirect_type': {'key': 'properties.redirectType', 'type': 'str'},
'target_listener': {'key': 'properties.targetListener', 'type': 'SubResource'},
'target_url': {'key': 'properties.targetUrl', 'type': 'str'},
'include_path': {'key': 'properties.includePath', 'type': 'bool'},
'include_query_string': {'key': 'properties.includeQueryString', 'type': 'bool'},
'request_routing_rules': {'key': 'properties.requestRoutingRules', 'type': '[SubResource]'},
'url_path_maps': {'key': 'properties.urlPathMaps', 'type': '[SubResource]'},
'path_rules': {'key': 'properties.pathRules', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRedirectConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.redirect_type = kwargs.get('redirect_type', None)
self.target_listener = kwargs.get('target_listener', None)
self.target_url = kwargs.get('target_url', None)
self.include_path = kwargs.get('include_path', None)
self.include_query_string = kwargs.get('include_query_string', None)
self.request_routing_rules = kwargs.get('request_routing_rules', None)
self.url_path_maps = kwargs.get('url_path_maps', None)
self.path_rules = kwargs.get('path_rules', None)
class ApplicationGatewayRequestRoutingRule(SubResource):
"""Request routing rule of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the request routing rule that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param rule_type: Rule type. Possible values include: "Basic", "PathBasedRouting".
:type rule_type: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRequestRoutingRuleType
:param backend_address_pool: Backend address pool resource of the application gateway.
:type backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param backend_http_settings: Backend http settings resource of the application gateway.
:type backend_http_settings: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param http_listener: Http listener resource of the application gateway.
:type http_listener: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param url_path_map: URL path map resource of the application gateway.
:type url_path_map: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param rewrite_rule_set: Rewrite Rule Set resource in Basic rule of the application gateway.
:type rewrite_rule_set: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param redirect_configuration: Redirect configuration resource of the application gateway.
:type redirect_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Provisioning state of the request routing rule resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'rule_type': {'key': 'properties.ruleType', 'type': 'str'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'backend_http_settings': {'key': 'properties.backendHttpSettings', 'type': 'SubResource'},
'http_listener': {'key': 'properties.httpListener', 'type': 'SubResource'},
'url_path_map': {'key': 'properties.urlPathMap', 'type': 'SubResource'},
'rewrite_rule_set': {'key': 'properties.rewriteRuleSet', 'type': 'SubResource'},
'redirect_configuration': {'key': 'properties.redirectConfiguration', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRequestRoutingRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.rule_type = kwargs.get('rule_type', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.backend_http_settings = kwargs.get('backend_http_settings', None)
self.http_listener = kwargs.get('http_listener', None)
self.url_path_map = kwargs.get('url_path_map', None)
self.rewrite_rule_set = kwargs.get('rewrite_rule_set', None)
self.redirect_configuration = kwargs.get('redirect_configuration', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayRewriteRule(msrest.serialization.Model):
"""Rewrite rule of an application gateway.
:param name: Name of the rewrite rule that is unique within an Application Gateway.
:type name: str
:param rule_sequence: Rule Sequence of the rewrite rule that determines the order of execution
of a particular rule in a RewriteRuleSet.
:type rule_sequence: int
:param conditions: Conditions based on which the action set execution will be evaluated.
:type conditions:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRewriteRuleCondition]
:param action_set: Set of actions to be done as part of the rewrite Rule.
:type action_set: ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRewriteRuleActionSet
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'rule_sequence': {'key': 'ruleSequence', 'type': 'int'},
'conditions': {'key': 'conditions', 'type': '[ApplicationGatewayRewriteRuleCondition]'},
'action_set': {'key': 'actionSet', 'type': 'ApplicationGatewayRewriteRuleActionSet'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.rule_sequence = kwargs.get('rule_sequence', None)
self.conditions = kwargs.get('conditions', None)
self.action_set = kwargs.get('action_set', None)
class ApplicationGatewayRewriteRuleActionSet(msrest.serialization.Model):
"""Set of actions in the Rewrite Rule in Application Gateway.
:param request_header_configurations: Request Header Actions in the Action Set.
:type request_header_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayHeaderConfiguration]
:param response_header_configurations: Response Header Actions in the Action Set.
:type response_header_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayHeaderConfiguration]
"""
_attribute_map = {
'request_header_configurations': {'key': 'requestHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'},
'response_header_configurations': {'key': 'responseHeaderConfigurations', 'type': '[ApplicationGatewayHeaderConfiguration]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleActionSet, self).__init__(**kwargs)
self.request_header_configurations = kwargs.get('request_header_configurations', None)
self.response_header_configurations = kwargs.get('response_header_configurations', None)
class ApplicationGatewayRewriteRuleCondition(msrest.serialization.Model):
"""Set of conditions in the Rewrite Rule in Application Gateway.
:param variable: The condition parameter of the RewriteRuleCondition.
:type variable: str
:param pattern: The pattern, either fixed string or regular expression, that evaluates the
truthfulness of the condition.
:type pattern: str
:param ignore_case: Setting this parameter to truth value with force the pattern to do a case
in-sensitive comparison.
:type ignore_case: bool
:param negate: Setting this value as truth will force to check the negation of the condition
given by the user.
:type negate: bool
"""
_attribute_map = {
'variable': {'key': 'variable', 'type': 'str'},
'pattern': {'key': 'pattern', 'type': 'str'},
'ignore_case': {'key': 'ignoreCase', 'type': 'bool'},
'negate': {'key': 'negate', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleCondition, self).__init__(**kwargs)
self.variable = kwargs.get('variable', None)
self.pattern = kwargs.get('pattern', None)
self.ignore_case = kwargs.get('ignore_case', None)
self.negate = kwargs.get('negate', None)
class ApplicationGatewayRewriteRuleSet(SubResource):
"""Rewrite rule set of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the rewrite rule set that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rewrite_rules: Rewrite rules in the rewrite rule set.
:type rewrite_rules: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayRewriteRule]
:ivar provisioning_state: Provisioning state of the rewrite rule set resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'rewrite_rules': {'key': 'properties.rewriteRules', 'type': '[ApplicationGatewayRewriteRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayRewriteRuleSet, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.rewrite_rules = kwargs.get('rewrite_rules', None)
self.provisioning_state = None
class ApplicationGatewaySku(msrest.serialization.Model):
"""SKU of an application gateway.
:param name: Name of an application gateway SKU. Possible values include: "Standard_Small",
"Standard_Medium", "Standard_Large", "WAF_Medium", "WAF_Large", "Standard_v2", "WAF_v2".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySkuName
:param tier: Tier of an application gateway. Possible values include: "Standard", "WAF",
"Standard_v2", "WAF_v2".
:type tier: str or ~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayTier
:param capacity: Capacity (instance count) of an application gateway.
:type capacity: int
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'capacity': {'key': 'capacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.capacity = kwargs.get('capacity', None)
class ApplicationGatewaySslCertificate(SubResource):
"""SSL certificates of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the SSL certificate that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param data: Base-64 encoded pfx certificate. Only applicable in PUT Request.
:type data: str
:param password: Password for the pfx file specified in data. Only applicable in PUT request.
:type password: str
:param public_cert_data: Base-64 encoded Public cert data corresponding to pfx specified in
data. Only applicable in GET request.
:type public_cert_data: str
:param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or
'Certificate' object stored in KeyVault.
:type key_vault_secret_id: str
:param provisioning_state: Provisioning state of the SSL certificate resource Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'password': {'key': 'properties.password', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.data = kwargs.get('data', None)
self.password = kwargs.get('password', None)
self.public_cert_data = kwargs.get('public_cert_data', None)
self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewaySslPolicy(msrest.serialization.Model):
"""Application Gateway Ssl policy.
:param disabled_ssl_protocols: Ssl protocols to be disabled on application gateway.
:type disabled_ssl_protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslProtocol]
:param policy_type: Type of Ssl Policy. Possible values include: "Predefined", "Custom".
:type policy_type: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslPolicyType
:param policy_name: Name of Ssl predefined policy. Possible values include:
"AppGwSslPolicy20150501", "AppGwSslPolicy20170401", "AppGwSslPolicy20170401S".
:type policy_name: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslPolicyName
:param cipher_suites: Ssl cipher suites to be enabled in the specified order to application
gateway.
:type cipher_suites: list[str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslCipherSuite]
:param min_protocol_version: Minimum version of Ssl protocol to be supported on application
gateway. Possible values include: "TLSv1_0", "TLSv1_1", "TLSv1_2".
:type min_protocol_version: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslProtocol
"""
_attribute_map = {
'disabled_ssl_protocols': {'key': 'disabledSslProtocols', 'type': '[str]'},
'policy_type': {'key': 'policyType', 'type': 'str'},
'policy_name': {'key': 'policyName', 'type': 'str'},
'cipher_suites': {'key': 'cipherSuites', 'type': '[str]'},
'min_protocol_version': {'key': 'minProtocolVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslPolicy, self).__init__(**kwargs)
self.disabled_ssl_protocols = kwargs.get('disabled_ssl_protocols', None)
self.policy_type = kwargs.get('policy_type', None)
self.policy_name = kwargs.get('policy_name', None)
self.cipher_suites = kwargs.get('cipher_suites', None)
self.min_protocol_version = kwargs.get('min_protocol_version', None)
class ApplicationGatewaySslPredefinedPolicy(SubResource):
"""An Ssl predefined policy.
:param id: Resource ID.
:type id: str
:param name: Name of the Ssl predefined policy.
:type name: str
:param cipher_suites: Ssl cipher suites to be enabled in the specified order for application
gateway.
:type cipher_suites: list[str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslCipherSuite]
:param min_protocol_version: Minimum version of Ssl protocol to be supported on application
gateway. Possible values include: "TLSv1_0", "TLSv1_1", "TLSv1_2".
:type min_protocol_version: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewaySslProtocol
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'},
'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.cipher_suites = kwargs.get('cipher_suites', None)
self.min_protocol_version = kwargs.get('min_protocol_version', None)
class ApplicationGatewayTrustedRootCertificate(SubResource):
"""Trusted Root certificates of an application gateway.
:param id: Resource ID.
:type id: str
:param name: Name of the trusted root certificate that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param data: Certificate public data.
:type data: str
:param key_vault_secret_id: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or
'Certificate' object stored in KeyVault.
:type key_vault_secret_id: str
:param provisioning_state: Provisioning state of the trusted root certificate resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'data': {'key': 'properties.data', 'type': 'str'},
'key_vault_secret_id': {'key': 'properties.keyVaultSecretId', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayTrustedRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.data = kwargs.get('data', None)
self.key_vault_secret_id = kwargs.get('key_vault_secret_id', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayUrlPathMap(SubResource):
"""UrlPathMaps give a url path to the backend mapping information for PathBasedRouting.
:param id: Resource ID.
:type id: str
:param name: Name of the URL path map that is unique within an Application Gateway.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
:param default_backend_address_pool: Default backend address pool resource of URL path map.
:type default_backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param default_backend_http_settings: Default backend http settings resource of URL path map.
:type default_backend_http_settings: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param default_rewrite_rule_set: Default Rewrite rule set resource of URL path map.
:type default_rewrite_rule_set: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param default_redirect_configuration: Default redirect configuration resource of URL path map.
:type default_redirect_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param path_rules: Path rule of URL path map resource.
:type path_rules: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayPathRule]
:param provisioning_state: Provisioning state of the backend http settings resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'},
'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'},
'default_rewrite_rule_set': {'key': 'properties.defaultRewriteRuleSet', 'type': 'SubResource'},
'default_redirect_configuration': {'key': 'properties.defaultRedirectConfiguration', 'type': 'SubResource'},
'path_rules': {'key': 'properties.pathRules', 'type': '[ApplicationGatewayPathRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayUrlPathMap, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = kwargs.get('type', None)
self.default_backend_address_pool = kwargs.get('default_backend_address_pool', None)
self.default_backend_http_settings = kwargs.get('default_backend_http_settings', None)
self.default_rewrite_rule_set = kwargs.get('default_rewrite_rule_set', None)
self.default_redirect_configuration = kwargs.get('default_redirect_configuration', None)
self.path_rules = kwargs.get('path_rules', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ApplicationGatewayWebApplicationFirewallConfiguration(msrest.serialization.Model):
"""Application gateway web application firewall configuration.
All required parameters must be populated in order to send to Azure.
:param enabled: Required. Whether the web application firewall is enabled or not.
:type enabled: bool
:param firewall_mode: Required. Web application firewall mode. Possible values include:
"Detection", "Prevention".
:type firewall_mode: str or
~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallMode
:param rule_set_type: Required. The type of the web application firewall rule set. Possible
values are: 'OWASP'.
:type rule_set_type: str
:param rule_set_version: Required. The version of the rule set type.
:type rule_set_version: str
:param disabled_rule_groups: The disabled rule groups.
:type disabled_rule_groups:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallDisabledRuleGroup]
:param request_body_check: Whether allow WAF to check request Body.
:type request_body_check: bool
:param max_request_body_size: Maximum request body size for WAF.
:type max_request_body_size: int
:param max_request_body_size_in_kb: Maximum request body size in Kb for WAF.
:type max_request_body_size_in_kb: int
:param file_upload_limit_in_mb: Maximum file upload size in Mb for WAF.
:type file_upload_limit_in_mb: int
:param exclusions: The exclusion list.
:type exclusions:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayFirewallExclusion]
"""
_validation = {
'enabled': {'required': True},
'firewall_mode': {'required': True},
'rule_set_type': {'required': True},
'rule_set_version': {'required': True},
'max_request_body_size': {'maximum': 128, 'minimum': 8},
'max_request_body_size_in_kb': {'maximum': 128, 'minimum': 8},
'file_upload_limit_in_mb': {'minimum': 0},
}
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'firewall_mode': {'key': 'firewallMode', 'type': 'str'},
'rule_set_type': {'key': 'ruleSetType', 'type': 'str'},
'rule_set_version': {'key': 'ruleSetVersion', 'type': 'str'},
'disabled_rule_groups': {'key': 'disabledRuleGroups', 'type': '[ApplicationGatewayFirewallDisabledRuleGroup]'},
'request_body_check': {'key': 'requestBodyCheck', 'type': 'bool'},
'max_request_body_size': {'key': 'maxRequestBodySize', 'type': 'int'},
'max_request_body_size_in_kb': {'key': 'maxRequestBodySizeInKb', 'type': 'int'},
'file_upload_limit_in_mb': {'key': 'fileUploadLimitInMb', 'type': 'int'},
'exclusions': {'key': 'exclusions', 'type': '[ApplicationGatewayFirewallExclusion]'},
}
def __init__(
self,
**kwargs
):
super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs)
self.enabled = kwargs['enabled']
self.firewall_mode = kwargs['firewall_mode']
self.rule_set_type = kwargs['rule_set_type']
self.rule_set_version = kwargs['rule_set_version']
self.disabled_rule_groups = kwargs.get('disabled_rule_groups', None)
self.request_body_check = kwargs.get('request_body_check', None)
self.max_request_body_size = kwargs.get('max_request_body_size', None)
self.max_request_body_size_in_kb = kwargs.get('max_request_body_size_in_kb', None)
self.file_upload_limit_in_mb = kwargs.get('file_upload_limit_in_mb', None)
self.exclusions = kwargs.get('exclusions', None)
class ApplicationSecurityGroup(Resource):
"""An application security group in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the application security group resource. It
uniquely identifies a resource, even if the user changes its name or migrate the resource
across subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the application security group resource.
Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationSecurityGroup, self).__init__(**kwargs)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
class ApplicationSecurityGroupListResult(msrest.serialization.Model):
"""A list of application security groups.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of application security groups.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ApplicationSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ApplicationSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ApplicationSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AuthorizationListResult(msrest.serialization.Model):
"""Response for ListAuthorizations API service call retrieves all authorizations that belongs to an ExpressRouteCircuit.
:param value: The authorizations in an ExpressRoute Circuit.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitAuthorization]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitAuthorization]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AuthorizationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AutoApprovedPrivateLinkService(msrest.serialization.Model):
"""The information of an AutoApprovedPrivateLinkService.
:param private_link_service: The id of the private link service resource.
:type private_link_service: str
"""
_attribute_map = {
'private_link_service': {'key': 'privateLinkService', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AutoApprovedPrivateLinkService, self).__init__(**kwargs)
self.private_link_service = kwargs.get('private_link_service', None)
class AutoApprovedPrivateLinkServicesResult(msrest.serialization.Model):
"""An array of private link service id that can be linked to a private end point with auto approved.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of auto approved private link service.
:type value: list[~azure.mgmt.network.v2019_04_01.models.AutoApprovedPrivateLinkService]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AutoApprovedPrivateLinkService]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AutoApprovedPrivateLinkServicesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class Availability(msrest.serialization.Model):
"""Availability of the metric.
:param time_grain: The time grain of the availability.
:type time_grain: str
:param retention: The retention of the availability.
:type retention: str
:param blob_duration: Duration of the availability blob.
:type blob_duration: str
"""
_attribute_map = {
'time_grain': {'key': 'timeGrain', 'type': 'str'},
'retention': {'key': 'retention', 'type': 'str'},
'blob_duration': {'key': 'blobDuration', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Availability, self).__init__(**kwargs)
self.time_grain = kwargs.get('time_grain', None)
self.retention = kwargs.get('retention', None)
self.blob_duration = kwargs.get('blob_duration', None)
class AvailableDelegation(msrest.serialization.Model):
"""The serviceName of an AvailableDelegation indicates a possible delegation for a subnet.
:param name: The name of the AvailableDelegation resource.
:type name: str
:param id: A unique identifier of the AvailableDelegation resource.
:type id: str
:param type: Resource type.
:type type: str
:param service_name: The name of the service and resource.
:type service_name: str
:param actions: Describes the actions permitted to the service upon delegation.
:type actions: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'service_name': {'key': 'serviceName', 'type': 'str'},
'actions': {'key': 'actions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AvailableDelegation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.service_name = kwargs.get('service_name', None)
self.actions = kwargs.get('actions', None)
class AvailableDelegationsResult(msrest.serialization.Model):
"""An array of available delegations.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of available delegations.
:type value: list[~azure.mgmt.network.v2019_04_01.models.AvailableDelegation]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AvailableDelegation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableDelegationsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AvailablePrivateEndpointType(msrest.serialization.Model):
"""The information of an AvailablePrivateEndpointType.
:param name: The name of the service and resource.
:type name: str
:param id: A unique identifier of the AvailablePrivateEndpoint Type resource.
:type id: str
:param type: Resource type.
:type type: str
:param resource_name: The name of the service and resource.
:type resource_name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'resource_name': {'key': 'resourceName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailablePrivateEndpointType, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.type = kwargs.get('type', None)
self.resource_name = kwargs.get('resource_name', None)
class AvailablePrivateEndpointTypesResult(msrest.serialization.Model):
"""An array of available PrivateEndpoint types.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: An array of available privateEndpoint type.
:type value: list[~azure.mgmt.network.v2019_04_01.models.AvailablePrivateEndpointType]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[AvailablePrivateEndpointType]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailablePrivateEndpointTypesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class AvailableProvidersList(msrest.serialization.Model):
"""List of available countries with details.
All required parameters must be populated in order to send to Azure.
:param countries: Required. List of available countries.
:type countries: list[~azure.mgmt.network.v2019_04_01.models.AvailableProvidersListCountry]
"""
_validation = {
'countries': {'required': True},
}
_attribute_map = {
'countries': {'key': 'countries', 'type': '[AvailableProvidersListCountry]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersList, self).__init__(**kwargs)
self.countries = kwargs['countries']
class AvailableProvidersListCity(msrest.serialization.Model):
"""City or town details.
:param city_name: The city or town name.
:type city_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
"""
_attribute_map = {
'city_name': {'key': 'cityName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListCity, self).__init__(**kwargs)
self.city_name = kwargs.get('city_name', None)
self.providers = kwargs.get('providers', None)
class AvailableProvidersListCountry(msrest.serialization.Model):
"""Country details.
:param country_name: The country name.
:type country_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
:param states: List of available states in the country.
:type states: list[~azure.mgmt.network.v2019_04_01.models.AvailableProvidersListState]
"""
_attribute_map = {
'country_name': {'key': 'countryName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
'states': {'key': 'states', 'type': '[AvailableProvidersListState]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListCountry, self).__init__(**kwargs)
self.country_name = kwargs.get('country_name', None)
self.providers = kwargs.get('providers', None)
self.states = kwargs.get('states', None)
class AvailableProvidersListParameters(msrest.serialization.Model):
"""Constraints that determine the list of available Internet service providers.
:param azure_locations: A list of Azure regions.
:type azure_locations: list[str]
:param country: The country for available providers list.
:type country: str
:param state: The state for available providers list.
:type state: str
:param city: The city or town for available providers list.
:type city: str
"""
_attribute_map = {
'azure_locations': {'key': 'azureLocations', 'type': '[str]'},
'country': {'key': 'country', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'city': {'key': 'city', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListParameters, self).__init__(**kwargs)
self.azure_locations = kwargs.get('azure_locations', None)
self.country = kwargs.get('country', None)
self.state = kwargs.get('state', None)
self.city = kwargs.get('city', None)
class AvailableProvidersListState(msrest.serialization.Model):
"""State details.
:param state_name: The state name.
:type state_name: str
:param providers: A list of Internet service providers.
:type providers: list[str]
:param cities: List of available cities or towns in the state.
:type cities: list[~azure.mgmt.network.v2019_04_01.models.AvailableProvidersListCity]
"""
_attribute_map = {
'state_name': {'key': 'stateName', 'type': 'str'},
'providers': {'key': 'providers', 'type': '[str]'},
'cities': {'key': 'cities', 'type': '[AvailableProvidersListCity]'},
}
def __init__(
self,
**kwargs
):
super(AvailableProvidersListState, self).__init__(**kwargs)
self.state_name = kwargs.get('state_name', None)
self.providers = kwargs.get('providers', None)
self.cities = kwargs.get('cities', None)
class AzureAsyncOperationResult(msrest.serialization.Model):
"""The response body contains the status of the specified asynchronous operation, indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous operation succeeded, the response body includes the HTTP status code for the successful request. If the asynchronous operation failed, the response body includes the HTTP status code for the failed request and error information regarding the failure.
:param status: Status of the Azure async operation. Possible values include: "InProgress",
"Succeeded", "Failed".
:type status: str or ~azure.mgmt.network.v2019_04_01.models.NetworkOperationStatus
:param error: Details of the error occurred during specified asynchronous operation.
:type error: ~azure.mgmt.network.v2019_04_01.models.Error
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'error': {'key': 'error', 'type': 'Error'},
}
def __init__(
self,
**kwargs
):
super(AzureAsyncOperationResult, self).__init__(**kwargs)
self.status = kwargs.get('status', None)
self.error = kwargs.get('error', None)
class AzureFirewall(Resource):
"""Azure Firewall resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param zones: A list of availability zones denoting where the resource needs to come from.
:type zones: list[str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param application_rule_collections: Collection of application rule collections used by Azure
Firewall.
:type application_rule_collections:
list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallApplicationRuleCollection]
:param nat_rule_collections: Collection of NAT rule collections used by Azure Firewall.
:type nat_rule_collections:
list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallNatRuleCollection]
:param network_rule_collections: Collection of network rule collections used by Azure Firewall.
:type network_rule_collections:
list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallNetworkRuleCollection]
:param ip_configurations: IP configuration of the Azure Firewall resource.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallIPConfiguration]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param threat_intel_mode: The operation mode for Threat Intelligence. Possible values include:
"Alert", "Deny", "Off".
:type threat_intel_mode: str or
~azure.mgmt.network.v2019_04_01.models.AzureFirewallThreatIntelMode
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'zones': {'key': 'zones', 'type': '[str]'},
'etag': {'key': 'etag', 'type': 'str'},
'application_rule_collections': {'key': 'properties.applicationRuleCollections', 'type': '[AzureFirewallApplicationRuleCollection]'},
'nat_rule_collections': {'key': 'properties.natRuleCollections', 'type': '[AzureFirewallNatRuleCollection]'},
'network_rule_collections': {'key': 'properties.networkRuleCollections', 'type': '[AzureFirewallNetworkRuleCollection]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[AzureFirewallIPConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'threat_intel_mode': {'key': 'properties.threatIntelMode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewall, self).__init__(**kwargs)
self.zones = kwargs.get('zones', None)
self.etag = None
self.application_rule_collections = kwargs.get('application_rule_collections', None)
self.nat_rule_collections = kwargs.get('nat_rule_collections', None)
self.network_rule_collections = kwargs.get('network_rule_collections', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.provisioning_state = None
self.threat_intel_mode = kwargs.get('threat_intel_mode', None)
class AzureFirewallApplicationRule(msrest.serialization.Model):
"""Properties of an application rule.
:param name: Name of the application rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param protocols: Array of ApplicationRuleProtocols.
:type protocols:
list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallApplicationRuleProtocol]
:param target_fqdns: List of FQDNs for this rule.
:type target_fqdns: list[str]
:param fqdn_tags: List of FQDN Tags for this rule.
:type fqdn_tags: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'protocols': {'key': 'protocols', 'type': '[AzureFirewallApplicationRuleProtocol]'},
'target_fqdns': {'key': 'targetFqdns', 'type': '[str]'},
'fqdn_tags': {'key': 'fqdnTags', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.protocols = kwargs.get('protocols', None)
self.target_fqdns = kwargs.get('target_fqdns', None)
self.fqdn_tags = kwargs.get('fqdn_tags', None)
class AzureFirewallApplicationRuleCollection(SubResource):
"""Application rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the application rule collection resource.
:type priority: int
:param action: The action type of a rule collection.
:type action: ~azure.mgmt.network.v2019_04_01.models.AzureFirewallRCAction
:param rules: Collection of rules used by a application rule collection.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallApplicationRule]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallApplicationRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallApplicationRuleProtocol(msrest.serialization.Model):
"""Properties of the application rule protocol.
:param protocol_type: Protocol type. Possible values include: "Http", "Https".
:type protocol_type: str or
~azure.mgmt.network.v2019_04_01.models.AzureFirewallApplicationRuleProtocolType
:param port: Port number for the protocol, cannot be greater than 64000. This field is
optional.
:type port: int
"""
_validation = {
'port': {'maximum': 64000, 'minimum': 0},
}
_attribute_map = {
'protocol_type': {'key': 'protocolType', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallApplicationRuleProtocol, self).__init__(**kwargs)
self.protocol_type = kwargs.get('protocol_type', None)
self.port = kwargs.get('port', None)
class AzureFirewallFqdnTag(Resource):
"""Azure Firewall FQDN Tag Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
:ivar fqdn_tag_name: The name of this FQDN Tag.
:vartype fqdn_tag_name: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'fqdn_tag_name': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'fqdn_tag_name': {'key': 'properties.fqdnTagName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallFqdnTag, self).__init__(**kwargs)
self.etag = None
self.provisioning_state = None
self.fqdn_tag_name = None
class AzureFirewallFqdnTagListResult(msrest.serialization.Model):
"""Response for ListAzureFirewallFqdnTags API service call.
:param value: List of Azure Firewall FQDN Tags in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallFqdnTag]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[AzureFirewallFqdnTag]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallFqdnTagListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AzureFirewallIPConfiguration(SubResource):
"""IP configuration of an Azure Firewall.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar private_ip_address: The Firewall Internal Load Balancer IP to be used as the next hop in
User Defined Routes.
:vartype private_ip_address: str
:param subnet: Reference of the subnet resource. This resource must be named
'AzureFirewallSubnet'.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param public_ip_address: Reference of the PublicIP resource. This field is a mandatory input
if subnet is not null.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'private_ip_address': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.private_ip_address = None
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
class AzureFirewallListResult(msrest.serialization.Model):
"""Response for ListAzureFirewalls API service call.
:param value: List of Azure Firewalls in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.AzureFirewall]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[AzureFirewall]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class AzureFirewallNatRCAction(msrest.serialization.Model):
"""AzureFirewall NAT Rule Collection Action.
:param type: The type of action. Possible values include: "Snat", "Dnat".
:type type: str or ~azure.mgmt.network.v2019_04_01.models.AzureFirewallNatRCActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRCAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class AzureFirewallNatRule(msrest.serialization.Model):
"""Properties of a NAT rule.
:param name: Name of the NAT rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses for this rule. Supports IP
ranges, prefixes, and service tags.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
:param protocols: Array of AzureFirewallNetworkRuleProtocols applicable to this NAT rule.
:type protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.AzureFirewallNetworkRuleProtocol]
:param translated_address: The translated address for this NAT rule.
:type translated_address: str
:param translated_port: The translated port for this NAT rule.
:type translated_port: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
'protocols': {'key': 'protocols', 'type': '[str]'},
'translated_address': {'key': 'translatedAddress', 'type': 'str'},
'translated_port': {'key': 'translatedPort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
self.protocols = kwargs.get('protocols', None)
self.translated_address = kwargs.get('translated_address', None)
self.translated_port = kwargs.get('translated_port', None)
class AzureFirewallNatRuleCollection(SubResource):
"""NAT rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the NAT rule collection resource.
:type priority: int
:param action: The action type of a NAT rule collection.
:type action: ~azure.mgmt.network.v2019_04_01.models.AzureFirewallNatRCAction
:param rules: Collection of rules used by a NAT rule collection.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallNatRule]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallNatRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNatRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNatRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallNetworkRule(msrest.serialization.Model):
"""Properties of the network rule.
:param name: Name of the network rule.
:type name: str
:param description: Description of the rule.
:type description: str
:param protocols: Array of AzureFirewallNetworkRuleProtocols.
:type protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.AzureFirewallNetworkRuleProtocol]
:param source_addresses: List of source IP addresses for this rule.
:type source_addresses: list[str]
:param destination_addresses: List of destination IP addresses.
:type destination_addresses: list[str]
:param destination_ports: List of destination ports.
:type destination_ports: list[str]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'protocols': {'key': 'protocols', 'type': '[str]'},
'source_addresses': {'key': 'sourceAddresses', 'type': '[str]'},
'destination_addresses': {'key': 'destinationAddresses', 'type': '[str]'},
'destination_ports': {'key': 'destinationPorts', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNetworkRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.description = kwargs.get('description', None)
self.protocols = kwargs.get('protocols', None)
self.source_addresses = kwargs.get('source_addresses', None)
self.destination_addresses = kwargs.get('destination_addresses', None)
self.destination_ports = kwargs.get('destination_ports', None)
class AzureFirewallNetworkRuleCollection(SubResource):
"""Network rule collection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Priority of the network rule collection resource.
:type priority: int
:param action: The action type of a rule collection.
:type action: ~azure.mgmt.network.v2019_04_01.models.AzureFirewallRCAction
:param rules: Collection of rules used by a network rule collection.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.AzureFirewallNetworkRule]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'priority': {'maximum': 65000, 'minimum': 100},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'},
'rules': {'key': 'properties.rules', 'type': '[AzureFirewallNetworkRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallNetworkRuleCollection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs.get('priority', None)
self.action = kwargs.get('action', None)
self.rules = kwargs.get('rules', None)
self.provisioning_state = None
class AzureFirewallRCAction(msrest.serialization.Model):
"""Properties of the AzureFirewallRCAction.
:param type: The type of action. Possible values include: "Allow", "Deny".
:type type: str or ~azure.mgmt.network.v2019_04_01.models.AzureFirewallRCActionType
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureFirewallRCAction, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
class AzureReachabilityReport(msrest.serialization.Model):
"""Azure reachability report details.
All required parameters must be populated in order to send to Azure.
:param aggregation_level: Required. The aggregation level of Azure reachability report. Can be
Country, State or City.
:type aggregation_level: str
:param provider_location: Required. Parameters that define a geographic location.
:type provider_location: ~azure.mgmt.network.v2019_04_01.models.AzureReachabilityReportLocation
:param reachability_report: Required. List of Azure reachability report items.
:type reachability_report:
list[~azure.mgmt.network.v2019_04_01.models.AzureReachabilityReportItem]
"""
_validation = {
'aggregation_level': {'required': True},
'provider_location': {'required': True},
'reachability_report': {'required': True},
}
_attribute_map = {
'aggregation_level': {'key': 'aggregationLevel', 'type': 'str'},
'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'},
'reachability_report': {'key': 'reachabilityReport', 'type': '[AzureReachabilityReportItem]'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReport, self).__init__(**kwargs)
self.aggregation_level = kwargs['aggregation_level']
self.provider_location = kwargs['provider_location']
self.reachability_report = kwargs['reachability_report']
class AzureReachabilityReportItem(msrest.serialization.Model):
"""Azure reachability report details for a given provider location.
:param provider: The Internet service provider.
:type provider: str
:param azure_location: The Azure region.
:type azure_location: str
:param latencies: List of latency details for each of the time series.
:type latencies:
list[~azure.mgmt.network.v2019_04_01.models.AzureReachabilityReportLatencyInfo]
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'azure_location': {'key': 'azureLocation', 'type': 'str'},
'latencies': {'key': 'latencies', 'type': '[AzureReachabilityReportLatencyInfo]'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportItem, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.azure_location = kwargs.get('azure_location', None)
self.latencies = kwargs.get('latencies', None)
class AzureReachabilityReportLatencyInfo(msrest.serialization.Model):
"""Details on latency for a time series.
:param time_stamp: The time stamp.
:type time_stamp: ~datetime.datetime
:param score: The relative latency score between 1 and 100, higher values indicating a faster
connection.
:type score: int
"""
_validation = {
'score': {'maximum': 100, 'minimum': 1},
}
_attribute_map = {
'time_stamp': {'key': 'timeStamp', 'type': 'iso-8601'},
'score': {'key': 'score', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportLatencyInfo, self).__init__(**kwargs)
self.time_stamp = kwargs.get('time_stamp', None)
self.score = kwargs.get('score', None)
class AzureReachabilityReportLocation(msrest.serialization.Model):
"""Parameters that define a geographic location.
All required parameters must be populated in order to send to Azure.
:param country: Required. The name of the country.
:type country: str
:param state: The name of the state.
:type state: str
:param city: The name of the city or town.
:type city: str
"""
_validation = {
'country': {'required': True},
}
_attribute_map = {
'country': {'key': 'country', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'city': {'key': 'city', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportLocation, self).__init__(**kwargs)
self.country = kwargs['country']
self.state = kwargs.get('state', None)
self.city = kwargs.get('city', None)
class AzureReachabilityReportParameters(msrest.serialization.Model):
"""Geographic and time constraints for Azure reachability report.
All required parameters must be populated in order to send to Azure.
:param provider_location: Required. Parameters that define a geographic location.
:type provider_location: ~azure.mgmt.network.v2019_04_01.models.AzureReachabilityReportLocation
:param providers: List of Internet service providers.
:type providers: list[str]
:param azure_locations: Optional Azure regions to scope the query to.
:type azure_locations: list[str]
:param start_time: Required. The start time for the Azure reachability report.
:type start_time: ~datetime.datetime
:param end_time: Required. The end time for the Azure reachability report.
:type end_time: ~datetime.datetime
"""
_validation = {
'provider_location': {'required': True},
'start_time': {'required': True},
'end_time': {'required': True},
}
_attribute_map = {
'provider_location': {'key': 'providerLocation', 'type': 'AzureReachabilityReportLocation'},
'providers': {'key': 'providers', 'type': '[str]'},
'azure_locations': {'key': 'azureLocations', 'type': '[str]'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
}
def __init__(
self,
**kwargs
):
super(AzureReachabilityReportParameters, self).__init__(**kwargs)
self.provider_location = kwargs['provider_location']
self.providers = kwargs.get('providers', None)
self.azure_locations = kwargs.get('azure_locations', None)
self.start_time = kwargs['start_time']
self.end_time = kwargs['end_time']
class BackendAddressPool(SubResource):
"""Pool of backend IP addresses.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar backend_ip_configurations: Gets collection of references to IP addresses defined in
network interfaces.
:vartype backend_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration]
:ivar load_balancing_rules: Gets load balancing rules that use this backend address pool.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar outbound_rule: Gets outbound rules that use this backend address pool.
:vartype outbound_rule: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar outbound_rules: Gets outbound rules that use this backend address pool.
:vartype outbound_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param provisioning_state: Get provisioning state of the public IP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'backend_ip_configurations': {'readonly': True},
'load_balancing_rules': {'readonly': True},
'outbound_rule': {'readonly': True},
'outbound_rules': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'outbound_rule': {'key': 'properties.outboundRule', 'type': 'SubResource'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BackendAddressPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.backend_ip_configurations = None
self.load_balancing_rules = None
self.outbound_rule = None
self.outbound_rules = None
self.provisioning_state = kwargs.get('provisioning_state', None)
class BastionHost(Resource):
"""Bastion Host resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param ip_configurations: IP configuration of the Bastion Host resource.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.BastionHostIPConfiguration]
:param dns_name: FQDN for the endpoint on which bastion host is accessible.
:type dns_name: str
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[BastionHostIPConfiguration]'},
'dns_name': {'key': 'properties.dnsName', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHost, self).__init__(**kwargs)
self.etag = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.dns_name = kwargs.get('dns_name', None)
self.provisioning_state = None
class BastionHostIPConfiguration(SubResource):
"""IP configuration of an Bastion Host.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Ip configuration type.
:vartype type: str
:param subnet: Reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param public_ip_address: Reference of the PublicIP resource.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param private_ip_allocation_method: Private IP allocation method. Possible values include:
"Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHostIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
class BastionHostListResult(msrest.serialization.Model):
"""Response for ListBastionHosts API service call.
:param value: List of Bastion Hosts in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.BastionHost]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BastionHost]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BastionHostListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BGPCommunity(msrest.serialization.Model):
"""Contains bgp community information offered in Service Community resources.
:param service_supported_region: The region which the service support. e.g. For O365, region is
Global.
:type service_supported_region: str
:param community_name: The name of the bgp community. e.g. Skype.
:type community_name: str
:param community_value: The value of the bgp community. For more information:
https://docs.microsoft.com/en-us/azure/expressroute/expressroute-routing.
:type community_value: str
:param community_prefixes: The prefixes that the bgp community contains.
:type community_prefixes: list[str]
:param is_authorized_to_use: Customer is authorized to use bgp community or not.
:type is_authorized_to_use: bool
:param service_group: The service group of the bgp community contains.
:type service_group: str
"""
_attribute_map = {
'service_supported_region': {'key': 'serviceSupportedRegion', 'type': 'str'},
'community_name': {'key': 'communityName', 'type': 'str'},
'community_value': {'key': 'communityValue', 'type': 'str'},
'community_prefixes': {'key': 'communityPrefixes', 'type': '[str]'},
'is_authorized_to_use': {'key': 'isAuthorizedToUse', 'type': 'bool'},
'service_group': {'key': 'serviceGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BGPCommunity, self).__init__(**kwargs)
self.service_supported_region = kwargs.get('service_supported_region', None)
self.community_name = kwargs.get('community_name', None)
self.community_value = kwargs.get('community_value', None)
self.community_prefixes = kwargs.get('community_prefixes', None)
self.is_authorized_to_use = kwargs.get('is_authorized_to_use', None)
self.service_group = kwargs.get('service_group', None)
class BgpPeerStatus(msrest.serialization.Model):
"""BGP peer status details.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar local_address: The virtual network gateway's local address.
:vartype local_address: str
:ivar neighbor: The remote BGP peer.
:vartype neighbor: str
:ivar asn: The autonomous system number of the remote BGP peer.
:vartype asn: int
:ivar state: The BGP peer state. Possible values include: "Unknown", "Stopped", "Idle",
"Connecting", "Connected".
:vartype state: str or ~azure.mgmt.network.v2019_04_01.models.BgpPeerState
:ivar connected_duration: For how long the peering has been up.
:vartype connected_duration: str
:ivar routes_received: The number of routes learned from this peer.
:vartype routes_received: long
:ivar messages_sent: The number of BGP messages sent.
:vartype messages_sent: long
:ivar messages_received: The number of BGP messages received.
:vartype messages_received: long
"""
_validation = {
'local_address': {'readonly': True},
'neighbor': {'readonly': True},
'asn': {'readonly': True},
'state': {'readonly': True},
'connected_duration': {'readonly': True},
'routes_received': {'readonly': True},
'messages_sent': {'readonly': True},
'messages_received': {'readonly': True},
}
_attribute_map = {
'local_address': {'key': 'localAddress', 'type': 'str'},
'neighbor': {'key': 'neighbor', 'type': 'str'},
'asn': {'key': 'asn', 'type': 'int'},
'state': {'key': 'state', 'type': 'str'},
'connected_duration': {'key': 'connectedDuration', 'type': 'str'},
'routes_received': {'key': 'routesReceived', 'type': 'long'},
'messages_sent': {'key': 'messagesSent', 'type': 'long'},
'messages_received': {'key': 'messagesReceived', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(BgpPeerStatus, self).__init__(**kwargs)
self.local_address = None
self.neighbor = None
self.asn = None
self.state = None
self.connected_duration = None
self.routes_received = None
self.messages_sent = None
self.messages_received = None
class BgpPeerStatusListResult(msrest.serialization.Model):
"""Response for list BGP peer status API service call.
:param value: List of BGP peers.
:type value: list[~azure.mgmt.network.v2019_04_01.models.BgpPeerStatus]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BgpPeerStatus]'},
}
def __init__(
self,
**kwargs
):
super(BgpPeerStatusListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class BgpServiceCommunity(Resource):
"""Service Community Properties.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param service_name: The name of the bgp community. e.g. Skype.
:type service_name: str
:param bgp_communities: Get a list of bgp communities.
:type bgp_communities: list[~azure.mgmt.network.v2019_04_01.models.BGPCommunity]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'service_name': {'key': 'properties.serviceName', 'type': 'str'},
'bgp_communities': {'key': 'properties.bgpCommunities', 'type': '[BGPCommunity]'},
}
def __init__(
self,
**kwargs
):
super(BgpServiceCommunity, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.bgp_communities = kwargs.get('bgp_communities', None)
class BgpServiceCommunityListResult(msrest.serialization.Model):
"""Response for the ListServiceCommunity API service call.
:param value: A list of service community resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.BgpServiceCommunity]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[BgpServiceCommunity]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(BgpServiceCommunityListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class BgpSettings(msrest.serialization.Model):
"""BGP settings details.
:param asn: The BGP speaker's ASN.
:type asn: long
:param bgp_peering_address: The BGP peering address and BGP identifier of this BGP speaker.
:type bgp_peering_address: str
:param peer_weight: The weight added to routes learned from this BGP speaker.
:type peer_weight: int
"""
_attribute_map = {
'asn': {'key': 'asn', 'type': 'long'},
'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
'peer_weight': {'key': 'peerWeight', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(BgpSettings, self).__init__(**kwargs)
self.asn = kwargs.get('asn', None)
self.bgp_peering_address = kwargs.get('bgp_peering_address', None)
self.peer_weight = kwargs.get('peer_weight', None)
class CheckPrivateLinkServiceVisibilityRequest(msrest.serialization.Model):
"""Request body of the CheckPrivateLinkServiceVisibility API service call.
:param private_link_service_alias: The alias of the private link service.
:type private_link_service_alias: str
"""
_attribute_map = {
'private_link_service_alias': {'key': 'privateLinkServiceAlias', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(CheckPrivateLinkServiceVisibilityRequest, self).__init__(**kwargs)
self.private_link_service_alias = kwargs.get('private_link_service_alias', None)
class CloudErrorBody(msrest.serialization.Model):
"""An error response from the Batch service.
:param code: An identifier for the error. Codes are invariant and are intended to be consumed
programmatically.
:type code: str
:param message: A message describing the error, intended to be suitable for display in a user
interface.
:type message: str
:param target: The target of the particular error. For example, the name of the property in
error.
:type target: str
:param details: A list of additional details about the error.
:type details: list[~azure.mgmt.network.v2019_04_01.models.CloudErrorBody]
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[CloudErrorBody]'},
}
def __init__(
self,
**kwargs
):
super(CloudErrorBody, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.message = kwargs.get('message', None)
self.target = kwargs.get('target', None)
self.details = kwargs.get('details', None)
class Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties(msrest.serialization.Model):
"""Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of user assigned identity.
:vartype principal_id: str
:ivar client_id: The client id of user assigned identity.
:vartype client_id: str
"""
_validation = {
'principal_id': {'readonly': True},
'client_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'client_id': {'key': 'clientId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties, self).__init__(**kwargs)
self.principal_id = None
self.client_id = None
class ConnectionMonitor(msrest.serialization.Model):
"""Parameters that define the operation to create a connection monitor.
All required parameters must be populated in order to send to Azure.
:param location: Connection monitor location.
:type location: str
:param tags: A set of tags. Connection monitor tags.
:type tags: dict[str, str]
:param source: Required. Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSource
:param destination: Required. Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
}
_attribute_map = {
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'properties.autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitor, self).__init__(**kwargs)
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.source = kwargs['source']
self.destination = kwargs['destination']
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
class ConnectionMonitorDestination(msrest.serialization.Model):
"""Describes the destination of connection monitor.
:param resource_id: The ID of the resource used as the destination by connection monitor.
:type resource_id: str
:param address: Address of the connection monitor destination (IP or domain name).
:type address: str
:param port: The destination port used by connection monitor.
:type port: int
"""
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorDestination, self).__init__(**kwargs)
self.resource_id = kwargs.get('resource_id', None)
self.address = kwargs.get('address', None)
self.port = kwargs.get('port', None)
class ConnectionMonitorListResult(msrest.serialization.Model):
"""List of connection monitors.
:param value: Information about connection monitors.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorResult]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConnectionMonitorResult]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConnectionMonitorParameters(msrest.serialization.Model):
"""Parameters that define the operation to create a connection monitor.
All required parameters must be populated in order to send to Azure.
:param source: Required. Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSource
:param destination: Required. Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorParameters, self).__init__(**kwargs)
self.source = kwargs['source']
self.destination = kwargs['destination']
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
class ConnectionMonitorQueryResult(msrest.serialization.Model):
"""List of connection states snapshots.
:param source_status: Status of connection monitor source. Possible values include: "Unknown",
"Active", "Inactive".
:type source_status: str or
~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSourceStatus
:param states: Information about connection states.
:type states: list[~azure.mgmt.network.v2019_04_01.models.ConnectionStateSnapshot]
"""
_attribute_map = {
'source_status': {'key': 'sourceStatus', 'type': 'str'},
'states': {'key': 'states', 'type': '[ConnectionStateSnapshot]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorQueryResult, self).__init__(**kwargs)
self.source_status = kwargs.get('source_status', None)
self.states = kwargs.get('states', None)
class ConnectionMonitorResult(msrest.serialization.Model):
"""Information about the connection monitor.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the connection monitor.
:vartype name: str
:ivar id: ID of the connection monitor.
:vartype id: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar type: Connection monitor type.
:vartype type: str
:param location: Connection monitor location.
:type location: str
:param tags: A set of tags. Connection monitor tags.
:type tags: dict[str, str]
:param source: Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSource
:param destination: Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:ivar provisioning_state: The provisioning state of the connection monitor. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param start_time: The date and time when the connection monitor was started.
:type start_time: ~datetime.datetime
:param monitoring_status: The monitoring status of the connection monitor.
:type monitoring_status: str
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'properties.autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},
'monitoring_status': {'key': 'properties.monitoringStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.etag = kwargs.get('etag', "A unique read-only string that changes whenever the resource is updated.")
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.source = kwargs.get('source', None)
self.destination = kwargs.get('destination', None)
self.auto_start = kwargs.get('auto_start', True)
self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60)
self.provisioning_state = None
self.start_time = kwargs.get('start_time', None)
self.monitoring_status = kwargs.get('monitoring_status', None)
class ConnectionMonitorResultProperties(ConnectionMonitorParameters):
"""Describes the properties of a connection monitor.
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 source: Required. Describes the source of connection monitor.
:type source: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSource
:param destination: Required. Describes the destination of connection monitor.
:type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorDestination
:param auto_start: Determines if the connection monitor will start automatically once created.
:type auto_start: bool
:param monitoring_interval_in_seconds: Monitoring interval in seconds.
:type monitoring_interval_in_seconds: int
:ivar provisioning_state: The provisioning state of the connection monitor. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param start_time: The date and time when the connection monitor was started.
:type start_time: ~datetime.datetime
:param monitoring_status: The monitoring status of the connection monitor.
:type monitoring_status: str
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectionMonitorSource'},
'destination': {'key': 'destination', 'type': 'ConnectionMonitorDestination'},
'auto_start': {'key': 'autoStart', 'type': 'bool'},
'monitoring_interval_in_seconds': {'key': 'monitoringIntervalInSeconds', 'type': 'int'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'monitoring_status': {'key': 'monitoringStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorResultProperties, self).__init__(**kwargs)
self.provisioning_state = None
self.start_time = kwargs.get('start_time', None)
self.monitoring_status = kwargs.get('monitoring_status', None)
class ConnectionMonitorSource(msrest.serialization.Model):
"""Describes the source of connection monitor.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource used as the source by connection monitor.
:type resource_id: str
:param port: The source port used by connection monitor.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionMonitorSource, self).__init__(**kwargs)
self.resource_id = kwargs['resource_id']
self.port = kwargs.get('port', None)
class ConnectionResetSharedKey(msrest.serialization.Model):
"""The virtual network connection reset shared key.
All required parameters must be populated in order to send to Azure.
:param key_length: Required. The virtual network connection reset shared key length, should
between 1 and 128.
:type key_length: int
"""
_validation = {
'key_length': {'required': True, 'maximum': 128, 'minimum': 1},
}
_attribute_map = {
'key_length': {'key': 'keyLength', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectionResetSharedKey, self).__init__(**kwargs)
self.key_length = kwargs['key_length']
class ConnectionSharedKey(SubResource):
"""Response for GetConnectionSharedKey API service call.
All required parameters must be populated in order to send to Azure.
:param id: Resource ID.
:type id: str
:param value: Required. The virtual network connection shared key value.
:type value: str
"""
_validation = {
'value': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConnectionSharedKey, self).__init__(**kwargs)
self.value = kwargs['value']
class ConnectionStateSnapshot(msrest.serialization.Model):
"""Connection state snapshot.
Variables are only populated by the server, and will be ignored when sending a request.
:param connection_state: The connection state. Possible values include: "Reachable",
"Unreachable", "Unknown".
:type connection_state: str or ~azure.mgmt.network.v2019_04_01.models.ConnectionState
:param start_time: The start time of the connection snapshot.
:type start_time: ~datetime.datetime
:param end_time: The end time of the connection snapshot.
:type end_time: ~datetime.datetime
:param evaluation_state: Connectivity analysis evaluation state. Possible values include:
"NotStarted", "InProgress", "Completed".
:type evaluation_state: str or ~azure.mgmt.network.v2019_04_01.models.EvaluationState
:param avg_latency_in_ms: Average latency in ms.
:type avg_latency_in_ms: int
:param min_latency_in_ms: Minimum latency in ms.
:type min_latency_in_ms: int
:param max_latency_in_ms: Maximum latency in ms.
:type max_latency_in_ms: int
:param probes_sent: The number of sent probes.
:type probes_sent: int
:param probes_failed: The number of failed probes.
:type probes_failed: int
:ivar hops: List of hops between the source and the destination.
:vartype hops: list[~azure.mgmt.network.v2019_04_01.models.ConnectivityHop]
"""
_validation = {
'hops': {'readonly': True},
}
_attribute_map = {
'connection_state': {'key': 'connectionState', 'type': 'str'},
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'evaluation_state': {'key': 'evaluationState', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
}
def __init__(
self,
**kwargs
):
super(ConnectionStateSnapshot, self).__init__(**kwargs)
self.connection_state = kwargs.get('connection_state', None)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
self.evaluation_state = kwargs.get('evaluation_state', None)
self.avg_latency_in_ms = kwargs.get('avg_latency_in_ms', None)
self.min_latency_in_ms = kwargs.get('min_latency_in_ms', None)
self.max_latency_in_ms = kwargs.get('max_latency_in_ms', None)
self.probes_sent = kwargs.get('probes_sent', None)
self.probes_failed = kwargs.get('probes_failed', None)
self.hops = None
class ConnectivityDestination(msrest.serialization.Model):
"""Parameters that define destination of connection.
:param resource_id: The ID of the resource to which a connection attempt will be made.
:type resource_id: str
:param address: The IP address or URI the resource to which a connection attempt will be made.
:type address: str
:param port: Port on which check connectivity will be performed.
:type port: int
"""
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityDestination, self).__init__(**kwargs)
self.resource_id = kwargs.get('resource_id', None)
self.address = kwargs.get('address', None)
self.port = kwargs.get('port', None)
class ConnectivityHop(msrest.serialization.Model):
"""Information about a hop between the source and the destination.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The type of the hop.
:vartype type: str
:ivar id: The ID of the hop.
:vartype id: str
:ivar address: The IP address of the hop.
:vartype address: str
:ivar resource_id: The ID of the resource corresponding to this hop.
:vartype resource_id: str
:ivar next_hop_ids: List of next hop identifiers.
:vartype next_hop_ids: list[str]
:ivar issues: List of issues.
:vartype issues: list[~azure.mgmt.network.v2019_04_01.models.ConnectivityIssue]
"""
_validation = {
'type': {'readonly': True},
'id': {'readonly': True},
'address': {'readonly': True},
'resource_id': {'readonly': True},
'next_hop_ids': {'readonly': True},
'issues': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'address': {'key': 'address', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'next_hop_ids': {'key': 'nextHopIds', 'type': '[str]'},
'issues': {'key': 'issues', 'type': '[ConnectivityIssue]'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityHop, self).__init__(**kwargs)
self.type = None
self.id = None
self.address = None
self.resource_id = None
self.next_hop_ids = None
self.issues = None
class ConnectivityInformation(msrest.serialization.Model):
"""Information on the connectivity status.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar hops: List of hops between the source and the destination.
:vartype hops: list[~azure.mgmt.network.v2019_04_01.models.ConnectivityHop]
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connected", "Disconnected", "Degraded".
:vartype connection_status: str or ~azure.mgmt.network.v2019_04_01.models.ConnectionStatus
:ivar avg_latency_in_ms: Average latency in milliseconds.
:vartype avg_latency_in_ms: int
:ivar min_latency_in_ms: Minimum latency in milliseconds.
:vartype min_latency_in_ms: int
:ivar max_latency_in_ms: Maximum latency in milliseconds.
:vartype max_latency_in_ms: int
:ivar probes_sent: Total number of probes sent.
:vartype probes_sent: int
:ivar probes_failed: Number of failed probes.
:vartype probes_failed: int
"""
_validation = {
'hops': {'readonly': True},
'connection_status': {'readonly': True},
'avg_latency_in_ms': {'readonly': True},
'min_latency_in_ms': {'readonly': True},
'max_latency_in_ms': {'readonly': True},
'probes_sent': {'readonly': True},
'probes_failed': {'readonly': True},
}
_attribute_map = {
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityInformation, self).__init__(**kwargs)
self.hops = None
self.connection_status = None
self.avg_latency_in_ms = None
self.min_latency_in_ms = None
self.max_latency_in_ms = None
self.probes_sent = None
self.probes_failed = None
class ConnectivityIssue(msrest.serialization.Model):
"""Information about an issue encountered in the process of checking for connectivity.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar origin: The origin of the issue. Possible values include: "Local", "Inbound", "Outbound".
:vartype origin: str or ~azure.mgmt.network.v2019_04_01.models.Origin
:ivar severity: The severity of the issue. Possible values include: "Error", "Warning".
:vartype severity: str or ~azure.mgmt.network.v2019_04_01.models.Severity
:ivar type: The type of issue. Possible values include: "Unknown", "AgentStopped",
"GuestFirewall", "DnsResolution", "SocketBind", "NetworkSecurityRule", "UserDefinedRoute",
"PortThrottled", "Platform".
:vartype type: str or ~azure.mgmt.network.v2019_04_01.models.IssueType
:ivar context: Provides additional context on the issue.
:vartype context: list[dict[str, str]]
"""
_validation = {
'origin': {'readonly': True},
'severity': {'readonly': True},
'type': {'readonly': True},
'context': {'readonly': True},
}
_attribute_map = {
'origin': {'key': 'origin', 'type': 'str'},
'severity': {'key': 'severity', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'context': {'key': 'context', 'type': '[{str}]'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityIssue, self).__init__(**kwargs)
self.origin = None
self.severity = None
self.type = None
self.context = None
class ConnectivityParameters(msrest.serialization.Model):
"""Parameters that determine how the connectivity check will be performed.
All required parameters must be populated in order to send to Azure.
:param source: Required. Describes the source of the connection.
:type source: ~azure.mgmt.network.v2019_04_01.models.ConnectivitySource
:param destination: Required. Describes the destination of connection.
:type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectivityDestination
:param protocol: Network protocol. Possible values include: "Tcp", "Http", "Https", "Icmp".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.Protocol
:param protocol_configuration: Configuration of the protocol.
:type protocol_configuration: ~azure.mgmt.network.v2019_04_01.models.ProtocolConfiguration
"""
_validation = {
'source': {'required': True},
'destination': {'required': True},
}
_attribute_map = {
'source': {'key': 'source', 'type': 'ConnectivitySource'},
'destination': {'key': 'destination', 'type': 'ConnectivityDestination'},
'protocol': {'key': 'protocol', 'type': 'str'},
'protocol_configuration': {'key': 'protocolConfiguration', 'type': 'ProtocolConfiguration'},
}
def __init__(
self,
**kwargs
):
super(ConnectivityParameters, self).__init__(**kwargs)
self.source = kwargs['source']
self.destination = kwargs['destination']
self.protocol = kwargs.get('protocol', None)
self.protocol_configuration = kwargs.get('protocol_configuration', None)
class ConnectivitySource(msrest.serialization.Model):
"""Parameters that define the source of the connection.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource from which a connectivity check will be
initiated.
:type resource_id: str
:param port: The source port from which a connectivity check will be performed.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = kwargs['resource_id']
self.port = kwargs.get('port', None)
class Container(SubResource):
"""Reference to container resource in remote resource provider.
:param id: Resource ID.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Container, self).__init__(**kwargs)
class ContainerNetworkInterface(SubResource):
"""Container network interface child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param container_network_interface_configuration: Container network interface configuration
from which this container network interface is created.
:type container_network_interface_configuration:
~azure.mgmt.network.v2019_04_01.models.ContainerNetworkInterfaceConfiguration
:param container: Reference to the container to which this container network interface is
attached.
:type container: ~azure.mgmt.network.v2019_04_01.models.Container
:param ip_configurations: Reference to the ip configuration on this container nic.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ContainerNetworkInterfaceIpConfiguration]
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'container_network_interface_configuration': {'key': 'properties.containerNetworkInterfaceConfiguration', 'type': 'ContainerNetworkInterfaceConfiguration'},
'container': {'key': 'properties.container', 'type': 'Container'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[ContainerNetworkInterfaceIpConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterface, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = kwargs.get('etag', None)
self.container_network_interface_configuration = kwargs.get('container_network_interface_configuration', None)
self.container = kwargs.get('container', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.provisioning_state = None
class ContainerNetworkInterfaceConfiguration(SubResource):
"""Container network interface configuration child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param ip_configurations: A list of ip configurations of the container network interface
configuration.
:type ip_configurations: list[~azure.mgmt.network.v2019_04_01.models.IPConfigurationProfile]
:param container_network_interfaces: A list of container network interfaces created from this
container network interface configuration.
:type container_network_interfaces: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfigurationProfile]'},
'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterfaceConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = kwargs.get('etag', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.container_network_interfaces = kwargs.get('container_network_interfaces', None)
self.provisioning_state = None
class ContainerNetworkInterfaceIpConfiguration(msrest.serialization.Model):
"""The ip configuration for a container network interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ContainerNetworkInterfaceIpConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = kwargs.get('etag', None)
self.provisioning_state = None
class DdosCustomPolicy(Resource):
"""A DDoS custom policy in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the DDoS custom policy resource. It uniquely
identifies the resource, even if the user changes its name or migrate the resource across
subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the DDoS custom policy resource. Possible
values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:ivar public_ip_addresses: The list of public IPs associated with the DDoS custom policy
resource. This list is read-only.
:vartype public_ip_addresses: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param protocol_custom_settings: The protocol-specific DDoS policy customization parameters.
:type protocol_custom_settings:
list[~azure.mgmt.network.v2019_04_01.models.ProtocolCustomSettingsFormat]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
'public_ip_addresses': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[SubResource]'},
'protocol_custom_settings': {'key': 'properties.protocolCustomSettings', 'type': '[ProtocolCustomSettingsFormat]'},
}
def __init__(
self,
**kwargs
):
super(DdosCustomPolicy, self).__init__(**kwargs)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
self.public_ip_addresses = None
self.protocol_custom_settings = kwargs.get('protocol_custom_settings', None)
class DdosProtectionPlan(msrest.serialization.Model):
"""A DDoS protection plan in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource ID.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the DDoS protection plan resource. It
uniquely identifies the resource, even if the user changes its name or migrate the resource
across subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the DDoS protection plan resource. Possible
values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:ivar virtual_networks: The list of virtual networks associated with the DDoS protection plan
resource. This list is read-only.
:vartype virtual_networks: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
'virtual_networks': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'virtual_networks': {'key': 'properties.virtualNetworks', 'type': '[SubResource]'},
}
def __init__(
self,
**kwargs
):
super(DdosProtectionPlan, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
self.location = kwargs.get('location', None)
self.tags = kwargs.get('tags', None)
self.etag = None
self.resource_guid = None
self.provisioning_state = None
self.virtual_networks = None
class DdosProtectionPlanListResult(msrest.serialization.Model):
"""A list of DDoS protection plans.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of DDoS protection plans.
:type value: list[~azure.mgmt.network.v2019_04_01.models.DdosProtectionPlan]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[DdosProtectionPlan]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DdosProtectionPlanListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class DdosSettings(msrest.serialization.Model):
"""Contains the DDoS protection settings of the public IP.
:param ddos_custom_policy: The DDoS custom policy associated with the public IP.
:type ddos_custom_policy: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param protection_coverage: The DDoS protection policy customizability of the public IP. Only
standard coverage will have the ability to be customized. Possible values include: "Basic",
"Standard".
:type protection_coverage: str or
~azure.mgmt.network.v2019_04_01.models.DdosSettingsProtectionCoverage
"""
_attribute_map = {
'ddos_custom_policy': {'key': 'ddosCustomPolicy', 'type': 'SubResource'},
'protection_coverage': {'key': 'protectionCoverage', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(DdosSettings, self).__init__(**kwargs)
self.ddos_custom_policy = kwargs.get('ddos_custom_policy', None)
self.protection_coverage = kwargs.get('protection_coverage', None)
class Delegation(SubResource):
"""Details the service to which the subnet is delegated.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a subnet. This name can be used to
access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param service_name: The name of the service to whom the subnet should be delegated (e.g.
Microsoft.Sql/servers).
:type service_name: str
:param actions: Describes the actions permitted to the service upon delegation.
:type actions: list[str]
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'service_name': {'key': 'properties.serviceName', 'type': 'str'},
'actions': {'key': 'properties.actions', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Delegation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.service_name = kwargs.get('service_name', None)
self.actions = kwargs.get('actions', None)
self.provisioning_state = None
class DeviceProperties(msrest.serialization.Model):
"""List of properties of the device.
:param device_vendor: Name of the device Vendor.
:type device_vendor: str
:param device_model: Model of the device.
:type device_model: str
:param link_speed_in_mbps: Link speed.
:type link_speed_in_mbps: int
"""
_attribute_map = {
'device_vendor': {'key': 'deviceVendor', 'type': 'str'},
'device_model': {'key': 'deviceModel', 'type': 'str'},
'link_speed_in_mbps': {'key': 'linkSpeedInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(DeviceProperties, self).__init__(**kwargs)
self.device_vendor = kwargs.get('device_vendor', None)
self.device_model = kwargs.get('device_model', None)
self.link_speed_in_mbps = kwargs.get('link_speed_in_mbps', None)
class DhcpOptions(msrest.serialization.Model):
"""DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network. Standard DHCP option for a subnet overrides VNET DHCP options.
:param dns_servers: The list of DNS servers IP addresses.
:type dns_servers: list[str]
"""
_attribute_map = {
'dns_servers': {'key': 'dnsServers', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(DhcpOptions, self).__init__(**kwargs)
self.dns_servers = kwargs.get('dns_servers', None)
class Dimension(msrest.serialization.Model):
"""Dimension of the metric.
:param name: The name of the dimension.
:type name: str
:param display_name: The display name of the dimension.
:type display_name: str
:param internal_name: The internal name of the dimension.
:type internal_name: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'internal_name': {'key': 'internalName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Dimension, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.internal_name = kwargs.get('internal_name', None)
class DnsNameAvailabilityResult(msrest.serialization.Model):
"""Response for the CheckDnsNameAvailability API service call.
:param available: Domain availability (True/False).
:type available: bool
"""
_attribute_map = {
'available': {'key': 'available', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(DnsNameAvailabilityResult, self).__init__(**kwargs)
self.available = kwargs.get('available', None)
class EffectiveNetworkSecurityGroup(msrest.serialization.Model):
"""Effective network security group.
:param network_security_group: The ID of network security group that is applied.
:type network_security_group: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param association: Associated resources.
:type association:
~azure.mgmt.network.v2019_04_01.models.EffectiveNetworkSecurityGroupAssociation
:param effective_security_rules: A collection of effective security rules.
:type effective_security_rules:
list[~azure.mgmt.network.v2019_04_01.models.EffectiveNetworkSecurityRule]
:param tag_map: Mapping of tags to list of IP Addresses included within the tag.
:type tag_map: str
"""
_attribute_map = {
'network_security_group': {'key': 'networkSecurityGroup', 'type': 'SubResource'},
'association': {'key': 'association', 'type': 'EffectiveNetworkSecurityGroupAssociation'},
'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'},
'tag_map': {'key': 'tagMap', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroup, self).__init__(**kwargs)
self.network_security_group = kwargs.get('network_security_group', None)
self.association = kwargs.get('association', None)
self.effective_security_rules = kwargs.get('effective_security_rules', None)
self.tag_map = kwargs.get('tag_map', None)
class EffectiveNetworkSecurityGroupAssociation(msrest.serialization.Model):
"""The effective network security group association.
:param subnet: The ID of the subnet if assigned.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param network_interface: The ID of the network interface if assigned.
:type network_interface: ~azure.mgmt.network.v2019_04_01.models.SubResource
"""
_attribute_map = {
'subnet': {'key': 'subnet', 'type': 'SubResource'},
'network_interface': {'key': 'networkInterface', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroupAssociation, self).__init__(**kwargs)
self.subnet = kwargs.get('subnet', None)
self.network_interface = kwargs.get('network_interface', None)
class EffectiveNetworkSecurityGroupListResult(msrest.serialization.Model):
"""Response for list effective network security groups API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of effective network security groups.
:type value: list[~azure.mgmt.network.v2019_04_01.models.EffectiveNetworkSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[EffectiveNetworkSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class EffectiveNetworkSecurityRule(msrest.serialization.Model):
"""Effective network security rules.
:param name: The name of the security rule specified by the user (if created by the user).
:type name: str
:param protocol: The network protocol this rule applies to. Possible values include: "Tcp",
"Udp", "All".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.EffectiveSecurityRuleProtocol
:param source_port_range: The source port or range.
:type source_port_range: str
:param destination_port_range: The destination port or range.
:type destination_port_range: str
:param source_port_ranges: The source port ranges. Expected values include a single integer
between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*).
:type source_port_ranges: list[str]
:param destination_port_ranges: The destination port ranges. Expected values include a single
integer between 0 and 65535, a range using '-' as separator (e.g. 100-400), or an asterisk (*).
:type destination_port_ranges: list[str]
:param source_address_prefix: The source address prefix.
:type source_address_prefix: str
:param destination_address_prefix: The destination address prefix.
:type destination_address_prefix: str
:param source_address_prefixes: The source address prefixes. Expected values include CIDR IP
ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the
asterisk (*).
:type source_address_prefixes: list[str]
:param destination_address_prefixes: The destination address prefixes. Expected values include
CIDR IP ranges, Default Tags (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and
the asterisk (*).
:type destination_address_prefixes: list[str]
:param expanded_source_address_prefix: The expanded source address prefix.
:type expanded_source_address_prefix: list[str]
:param expanded_destination_address_prefix: Expanded destination address prefix.
:type expanded_destination_address_prefix: list[str]
:param access: Whether network traffic is allowed or denied. Possible values include: "Allow",
"Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.SecurityRuleAccess
:param priority: The priority of the rule.
:type priority: int
:param direction: The direction of the rule. Possible values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2019_04_01.models.SecurityRuleDirection
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'source_port_range': {'key': 'sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'destinationPortRange', 'type': 'str'},
'source_port_ranges': {'key': 'sourcePortRanges', 'type': '[str]'},
'destination_port_ranges': {'key': 'destinationPortRanges', 'type': '[str]'},
'source_address_prefix': {'key': 'sourceAddressPrefix', 'type': 'str'},
'destination_address_prefix': {'key': 'destinationAddressPrefix', 'type': 'str'},
'source_address_prefixes': {'key': 'sourceAddressPrefixes', 'type': '[str]'},
'destination_address_prefixes': {'key': 'destinationAddressPrefixes', 'type': '[str]'},
'expanded_source_address_prefix': {'key': 'expandedSourceAddressPrefix', 'type': '[str]'},
'expanded_destination_address_prefix': {'key': 'expandedDestinationAddressPrefix', 'type': '[str]'},
'access': {'key': 'access', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'direction': {'key': 'direction', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveNetworkSecurityRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.protocol = kwargs.get('protocol', None)
self.source_port_range = kwargs.get('source_port_range', None)
self.destination_port_range = kwargs.get('destination_port_range', None)
self.source_port_ranges = kwargs.get('source_port_ranges', None)
self.destination_port_ranges = kwargs.get('destination_port_ranges', None)
self.source_address_prefix = kwargs.get('source_address_prefix', None)
self.destination_address_prefix = kwargs.get('destination_address_prefix', None)
self.source_address_prefixes = kwargs.get('source_address_prefixes', None)
self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None)
self.expanded_source_address_prefix = kwargs.get('expanded_source_address_prefix', None)
self.expanded_destination_address_prefix = kwargs.get('expanded_destination_address_prefix', None)
self.access = kwargs.get('access', None)
self.priority = kwargs.get('priority', None)
self.direction = kwargs.get('direction', None)
class EffectiveRoute(msrest.serialization.Model):
"""Effective Route.
:param name: The name of the user defined route. This is optional.
:type name: str
:param disable_bgp_route_propagation: If true, on-premises routes are not propagated to the
network interfaces in the subnet.
:type disable_bgp_route_propagation: bool
:param source: Who created the route. Possible values include: "Unknown", "User",
"VirtualNetworkGateway", "Default".
:type source: str or ~azure.mgmt.network.v2019_04_01.models.EffectiveRouteSource
:param state: The value of effective route. Possible values include: "Active", "Invalid".
:type state: str or ~azure.mgmt.network.v2019_04_01.models.EffectiveRouteState
:param address_prefix: The address prefixes of the effective routes in CIDR notation.
:type address_prefix: list[str]
:param next_hop_ip_address: The IP address of the next hop of the effective route.
:type next_hop_ip_address: list[str]
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values
include: "VirtualNetworkGateway", "VnetLocal", "Internet", "VirtualAppliance", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2019_04_01.models.RouteNextHopType
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'disable_bgp_route_propagation': {'key': 'disableBgpRoutePropagation', 'type': 'bool'},
'source': {'key': 'source', 'type': 'str'},
'state': {'key': 'state', 'type': 'str'},
'address_prefix': {'key': 'addressPrefix', 'type': '[str]'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': '[str]'},
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveRoute, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None)
self.source = kwargs.get('source', None)
self.state = kwargs.get('state', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.next_hop_type = kwargs.get('next_hop_type', None)
class EffectiveRouteListResult(msrest.serialization.Model):
"""Response for list effective route API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of effective routes.
:type value: list[~azure.mgmt.network.v2019_04_01.models.EffectiveRoute]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[EffectiveRoute]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EffectiveRouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class EndpointServiceResult(SubResource):
"""Endpoint service.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Name of the endpoint service.
:vartype name: str
:ivar type: Type of the endpoint service.
:vartype type: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EndpointServiceResult, self).__init__(**kwargs)
self.name = None
self.type = None
class EndpointServicesListResult(msrest.serialization.Model):
"""Response for the ListAvailableEndpointServices API service call.
:param value: List of available endpoint services in a region.
:type value: list[~azure.mgmt.network.v2019_04_01.models.EndpointServiceResult]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[EndpointServiceResult]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(EndpointServicesListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class Error(msrest.serialization.Model):
"""Common error representation.
:param code: Error code.
:type code: str
:param message: Error message.
:type message: str
:param target: Error target.
:type target: str
:param details: Error details.
:type details: list[~azure.mgmt.network.v2019_04_01.models.ErrorDetails]
:param inner_error: Inner error message.
:type inner_error: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[ErrorDetails]'},
'inner_error': {'key': 'innerError', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Error, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.message = kwargs.get('message', None)
self.target = kwargs.get('target', None)
self.details = kwargs.get('details', None)
self.inner_error = kwargs.get('inner_error', None)
class ErrorDetails(msrest.serialization.Model):
"""Common error details representation.
:param code: Error code.
:type code: str
:param target: Error target.
:type target: str
:param message: Error message.
:type message: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ErrorDetails, self).__init__(**kwargs)
self.code = kwargs.get('code', None)
self.target = kwargs.get('target', None)
self.message = kwargs.get('message', None)
class ErrorResponse(msrest.serialization.Model):
"""The error object.
:param error: The error details object.
:type error: ~azure.mgmt.network.v2019_04_01.models.ErrorDetails
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorDetails'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponse, self).__init__(**kwargs)
self.error = kwargs.get('error', None)
class EvaluatedNetworkSecurityGroup(msrest.serialization.Model):
"""Results of network security group evaluation.
Variables are only populated by the server, and will be ignored when sending a request.
:param network_security_group_id: Network security group ID.
:type network_security_group_id: str
:param applied_to: Resource ID of nic or subnet to which network security group is applied.
:type applied_to: str
:param matched_rule: Matched network security rule.
:type matched_rule: ~azure.mgmt.network.v2019_04_01.models.MatchedRule
:ivar rules_evaluation_result: List of network security rules evaluation results.
:vartype rules_evaluation_result:
list[~azure.mgmt.network.v2019_04_01.models.NetworkSecurityRulesEvaluationResult]
"""
_validation = {
'rules_evaluation_result': {'readonly': True},
}
_attribute_map = {
'network_security_group_id': {'key': 'networkSecurityGroupId', 'type': 'str'},
'applied_to': {'key': 'appliedTo', 'type': 'str'},
'matched_rule': {'key': 'matchedRule', 'type': 'MatchedRule'},
'rules_evaluation_result': {'key': 'rulesEvaluationResult', 'type': '[NetworkSecurityRulesEvaluationResult]'},
}
def __init__(
self,
**kwargs
):
super(EvaluatedNetworkSecurityGroup, self).__init__(**kwargs)
self.network_security_group_id = kwargs.get('network_security_group_id', None)
self.applied_to = kwargs.get('applied_to', None)
self.matched_rule = kwargs.get('matched_rule', None)
self.rules_evaluation_result = None
class ExpressRouteCircuit(Resource):
"""ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The SKU.
:type sku: ~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitSku
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param allow_classic_operations: Allow classic operations.
:type allow_classic_operations: bool
:param circuit_provisioning_state: The CircuitProvisioningState state of the resource.
:type circuit_provisioning_state: str
:param service_provider_provisioning_state: The ServiceProviderProvisioningState state of the
resource. Possible values include: "NotProvisioned", "Provisioning", "Provisioned",
"Deprovisioning".
:type service_provider_provisioning_state: str or
~azure.mgmt.network.v2019_04_01.models.ServiceProviderProvisioningState
:param authorizations: The list of authorizations.
:type authorizations:
list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitAuthorization]
:param peerings: The list of peerings.
:type peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:param service_key: The ServiceKey.
:type service_key: str
:param service_provider_notes: The ServiceProviderNotes.
:type service_provider_notes: str
:param service_provider_properties: The ServiceProviderProperties.
:type service_provider_properties:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitServiceProviderProperties
:param express_route_port: The reference to the ExpressRoutePort resource when the circuit is
provisioned on an ExpressRoutePort resource.
:type express_route_port: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param bandwidth_in_gbps: The bandwidth of the circuit when the circuit is provisioned on an
ExpressRoutePort resource.
:type bandwidth_in_gbps: float
:ivar stag: The identifier of the circuit traffic. Outer tag for QinQ encapsulation.
:vartype stag: int
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:param global_reach_enabled: Flag denoting Global reach status.
:type global_reach_enabled: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'stag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'ExpressRouteCircuitSku'},
'etag': {'key': 'etag', 'type': 'str'},
'allow_classic_operations': {'key': 'properties.allowClassicOperations', 'type': 'bool'},
'circuit_provisioning_state': {'key': 'properties.circuitProvisioningState', 'type': 'str'},
'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'},
'authorizations': {'key': 'properties.authorizations', 'type': '[ExpressRouteCircuitAuthorization]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'service_key': {'key': 'properties.serviceKey', 'type': 'str'},
'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'},
'service_provider_properties': {'key': 'properties.serviceProviderProperties', 'type': 'ExpressRouteCircuitServiceProviderProperties'},
'express_route_port': {'key': 'properties.expressRoutePort', 'type': 'SubResource'},
'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'float'},
'stag': {'key': 'properties.stag', 'type': 'int'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'global_reach_enabled': {'key': 'properties.globalReachEnabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuit, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = None
self.allow_classic_operations = kwargs.get('allow_classic_operations', None)
self.circuit_provisioning_state = kwargs.get('circuit_provisioning_state', None)
self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None)
self.authorizations = kwargs.get('authorizations', None)
self.peerings = kwargs.get('peerings', None)
self.service_key = kwargs.get('service_key', None)
self.service_provider_notes = kwargs.get('service_provider_notes', None)
self.service_provider_properties = kwargs.get('service_provider_properties', None)
self.express_route_port = kwargs.get('express_route_port', None)
self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None)
self.stag = None
self.provisioning_state = kwargs.get('provisioning_state', None)
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.global_reach_enabled = kwargs.get('global_reach_enabled', None)
class ExpressRouteCircuitArpTable(msrest.serialization.Model):
"""The ARP table associated with the ExpressRouteCircuit.
:param age: Entry age in minutes.
:type age: int
:param interface: Interface address.
:type interface: str
:param ip_address: The IP address.
:type ip_address: str
:param mac_address: The MAC address.
:type mac_address: str
"""
_attribute_map = {
'age': {'key': 'age', 'type': 'int'},
'interface': {'key': 'interface', 'type': 'str'},
'ip_address': {'key': 'ipAddress', 'type': 'str'},
'mac_address': {'key': 'macAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitArpTable, self).__init__(**kwargs)
self.age = kwargs.get('age', None)
self.interface = kwargs.get('interface', None)
self.ip_address = kwargs.get('ip_address', None)
self.mac_address = kwargs.get('mac_address', None)
class ExpressRouteCircuitAuthorization(SubResource):
"""Authorization in an ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param authorization_key: The authorization key.
:type authorization_key: str
:param authorization_use_status: The authorization use status. Possible values include:
"Available", "InUse".
:type authorization_use_status: str or
~azure.mgmt.network.v2019_04_01.models.AuthorizationUseStatus
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'authorization_use_status': {'key': 'properties.authorizationUseStatus', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitAuthorization, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.authorization_key = kwargs.get('authorization_key', None)
self.authorization_use_status = kwargs.get('authorization_use_status', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ExpressRouteCircuitConnection(SubResource):
"""Express Route Circuit Connection in an ExpressRouteCircuitPeering resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the circuit initiating connection.
:type express_route_circuit_peering: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the peered circuit.
:type peer_express_route_circuit_peering: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param address_prefix: /29 IP address space to carve out Customer addresses for tunnels.
:type address_prefix: str
:param authorization_key: The authorization key.
:type authorization_key: str
:ivar circuit_connection_status: Express Route Circuit connection state. Possible values
include: "Connected", "Connecting", "Disconnected".
:vartype circuit_connection_status: str or
~azure.mgmt.network.v2019_04_01.models.CircuitConnectionStatus
:ivar provisioning_state: Provisioning state of the circuit connection resource. Possible
values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'circuit_connection_status': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'},
'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.circuit_connection_status = None
self.provisioning_state = None
class ExpressRouteCircuitConnectionListResult(msrest.serialization.Model):
"""Response for ListConnections API service call retrieves all global reach connections that belongs to a Private Peering for an ExpressRouteCircuit.
:param value: The global reach connection associated with Private Peering in an ExpressRoute
Circuit.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitConnection]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitListResult(msrest.serialization.Model):
"""Response for ListExpressRouteCircuit API service call.
:param value: A list of ExpressRouteCircuits in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuit]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuit]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitPeering(SubResource):
"""Peering in an ExpressRouteCircuit resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param peering_type: The peering type. Possible values include: "AzurePublicPeering",
"AzurePrivatePeering", "MicrosoftPeering".
:type peering_type: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRoutePeeringType
:param state: The peering state. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRoutePeeringState
:param azure_asn: The Azure ASN.
:type azure_asn: int
:param peer_asn: The peer ASN.
:type peer_asn: long
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:param primary_azure_port: The primary port.
:type primary_azure_port: str
:param secondary_azure_port: The secondary port.
:type secondary_azure_port: str
:param shared_key: The shared key.
:type shared_key: str
:param vlan_id: The VLAN ID.
:type vlan_id: int
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringConfig
:param stats: Gets peering stats.
:type stats: ~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitStats
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:param last_modified_by: Gets whether the provider or the customer last modified the peering.
:type last_modified_by: str
:param route_filter: The reference of the RouteFilter resource.
:type route_filter: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param ipv6_peering_config: The IPv6 peering configuration.
:type ipv6_peering_config:
~azure.mgmt.network.v2019_04_01.models.Ipv6ExpressRouteCircuitPeeringConfig
:param express_route_connection: The ExpressRoute connection.
:type express_route_connection: ~azure.mgmt.network.v2019_04_01.models.ExpressRouteConnectionId
:param connections: The list of circuit connections associated with Azure Private Peering for
this circuit.
:type connections: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitConnection]
:ivar peered_connections: The list of peered circuit connections associated with Azure Private
Peering for this circuit.
:vartype peered_connections:
list[~azure.mgmt.network.v2019_04_01.models.PeerExpressRouteCircuitConnection]
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'peer_asn': {'maximum': 4294967295, 'minimum': 1},
'peered_connections': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'peering_type': {'key': 'properties.peeringType', 'type': 'str'},
'state': {'key': 'properties.state', 'type': 'str'},
'azure_asn': {'key': 'properties.azureASN', 'type': 'int'},
'peer_asn': {'key': 'properties.peerASN', 'type': 'long'},
'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'vlan_id': {'key': 'properties.vlanId', 'type': 'int'},
'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'stats': {'key': 'properties.stats', 'type': 'ExpressRouteCircuitStats'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'},
'route_filter': {'key': 'properties.routeFilter', 'type': 'SubResource'},
'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'},
'express_route_connection': {'key': 'properties.expressRouteConnection', 'type': 'ExpressRouteConnectionId'},
'connections': {'key': 'properties.connections', 'type': '[ExpressRouteCircuitConnection]'},
'peered_connections': {'key': 'properties.peeredConnections', 'type': '[PeerExpressRouteCircuitConnection]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.peering_type = kwargs.get('peering_type', None)
self.state = kwargs.get('state', None)
self.azure_asn = kwargs.get('azure_asn', None)
self.peer_asn = kwargs.get('peer_asn', None)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.primary_azure_port = kwargs.get('primary_azure_port', None)
self.secondary_azure_port = kwargs.get('secondary_azure_port', None)
self.shared_key = kwargs.get('shared_key', None)
self.vlan_id = kwargs.get('vlan_id', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.stats = kwargs.get('stats', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.last_modified_by = kwargs.get('last_modified_by', None)
self.route_filter = kwargs.get('route_filter', None)
self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None)
self.express_route_connection = kwargs.get('express_route_connection', None)
self.connections = kwargs.get('connections', None)
self.peered_connections = None
class ExpressRouteCircuitPeeringConfig(msrest.serialization.Model):
"""Specifies the peering configuration.
:param advertised_public_prefixes: The reference of AdvertisedPublicPrefixes.
:type advertised_public_prefixes: list[str]
:param advertised_communities: The communities of bgp peering. Specified for microsoft peering.
:type advertised_communities: list[str]
:param advertised_public_prefixes_state: The advertised public prefix state of the Peering
resource. Possible values include: "NotConfigured", "Configuring", "Configured",
"ValidationNeeded".
:type advertised_public_prefixes_state: str or
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringAdvertisedPublicPrefixState
:param legacy_mode: The legacy mode of the peering.
:type legacy_mode: int
:param customer_asn: The CustomerASN of the peering.
:type customer_asn: int
:param routing_registry_name: The RoutingRegistryName of the configuration.
:type routing_registry_name: str
"""
_attribute_map = {
'advertised_public_prefixes': {'key': 'advertisedPublicPrefixes', 'type': '[str]'},
'advertised_communities': {'key': 'advertisedCommunities', 'type': '[str]'},
'advertised_public_prefixes_state': {'key': 'advertisedPublicPrefixesState', 'type': 'str'},
'legacy_mode': {'key': 'legacyMode', 'type': 'int'},
'customer_asn': {'key': 'customerASN', 'type': 'int'},
'routing_registry_name': {'key': 'routingRegistryName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs)
self.advertised_public_prefixes = kwargs.get('advertised_public_prefixes', None)
self.advertised_communities = kwargs.get('advertised_communities', None)
self.advertised_public_prefixes_state = kwargs.get('advertised_public_prefixes_state', None)
self.legacy_mode = kwargs.get('legacy_mode', None)
self.customer_asn = kwargs.get('customer_asn', None)
self.routing_registry_name = kwargs.get('routing_registry_name', None)
class ExpressRouteCircuitPeeringId(msrest.serialization.Model):
"""ExpressRoute circuit peering identifier.
:param id: The ID of the ExpressRoute circuit peering.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringId, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ExpressRouteCircuitPeeringListResult(msrest.serialization.Model):
"""Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCircuit.
:param value: The peerings in an express route circuit.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitPeeringListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitReference(msrest.serialization.Model):
"""Reference to an express route circuit.
:param id: Corresponding Express Route Circuit Id.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitReference, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ExpressRouteCircuitRoutesTable(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param network: IP address of a network entity.
:type network: str
:param next_hop: NextHop address.
:type next_hop: str
:param loc_prf: Local preference value as set with the set local-preference route-map
configuration command.
:type loc_prf: str
:param weight: Route Weight.
:type weight: int
:param path: Autonomous system paths to the destination network.
:type path: str
"""
_attribute_map = {
'network': {'key': 'network', 'type': 'str'},
'next_hop': {'key': 'nextHop', 'type': 'str'},
'loc_prf': {'key': 'locPrf', 'type': 'str'},
'weight': {'key': 'weight', 'type': 'int'},
'path': {'key': 'path', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitRoutesTable, self).__init__(**kwargs)
self.network = kwargs.get('network', None)
self.next_hop = kwargs.get('next_hop', None)
self.loc_prf = kwargs.get('loc_prf', None)
self.weight = kwargs.get('weight', None)
self.path = kwargs.get('path', None)
class ExpressRouteCircuitRoutesTableSummary(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param neighbor: IP address of the neighbor.
:type neighbor: str
:param v: BGP version number spoken to the neighbor.
:type v: int
:param as_property: Autonomous system number.
:type as_property: int
:param up_down: The length of time that the BGP session has been in the Established state, or
the current status if not in the Established state.
:type up_down: str
:param state_pfx_rcd: Current state of the BGP session, and the number of prefixes that have
been received from a neighbor or peer group.
:type state_pfx_rcd: str
"""
_attribute_map = {
'neighbor': {'key': 'neighbor', 'type': 'str'},
'v': {'key': 'v', 'type': 'int'},
'as_property': {'key': 'as', 'type': 'int'},
'up_down': {'key': 'upDown', 'type': 'str'},
'state_pfx_rcd': {'key': 'statePfxRcd', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitRoutesTableSummary, self).__init__(**kwargs)
self.neighbor = kwargs.get('neighbor', None)
self.v = kwargs.get('v', None)
self.as_property = kwargs.get('as_property', None)
self.up_down = kwargs.get('up_down', None)
self.state_pfx_rcd = kwargs.get('state_pfx_rcd', None)
class ExpressRouteCircuitsArpTableListResult(msrest.serialization.Model):
"""Response for ListArpTable associated with the Express Route Circuits API.
:param value: Gets list of the ARP table.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitArpTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitArpTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsArpTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitServiceProviderProperties(msrest.serialization.Model):
"""Contains ServiceProviderProperties in an ExpressRouteCircuit.
:param service_provider_name: The serviceProviderName.
:type service_provider_name: str
:param peering_location: The peering location.
:type peering_location: str
:param bandwidth_in_mbps: The BandwidthInMbps.
:type bandwidth_in_mbps: int
"""
_attribute_map = {
'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'},
'peering_location': {'key': 'peeringLocation', 'type': 'str'},
'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitServiceProviderProperties, self).__init__(**kwargs)
self.service_provider_name = kwargs.get('service_provider_name', None)
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None)
class ExpressRouteCircuitSku(msrest.serialization.Model):
"""Contains SKU in an ExpressRouteCircuit.
:param name: The name of the SKU.
:type name: str
:param tier: The tier of the SKU. Possible values include: "Standard", "Premium", "Basic",
"Local".
:type tier: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitSkuTier
:param family: The family of the SKU. Possible values include: "UnlimitedData", "MeteredData".
:type family: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitSkuFamily
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'family': {'key': 'family', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.family = kwargs.get('family', None)
class ExpressRouteCircuitsRoutesTableListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Circuits API.
:param value: The list of routes table.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitRoutesTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsRoutesTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitsRoutesTableSummaryListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Circuits API.
:param value: A list of the routes table.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitRoutesTableSummary]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCircuitRoutesTableSummary]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitsRoutesTableSummaryListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteCircuitStats(msrest.serialization.Model):
"""Contains stats associated with the peering.
:param primarybytes_in: Gets BytesIn of the peering.
:type primarybytes_in: long
:param primarybytes_out: Gets BytesOut of the peering.
:type primarybytes_out: long
:param secondarybytes_in: Gets BytesIn of the peering.
:type secondarybytes_in: long
:param secondarybytes_out: Gets BytesOut of the peering.
:type secondarybytes_out: long
"""
_attribute_map = {
'primarybytes_in': {'key': 'primarybytesIn', 'type': 'long'},
'primarybytes_out': {'key': 'primarybytesOut', 'type': 'long'},
'secondarybytes_in': {'key': 'secondarybytesIn', 'type': 'long'},
'secondarybytes_out': {'key': 'secondarybytesOut', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCircuitStats, self).__init__(**kwargs)
self.primarybytes_in = kwargs.get('primarybytes_in', None)
self.primarybytes_out = kwargs.get('primarybytes_out', None)
self.secondarybytes_in = kwargs.get('secondarybytes_in', None)
self.secondarybytes_out = kwargs.get('secondarybytes_out', None)
class ExpressRouteConnection(SubResource):
"""ExpressRouteConnection resource.
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: Resource ID.
:type id: str
:param name: Required. The name of the resource.
:type name: str
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param express_route_circuit_peering: The ExpressRoute circuit peering.
:type express_route_circuit_peering:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringId
:param authorization_key: Authorization key to establish the connection.
:type authorization_key: str
:param routing_weight: The routing weight associated to the connection.
:type routing_weight: int
"""
_validation = {
'name': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'ExpressRouteCircuitPeeringId'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnection, self).__init__(**kwargs)
self.name = kwargs['name']
self.provisioning_state = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.routing_weight = kwargs.get('routing_weight', None)
class ExpressRouteConnectionId(msrest.serialization.Model):
"""The ID of the ExpressRouteConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ID of the ExpressRouteConnection.
:vartype id: str
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnectionId, self).__init__(**kwargs)
self.id = None
class ExpressRouteConnectionList(msrest.serialization.Model):
"""ExpressRouteConnection list.
:param value: The list of ExpressRoute connections.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteConnection]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteConnection]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteConnectionList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ExpressRouteCrossConnection(Resource):
"""ExpressRouteCrossConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar primary_azure_port: The name of the primary port.
:vartype primary_azure_port: str
:ivar secondary_azure_port: The name of the secondary port.
:vartype secondary_azure_port: str
:ivar s_tag: The identifier of the circuit traffic.
:vartype s_tag: int
:param peering_location: The peering location of the ExpressRoute circuit.
:type peering_location: str
:param bandwidth_in_mbps: The circuit bandwidth In Mbps.
:type bandwidth_in_mbps: int
:param express_route_circuit: The ExpressRouteCircuit.
:type express_route_circuit:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitReference
:param service_provider_provisioning_state: The provisioning state of the circuit in the
connectivity provider system. Possible values include: "NotProvisioned", "Provisioning",
"Provisioned", "Deprovisioning".
:type service_provider_provisioning_state: str or
~azure.mgmt.network.v2019_04_01.models.ServiceProviderProvisioningState
:param service_provider_notes: Additional read only notes set by the connectivity provider.
:type service_provider_notes: str
:ivar provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param peerings: The list of peerings.
:type peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCrossConnectionPeering]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'primary_azure_port': {'readonly': True},
'secondary_azure_port': {'readonly': True},
's_tag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
's_tag': {'key': 'properties.sTag', 'type': 'int'},
'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'},
'bandwidth_in_mbps': {'key': 'properties.bandwidthInMbps', 'type': 'int'},
'express_route_circuit': {'key': 'properties.expressRouteCircuit', 'type': 'ExpressRouteCircuitReference'},
'service_provider_provisioning_state': {'key': 'properties.serviceProviderProvisioningState', 'type': 'str'},
'service_provider_notes': {'key': 'properties.serviceProviderNotes', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCrossConnectionPeering]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnection, self).__init__(**kwargs)
self.etag = None
self.primary_azure_port = None
self.secondary_azure_port = None
self.s_tag = None
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None)
self.express_route_circuit = kwargs.get('express_route_circuit', None)
self.service_provider_provisioning_state = kwargs.get('service_provider_provisioning_state', None)
self.service_provider_notes = kwargs.get('service_provider_notes', None)
self.provisioning_state = None
self.peerings = kwargs.get('peerings', None)
class ExpressRouteCrossConnectionListResult(msrest.serialization.Model):
"""Response for ListExpressRouteCrossConnection API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ExpressRouteCrossConnection resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCrossConnection]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteCrossConnectionPeering(SubResource):
"""Peering in an ExpressRoute Cross Connection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param peering_type: The peering type. Possible values include: "AzurePublicPeering",
"AzurePrivatePeering", "MicrosoftPeering".
:type peering_type: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRoutePeeringType
:param state: The peering state. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRoutePeeringState
:ivar azure_asn: The Azure ASN.
:vartype azure_asn: int
:param peer_asn: The peer ASN.
:type peer_asn: long
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:ivar primary_azure_port: The primary port.
:vartype primary_azure_port: str
:ivar secondary_azure_port: The secondary port.
:vartype secondary_azure_port: str
:param shared_key: The shared key.
:type shared_key: str
:param vlan_id: The VLAN ID.
:type vlan_id: int
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringConfig
:ivar provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param gateway_manager_etag: The GatewayManager Etag.
:type gateway_manager_etag: str
:param last_modified_by: Gets whether the provider or the customer last modified the peering.
:type last_modified_by: str
:param ipv6_peering_config: The IPv6 peering configuration.
:type ipv6_peering_config:
~azure.mgmt.network.v2019_04_01.models.Ipv6ExpressRouteCircuitPeeringConfig
"""
_validation = {
'etag': {'readonly': True},
'azure_asn': {'readonly': True},
'peer_asn': {'maximum': 4294967295, 'minimum': 1},
'primary_azure_port': {'readonly': True},
'secondary_azure_port': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'peering_type': {'key': 'properties.peeringType', 'type': 'str'},
'state': {'key': 'properties.state', 'type': 'str'},
'azure_asn': {'key': 'properties.azureASN', 'type': 'int'},
'peer_asn': {'key': 'properties.peerASN', 'type': 'long'},
'primary_peer_address_prefix': {'key': 'properties.primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'properties.secondaryPeerAddressPrefix', 'type': 'str'},
'primary_azure_port': {'key': 'properties.primaryAzurePort', 'type': 'str'},
'secondary_azure_port': {'key': 'properties.secondaryAzurePort', 'type': 'str'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'vlan_id': {'key': 'properties.vlanId', 'type': 'int'},
'microsoft_peering_config': {'key': 'properties.microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'gateway_manager_etag': {'key': 'properties.gatewayManagerEtag', 'type': 'str'},
'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'},
'ipv6_peering_config': {'key': 'properties.ipv6PeeringConfig', 'type': 'Ipv6ExpressRouteCircuitPeeringConfig'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.peering_type = kwargs.get('peering_type', None)
self.state = kwargs.get('state', None)
self.azure_asn = None
self.peer_asn = kwargs.get('peer_asn', None)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.primary_azure_port = None
self.secondary_azure_port = None
self.shared_key = kwargs.get('shared_key', None)
self.vlan_id = kwargs.get('vlan_id', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.provisioning_state = None
self.gateway_manager_etag = kwargs.get('gateway_manager_etag', None)
self.last_modified_by = kwargs.get('last_modified_by', None)
self.ipv6_peering_config = kwargs.get('ipv6_peering_config', None)
class ExpressRouteCrossConnectionPeeringList(msrest.serialization.Model):
"""Response for ListPeering API service call retrieves all peerings that belong to an ExpressRouteCrossConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The peerings in an express route cross connection.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCrossConnectionPeering]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnectionPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionPeeringList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteCrossConnectionRoutesTableSummary(msrest.serialization.Model):
"""The routes table associated with the ExpressRouteCircuit.
:param neighbor: IP address of Neighbor router.
:type neighbor: str
:param asn: Autonomous system number.
:type asn: int
:param up_down: The length of time that the BGP session has been in the Established state, or
the current status if not in the Established state.
:type up_down: str
:param state_or_prefixes_received: Current state of the BGP session, and the number of prefixes
that have been received from a neighbor or peer group.
:type state_or_prefixes_received: str
"""
_attribute_map = {
'neighbor': {'key': 'neighbor', 'type': 'str'},
'asn': {'key': 'asn', 'type': 'int'},
'up_down': {'key': 'upDown', 'type': 'str'},
'state_or_prefixes_received': {'key': 'stateOrPrefixesReceived', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionRoutesTableSummary, self).__init__(**kwargs)
self.neighbor = kwargs.get('neighbor', None)
self.asn = kwargs.get('asn', None)
self.up_down = kwargs.get('up_down', None)
self.state_or_prefixes_received = kwargs.get('state_or_prefixes_received', None)
class ExpressRouteCrossConnectionsRoutesTableSummaryListResult(msrest.serialization.Model):
"""Response for ListRoutesTable associated with the Express Route Cross Connections.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of the routes table.
:type value:
list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCrossConnectionRoutesTableSummary]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteCrossConnectionRoutesTableSummary]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteCrossConnectionsRoutesTableSummaryListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ExpressRouteGateway(Resource):
"""ExpressRoute gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param auto_scale_configuration: Configuration for auto scaling.
:type auto_scale_configuration:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteGatewayPropertiesAutoScaleConfiguration
:ivar express_route_connections: List of ExpressRoute connections to the ExpressRoute gateway.
:vartype express_route_connections:
list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteConnection]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param virtual_hub: The Virtual Hub where the ExpressRoute gateway is or will be deployed.
:type virtual_hub: ~azure.mgmt.network.v2019_04_01.models.VirtualHubId
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'express_route_connections': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'auto_scale_configuration': {'key': 'properties.autoScaleConfiguration', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfiguration'},
'express_route_connections': {'key': 'properties.expressRouteConnections', 'type': '[ExpressRouteConnection]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'VirtualHubId'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGateway, self).__init__(**kwargs)
self.etag = None
self.auto_scale_configuration = kwargs.get('auto_scale_configuration', None)
self.express_route_connections = None
self.provisioning_state = None
self.virtual_hub = kwargs.get('virtual_hub', None)
class ExpressRouteGatewayList(msrest.serialization.Model):
"""List of ExpressRoute gateways.
:param value: List of ExpressRoute gateways.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteGateway]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteGateway]'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ExpressRouteGatewayPropertiesAutoScaleConfiguration(msrest.serialization.Model):
"""Configuration for auto scaling.
:param bounds: Minimum and maximum number of scale units to deploy.
:type bounds:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds
"""
_attribute_map = {
'bounds': {'key': 'bounds', 'type': 'ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayPropertiesAutoScaleConfiguration, self).__init__(**kwargs)
self.bounds = kwargs.get('bounds', None)
class ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds(msrest.serialization.Model):
"""Minimum and maximum number of scale units to deploy.
:param min: Minimum number of scale units deployed for ExpressRoute gateway.
:type min: int
:param max: Maximum number of scale units deployed for ExpressRoute gateway.
:type max: int
"""
_attribute_map = {
'min': {'key': 'min', 'type': 'int'},
'max': {'key': 'max', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds, self).__init__(**kwargs)
self.min = kwargs.get('min', None)
self.max = kwargs.get('max', None)
class ExpressRouteLink(SubResource):
"""ExpressRouteLink child resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of child port resource that is unique among child port resources of the
parent.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar router_name: Name of Azure router associated with physical port.
:vartype router_name: str
:ivar interface_name: Name of Azure router interface.
:vartype interface_name: str
:ivar patch_panel_id: Mapping between physical port to patch panel port.
:vartype patch_panel_id: str
:ivar rack_id: Mapping of physical patch panel to rack.
:vartype rack_id: str
:ivar connector_type: Physical fiber port type. Possible values include: "LC", "SC".
:vartype connector_type: str or
~azure.mgmt.network.v2019_04_01.models.ExpressRouteLinkConnectorType
:param admin_state: Administrative state of the physical port. Possible values include:
"Enabled", "Disabled".
:type admin_state: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRouteLinkAdminState
:ivar provisioning_state: The provisioning state of the ExpressRouteLink resource. Possible
values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'router_name': {'readonly': True},
'interface_name': {'readonly': True},
'patch_panel_id': {'readonly': True},
'rack_id': {'readonly': True},
'connector_type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'router_name': {'key': 'properties.routerName', 'type': 'str'},
'interface_name': {'key': 'properties.interfaceName', 'type': 'str'},
'patch_panel_id': {'key': 'properties.patchPanelId', 'type': 'str'},
'rack_id': {'key': 'properties.rackId', 'type': 'str'},
'connector_type': {'key': 'properties.connectorType', 'type': 'str'},
'admin_state': {'key': 'properties.adminState', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.router_name = None
self.interface_name = None
self.patch_panel_id = None
self.rack_id = None
self.connector_type = None
self.admin_state = kwargs.get('admin_state', None)
self.provisioning_state = None
class ExpressRouteLinkListResult(msrest.serialization.Model):
"""Response for ListExpressRouteLinks API service call.
:param value: The list of ExpressRouteLink sub-resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteLink]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteLinkListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRoutePort(Resource):
"""ExpressRoutePort resource definition.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param peering_location: The name of the peering location that the ExpressRoutePort is mapped
to physically.
:type peering_location: str
:param bandwidth_in_gbps: Bandwidth of procured ports in Gbps.
:type bandwidth_in_gbps: int
:ivar provisioned_bandwidth_in_gbps: Aggregate Gbps of associated circuit bandwidths.
:vartype provisioned_bandwidth_in_gbps: float
:ivar mtu: Maximum transmission unit of the physical port pair(s).
:vartype mtu: str
:param encapsulation: Encapsulation method on physical ports. Possible values include: "Dot1Q",
"QinQ".
:type encapsulation: str or
~azure.mgmt.network.v2019_04_01.models.ExpressRoutePortsEncapsulation
:ivar ether_type: Ether type of the physical port.
:vartype ether_type: str
:ivar allocation_date: Date of the physical port allocation to be used in Letter of
Authorization.
:vartype allocation_date: str
:param links: The set of physical links of the ExpressRoutePort resource.
:type links: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteLink]
:ivar circuits: Reference the ExpressRoute circuit(s) that are provisioned on this
ExpressRoutePort resource.
:vartype circuits: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar provisioning_state: The provisioning state of the ExpressRoutePort resource. Possible
values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param resource_guid: The resource GUID property of the ExpressRoutePort resource.
:type resource_guid: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioned_bandwidth_in_gbps': {'readonly': True},
'mtu': {'readonly': True},
'ether_type': {'readonly': True},
'allocation_date': {'readonly': True},
'circuits': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'peering_location': {'key': 'properties.peeringLocation', 'type': 'str'},
'bandwidth_in_gbps': {'key': 'properties.bandwidthInGbps', 'type': 'int'},
'provisioned_bandwidth_in_gbps': {'key': 'properties.provisionedBandwidthInGbps', 'type': 'float'},
'mtu': {'key': 'properties.mtu', 'type': 'str'},
'encapsulation': {'key': 'properties.encapsulation', 'type': 'str'},
'ether_type': {'key': 'properties.etherType', 'type': 'str'},
'allocation_date': {'key': 'properties.allocationDate', 'type': 'str'},
'links': {'key': 'properties.links', 'type': '[ExpressRouteLink]'},
'circuits': {'key': 'properties.circuits', 'type': '[SubResource]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePort, self).__init__(**kwargs)
self.etag = None
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_gbps = kwargs.get('bandwidth_in_gbps', None)
self.provisioned_bandwidth_in_gbps = None
self.mtu = None
self.encapsulation = kwargs.get('encapsulation', None)
self.ether_type = None
self.allocation_date = None
self.links = kwargs.get('links', None)
self.circuits = None
self.provisioning_state = None
self.resource_guid = kwargs.get('resource_guid', None)
class ExpressRoutePortListResult(msrest.serialization.Model):
"""Response for ListExpressRoutePorts API service call.
:param value: A list of ExpressRoutePort resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRoutePort]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRoutePort]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRoutePortsLocation(Resource):
"""Definition of the ExpressRoutePorts peering location resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar address: Address of peering location.
:vartype address: str
:ivar contact: Contact details of peering locations.
:vartype contact: str
:param available_bandwidths: The inventory of available ExpressRoutePort bandwidths.
:type available_bandwidths:
list[~azure.mgmt.network.v2019_04_01.models.ExpressRoutePortsLocationBandwidths]
:ivar provisioning_state: The provisioning state of the ExpressRoutePortLocation resource.
Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'address': {'readonly': True},
'contact': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'address': {'key': 'properties.address', 'type': 'str'},
'contact': {'key': 'properties.contact', 'type': 'str'},
'available_bandwidths': {'key': 'properties.availableBandwidths', 'type': '[ExpressRoutePortsLocationBandwidths]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocation, self).__init__(**kwargs)
self.address = None
self.contact = None
self.available_bandwidths = kwargs.get('available_bandwidths', None)
self.provisioning_state = None
class ExpressRoutePortsLocationBandwidths(msrest.serialization.Model):
"""Real-time inventory of available ExpressRoute port bandwidths.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar offer_name: Bandwidth descriptive name.
:vartype offer_name: str
:ivar value_in_gbps: Bandwidth value in Gbps.
:vartype value_in_gbps: int
"""
_validation = {
'offer_name': {'readonly': True},
'value_in_gbps': {'readonly': True},
}
_attribute_map = {
'offer_name': {'key': 'offerName', 'type': 'str'},
'value_in_gbps': {'key': 'valueInGbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocationBandwidths, self).__init__(**kwargs)
self.offer_name = None
self.value_in_gbps = None
class ExpressRoutePortsLocationListResult(msrest.serialization.Model):
"""Response for ListExpressRoutePortsLocations API service call.
:param value: The list of all ExpressRoutePort peering locations.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRoutePortsLocation]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRoutePortsLocation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRoutePortsLocationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ExpressRouteServiceProvider(Resource):
"""A ExpressRouteResourceProvider object.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param peering_locations: Get a list of peering locations.
:type peering_locations: list[str]
:param bandwidths_offered: Gets bandwidths offered.
:type bandwidths_offered:
list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteServiceProviderBandwidthsOffered]
:param provisioning_state: Gets the provisioning state of the resource.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'peering_locations': {'key': 'properties.peeringLocations', 'type': '[str]'},
'bandwidths_offered': {'key': 'properties.bandwidthsOffered', 'type': '[ExpressRouteServiceProviderBandwidthsOffered]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProvider, self).__init__(**kwargs)
self.peering_locations = kwargs.get('peering_locations', None)
self.bandwidths_offered = kwargs.get('bandwidths_offered', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ExpressRouteServiceProviderBandwidthsOffered(msrest.serialization.Model):
"""Contains bandwidths offered in ExpressRouteServiceProvider resources.
:param offer_name: The OfferName.
:type offer_name: str
:param value_in_mbps: The ValueInMbps.
:type value_in_mbps: int
"""
_attribute_map = {
'offer_name': {'key': 'offerName', 'type': 'str'},
'value_in_mbps': {'key': 'valueInMbps', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProviderBandwidthsOffered, self).__init__(**kwargs)
self.offer_name = kwargs.get('offer_name', None)
self.value_in_mbps = kwargs.get('value_in_mbps', None)
class ExpressRouteServiceProviderListResult(msrest.serialization.Model):
"""Response for the ListExpressRouteServiceProvider API service call.
:param value: A list of ExpressRouteResourceProvider resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteServiceProvider]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ExpressRouteServiceProvider]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ExpressRouteServiceProviderListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class FlowLogFormatParameters(msrest.serialization.Model):
"""Parameters that define the flow log format.
:param type: The file type of flow log. Possible values include: "JSON".
:type type: str or ~azure.mgmt.network.v2019_04_01.models.FlowLogFormatType
:param version: The version (revision) of the flow log.
:type version: int
"""
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'version': {'key': 'version', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(FlowLogFormatParameters, self).__init__(**kwargs)
self.type = kwargs.get('type', None)
self.version = kwargs.get('version', 0)
class FlowLogInformation(msrest.serialization.Model):
"""Information on the configuration of flow log and traffic analytics (optional) .
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the resource to configure for flow log and
traffic analytics (optional) .
:type target_resource_id: str
:param flow_analytics_configuration: Parameters that define the configuration of traffic
analytics.
:type flow_analytics_configuration:
~azure.mgmt.network.v2019_04_01.models.TrafficAnalyticsProperties
:param storage_id: Required. ID of the storage account which is used to store the flow log.
:type storage_id: str
:param enabled: Required. Flag to enable/disable flow logging.
:type enabled: bool
:param retention_policy: Parameters that define the retention policy for flow log.
:type retention_policy: ~azure.mgmt.network.v2019_04_01.models.RetentionPolicyParameters
:param format: Parameters that define the flow log format.
:type format: ~azure.mgmt.network.v2019_04_01.models.FlowLogFormatParameters
"""
_validation = {
'target_resource_id': {'required': True},
'storage_id': {'required': True},
'enabled': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'flow_analytics_configuration': {'key': 'flowAnalyticsConfiguration', 'type': 'TrafficAnalyticsProperties'},
'storage_id': {'key': 'properties.storageId', 'type': 'str'},
'enabled': {'key': 'properties.enabled', 'type': 'bool'},
'retention_policy': {'key': 'properties.retentionPolicy', 'type': 'RetentionPolicyParameters'},
'format': {'key': 'properties.format', 'type': 'FlowLogFormatParameters'},
}
def __init__(
self,
**kwargs
):
super(FlowLogInformation, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.flow_analytics_configuration = kwargs.get('flow_analytics_configuration', None)
self.storage_id = kwargs['storage_id']
self.enabled = kwargs['enabled']
self.retention_policy = kwargs.get('retention_policy', None)
self.format = kwargs.get('format', None)
class FlowLogStatusParameters(msrest.serialization.Model):
"""Parameters that define a resource to query flow log and traffic analytics (optional) status.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource where getting the flow log and traffic
analytics (optional) status.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FlowLogStatusParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class FrontendIPConfiguration(SubResource):
"""Frontend IP address of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:ivar inbound_nat_rules: Read only. Inbound rules URIs that use this frontend IP.
:vartype inbound_nat_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar inbound_nat_pools: Read only. Inbound pools URIs that use this frontend IP.
:vartype inbound_nat_pools: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar outbound_rules: Read only. Outbound rules URIs that use this frontend IP.
:vartype outbound_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar load_balancing_rules: Gets load balancing rules URIs that use this frontend IP.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The Private IP allocation method. Possible values include:
"Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param private_ip_address_version: It represents whether the specific ipconfiguration is IPv4
or IPv6. Default is taken as IPv4. Possible values include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2019_04_01.models.IPVersion
:param subnet: The reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:param public_ip_address: The reference of the Public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.PublicIPAddress
:param public_ip_prefix: The reference of the Public IP Prefix resource.
:type public_ip_prefix: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'inbound_nat_rules': {'readonly': True},
'inbound_nat_pools': {'readonly': True},
'outbound_rules': {'readonly': True},
'load_balancing_rules': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[SubResource]'},
'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[SubResource]'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[SubResource]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(FrontendIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.zones = kwargs.get('zones', None)
self.inbound_nat_rules = None
self.inbound_nat_pools = None
self.outbound_rules = None
self.load_balancing_rules = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.public_ip_prefix = kwargs.get('public_ip_prefix', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class GatewayRoute(msrest.serialization.Model):
"""Gateway routing details.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar local_address: The gateway's local address.
:vartype local_address: str
:ivar network: The route's network prefix.
:vartype network: str
:ivar next_hop: The route's next hop.
:vartype next_hop: str
:ivar source_peer: The peer this route was learned from.
:vartype source_peer: str
:ivar origin: The source this route was learned from.
:vartype origin: str
:ivar as_path: The route's AS path sequence.
:vartype as_path: str
:ivar weight: The route's weight.
:vartype weight: int
"""
_validation = {
'local_address': {'readonly': True},
'network': {'readonly': True},
'next_hop': {'readonly': True},
'source_peer': {'readonly': True},
'origin': {'readonly': True},
'as_path': {'readonly': True},
'weight': {'readonly': True},
}
_attribute_map = {
'local_address': {'key': 'localAddress', 'type': 'str'},
'network': {'key': 'network', 'type': 'str'},
'next_hop': {'key': 'nextHop', 'type': 'str'},
'source_peer': {'key': 'sourcePeer', 'type': 'str'},
'origin': {'key': 'origin', 'type': 'str'},
'as_path': {'key': 'asPath', 'type': 'str'},
'weight': {'key': 'weight', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(GatewayRoute, self).__init__(**kwargs)
self.local_address = None
self.network = None
self.next_hop = None
self.source_peer = None
self.origin = None
self.as_path = None
self.weight = None
class GatewayRouteListResult(msrest.serialization.Model):
"""List of virtual network gateway routes.
:param value: List of gateway routes.
:type value: list[~azure.mgmt.network.v2019_04_01.models.GatewayRoute]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[GatewayRoute]'},
}
def __init__(
self,
**kwargs
):
super(GatewayRouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class GetVpnSitesConfigurationRequest(msrest.serialization.Model):
"""List of Vpn-Sites.
All required parameters must be populated in order to send to Azure.
:param vpn_sites: List of resource-ids of the vpn-sites for which config is to be downloaded.
:type vpn_sites: list[str]
:param output_blob_sas_url: Required. The sas-url to download the configurations for vpn-sites.
:type output_blob_sas_url: str
"""
_validation = {
'output_blob_sas_url': {'required': True},
}
_attribute_map = {
'vpn_sites': {'key': 'vpnSites', 'type': '[str]'},
'output_blob_sas_url': {'key': 'outputBlobSasUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(GetVpnSitesConfigurationRequest, self).__init__(**kwargs)
self.vpn_sites = kwargs.get('vpn_sites', None)
self.output_blob_sas_url = kwargs['output_blob_sas_url']
class HTTPConfiguration(msrest.serialization.Model):
"""HTTP configuration of the connectivity check.
:param method: HTTP method. Possible values include: "Get".
:type method: str or ~azure.mgmt.network.v2019_04_01.models.HTTPMethod
:param headers: List of HTTP headers.
:type headers: list[~azure.mgmt.network.v2019_04_01.models.HTTPHeader]
:param valid_status_codes: Valid status codes.
:type valid_status_codes: list[int]
"""
_attribute_map = {
'method': {'key': 'method', 'type': 'str'},
'headers': {'key': 'headers', 'type': '[HTTPHeader]'},
'valid_status_codes': {'key': 'validStatusCodes', 'type': '[int]'},
}
def __init__(
self,
**kwargs
):
super(HTTPConfiguration, self).__init__(**kwargs)
self.method = kwargs.get('method', None)
self.headers = kwargs.get('headers', None)
self.valid_status_codes = kwargs.get('valid_status_codes', None)
class HTTPHeader(msrest.serialization.Model):
"""Describes the HTTP header.
:param name: The name in HTTP header.
:type name: str
:param value: The value in HTTP header.
:type value: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HTTPHeader, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.value = kwargs.get('value', None)
class HubVirtualNetworkConnection(SubResource):
"""HubVirtualNetworkConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param remote_virtual_network: Reference to the remote virtual network.
:type remote_virtual_network: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param allow_hub_to_remote_vnet_transit: VirtualHub to RemoteVnet transit to enabled or not.
:type allow_hub_to_remote_vnet_transit: bool
:param allow_remote_vnet_to_use_hub_vnet_gateways: Allow RemoteVnet to use Virtual Hub's
gateways.
:type allow_remote_vnet_to_use_hub_vnet_gateways: bool
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'},
'allow_hub_to_remote_vnet_transit': {'key': 'properties.allowHubToRemoteVnetTransit', 'type': 'bool'},
'allow_remote_vnet_to_use_hub_vnet_gateways': {'key': 'properties.allowRemoteVnetToUseHubVnetGateways', 'type': 'bool'},
'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(HubVirtualNetworkConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.remote_virtual_network = kwargs.get('remote_virtual_network', None)
self.allow_hub_to_remote_vnet_transit = kwargs.get('allow_hub_to_remote_vnet_transit', None)
self.allow_remote_vnet_to_use_hub_vnet_gateways = kwargs.get('allow_remote_vnet_to_use_hub_vnet_gateways', None)
self.enable_internet_security = kwargs.get('enable_internet_security', None)
self.provisioning_state = None
class InboundNatPool(SubResource):
"""Inbound NAT pool of the load balancer.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param protocol: The reference to the transport protocol used by the inbound NAT pool. Possible
values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.TransportProtocol
:param frontend_port_range_start: The first port number in the range of external ports that
will be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values
range between 1 and 65534.
:type frontend_port_range_start: int
:param frontend_port_range_end: The last port number in the range of external ports that will
be used to provide Inbound Nat to NICs associated with a load balancer. Acceptable values range
between 1 and 65535.
:type frontend_port_range_end: int
:param backend_port: The port used for internal connections on the endpoint. Acceptable values
are between 1 and 65535.
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'frontend_port_range_start': {'key': 'properties.frontendPortRangeStart', 'type': 'int'},
'frontend_port_range_end': {'key': 'properties.frontendPortRangeEnd', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatPool, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.protocol = kwargs.get('protocol', None)
self.frontend_port_range_start = kwargs.get('frontend_port_range_start', None)
self.frontend_port_range_end = kwargs.get('frontend_port_range_end', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class InboundNatRule(SubResource):
"""Inbound NAT rule of the load balancer.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar backend_ip_configuration: A reference to a private IP address defined on a network
interface of a VM. Traffic sent to the frontend port of each of the frontend IP configurations
is forwarded to the backend IP.
:vartype backend_ip_configuration:
~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration
:param protocol: The reference to the transport protocol used by the load balancing rule.
Possible values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.TransportProtocol
:param frontend_port: The port for the external endpoint. Port numbers for each rule must be
unique within the Load Balancer. Acceptable values range from 1 to 65534.
:type frontend_port: int
:param backend_port: The port used for the internal endpoint. Acceptable values range from 1 to
65535.
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'backend_ip_configuration': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'backend_ip_configuration': {'key': 'properties.backendIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.backend_ip_configuration = None
self.protocol = kwargs.get('protocol', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class InboundNatRuleListResult(msrest.serialization.Model):
"""Response for ListInboundNatRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of inbound nat rules in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.InboundNatRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[InboundNatRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(InboundNatRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class IPAddressAvailabilityResult(msrest.serialization.Model):
"""Response for CheckIPAddressAvailability API service call.
:param available: Private IP address availability.
:type available: bool
:param available_ip_addresses: Contains other available private IP addresses if the asked for
address is taken.
:type available_ip_addresses: list[str]
"""
_attribute_map = {
'available': {'key': 'available', 'type': 'bool'},
'available_ip_addresses': {'key': 'availableIPAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(IPAddressAvailabilityResult, self).__init__(**kwargs)
self.available = kwargs.get('available', None)
self.available_ip_addresses = kwargs.get('available_ip_addresses', None)
class IPConfiguration(SubResource):
"""IP configuration.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param subnet: The reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:param public_ip_address: The reference of the public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.PublicIPAddress
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class IPConfigurationProfile(SubResource):
"""IP configuration profile child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param subnet: The reference of the subnet resource to create a container network interface ip
configuration.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IPConfigurationProfile, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = kwargs.get('etag', None)
self.subnet = kwargs.get('subnet', None)
self.provisioning_state = None
class IpsecPolicy(msrest.serialization.Model):
"""An IPSec Policy configuration for a virtual network gateway connection.
All required parameters must be populated in order to send to Azure.
:param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) lifetime in seconds for a site to site VPN tunnel.
:type sa_life_time_seconds: int
:param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) payload size in KB for a site to site VPN tunnel.
:type sa_data_size_kilobytes: int
:param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible
values include: "None", "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES128", "GCMAES192",
"GCMAES256".
:type ipsec_encryption: str or ~azure.mgmt.network.v2019_04_01.models.IpsecEncryption
:param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values
include: "MD5", "SHA1", "SHA256", "GCMAES128", "GCMAES192", "GCMAES256".
:type ipsec_integrity: str or ~azure.mgmt.network.v2019_04_01.models.IpsecIntegrity
:param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values
include: "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES256", "GCMAES128".
:type ike_encryption: str or ~azure.mgmt.network.v2019_04_01.models.IkeEncryption
:param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values
include: "MD5", "SHA1", "SHA256", "SHA384", "GCMAES256", "GCMAES128".
:type ike_integrity: str or ~azure.mgmt.network.v2019_04_01.models.IkeIntegrity
:param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values
include: "None", "DHGroup1", "DHGroup2", "DHGroup14", "DHGroup2048", "ECP256", "ECP384",
"DHGroup24".
:type dh_group: str or ~azure.mgmt.network.v2019_04_01.models.DhGroup
:param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values
include: "None", "PFS1", "PFS2", "PFS2048", "ECP256", "ECP384", "PFS24", "PFS14", "PFSMM".
:type pfs_group: str or ~azure.mgmt.network.v2019_04_01.models.PfsGroup
"""
_validation = {
'sa_life_time_seconds': {'required': True},
'sa_data_size_kilobytes': {'required': True},
'ipsec_encryption': {'required': True},
'ipsec_integrity': {'required': True},
'ike_encryption': {'required': True},
'ike_integrity': {'required': True},
'dh_group': {'required': True},
'pfs_group': {'required': True},
}
_attribute_map = {
'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'},
'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'},
'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'},
'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'},
'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'},
'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'},
'dh_group': {'key': 'dhGroup', 'type': 'str'},
'pfs_group': {'key': 'pfsGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpsecPolicy, self).__init__(**kwargs)
self.sa_life_time_seconds = kwargs['sa_life_time_seconds']
self.sa_data_size_kilobytes = kwargs['sa_data_size_kilobytes']
self.ipsec_encryption = kwargs['ipsec_encryption']
self.ipsec_integrity = kwargs['ipsec_integrity']
self.ike_encryption = kwargs['ike_encryption']
self.ike_integrity = kwargs['ike_integrity']
self.dh_group = kwargs['dh_group']
self.pfs_group = kwargs['pfs_group']
class IpTag(msrest.serialization.Model):
"""Contains the IpTag associated with the object.
:param ip_tag_type: Gets or sets the ipTag type: Example FirstPartyUsage.
:type ip_tag_type: str
:param tag: Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage
etc.
:type tag: str
"""
_attribute_map = {
'ip_tag_type': {'key': 'ipTagType', 'type': 'str'},
'tag': {'key': 'tag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(IpTag, self).__init__(**kwargs)
self.ip_tag_type = kwargs.get('ip_tag_type', None)
self.tag = kwargs.get('tag', None)
class Ipv6ExpressRouteCircuitPeeringConfig(msrest.serialization.Model):
"""Contains IPv6 peering config.
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringConfig
:param route_filter: The reference of the RouteFilter resource.
:type route_filter: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param state: The state of peering. Possible values include: "Disabled", "Enabled".
:type state: str or ~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeeringState
"""
_attribute_map = {
'primary_peer_address_prefix': {'key': 'primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'secondaryPeerAddressPrefix', 'type': 'str'},
'microsoft_peering_config': {'key': 'microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'route_filter': {'key': 'routeFilter', 'type': 'SubResource'},
'state': {'key': 'state', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Ipv6ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.route_filter = kwargs.get('route_filter', None)
self.state = kwargs.get('state', None)
class ListHubVirtualNetworkConnectionsResult(msrest.serialization.Model):
"""List of HubVirtualNetworkConnections and a URL nextLink to get the next set of results.
:param value: List of HubVirtualNetworkConnections.
:type value: list[~azure.mgmt.network.v2019_04_01.models.HubVirtualNetworkConnection]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[HubVirtualNetworkConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListHubVirtualNetworkConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListP2SVpnGatewaysResult(msrest.serialization.Model):
"""Result of the request to list P2SVpnGateways. It contains a list of P2SVpnGateways and a URL nextLink to get the next set of results.
:param value: List of P2SVpnGateways.
:type value: list[~azure.mgmt.network.v2019_04_01.models.P2SVpnGateway]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[P2SVpnGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListP2SVpnGatewaysResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListP2SVpnServerConfigurationsResult(msrest.serialization.Model):
"""Result of the request to list all P2SVpnServerConfigurations associated to a VirtualWan. It contains a list of P2SVpnServerConfigurations and a URL nextLink to get the next set of results.
:param value: List of P2SVpnServerConfigurations.
:type value: list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfiguration]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[P2SVpnServerConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListP2SVpnServerConfigurationsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVirtualHubsResult(msrest.serialization.Model):
"""Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink to get the next set of results.
:param value: List of VirtualHubs.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualHub]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualHub]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVirtualHubsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVirtualWANsResult(msrest.serialization.Model):
"""Result of the request to list VirtualWANs. It contains a list of VirtualWANs and a URL nextLink to get the next set of results.
:param value: List of VirtualWANs.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualWAN]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualWAN]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVirtualWANsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnConnectionsResult(msrest.serialization.Model):
"""Result of the request to list all vpn connections to a virtual wan vpn gateway. It contains a list of Vpn Connections and a URL nextLink to get the next set of results.
:param value: List of Vpn Connections.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VpnConnection]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnGatewaysResult(msrest.serialization.Model):
"""Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink to get the next set of results.
:param value: List of VpnGateways.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VpnGateway]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnGatewaysResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ListVpnSitesResult(msrest.serialization.Model):
"""Result of the request to list VpnSites. It contains a list of VpnSites and a URL nextLink to get the next set of results.
:param value: List of VpnSites.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VpnSite]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnSite]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ListVpnSitesResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class LoadBalancer(Resource):
"""LoadBalancer resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The load balancer SKU.
:type sku: ~azure.mgmt.network.v2019_04_01.models.LoadBalancerSku
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param frontend_ip_configurations: Object representing the frontend IPs to be used for the load
balancer.
:type frontend_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.FrontendIPConfiguration]
:param backend_address_pools: Collection of backend address pools used by a load balancer.
:type backend_address_pools: list[~azure.mgmt.network.v2019_04_01.models.BackendAddressPool]
:param load_balancing_rules: Object collection representing the load balancing rules Gets the
provisioning.
:type load_balancing_rules: list[~azure.mgmt.network.v2019_04_01.models.LoadBalancingRule]
:param probes: Collection of probe objects used in the load balancer.
:type probes: list[~azure.mgmt.network.v2019_04_01.models.Probe]
:param inbound_nat_rules: Collection of inbound NAT Rules used by a load balancer. Defining
inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT
pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are
associated with individual virtual machines cannot reference an Inbound NAT pool. They have to
reference individual inbound NAT rules.
:type inbound_nat_rules: list[~azure.mgmt.network.v2019_04_01.models.InboundNatRule]
:param inbound_nat_pools: Defines an external port range for inbound NAT to a single backend
port on NICs associated with a load balancer. Inbound NAT rules are created automatically for
each NIC associated with the Load Balancer using an external port from this range. Defining an
Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules.
Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with
individual virtual machines cannot reference an inbound NAT pool. They have to reference
individual inbound NAT rules.
:type inbound_nat_pools: list[~azure.mgmt.network.v2019_04_01.models.InboundNatPool]
:param outbound_rules: The outbound rules.
:type outbound_rules: list[~azure.mgmt.network.v2019_04_01.models.OutboundRule]
:param resource_guid: The resource GUID property of the load balancer resource.
:type resource_guid: str
:param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'LoadBalancerSku'},
'etag': {'key': 'etag', 'type': 'str'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[FrontendIPConfiguration]'},
'backend_address_pools': {'key': 'properties.backendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[LoadBalancingRule]'},
'probes': {'key': 'properties.probes', 'type': '[Probe]'},
'inbound_nat_rules': {'key': 'properties.inboundNatRules', 'type': '[InboundNatRule]'},
'inbound_nat_pools': {'key': 'properties.inboundNatPools', 'type': '[InboundNatPool]'},
'outbound_rules': {'key': 'properties.outboundRules', 'type': '[OutboundRule]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancer, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = kwargs.get('etag', None)
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.backend_address_pools = kwargs.get('backend_address_pools', None)
self.load_balancing_rules = kwargs.get('load_balancing_rules', None)
self.probes = kwargs.get('probes', None)
self.inbound_nat_rules = kwargs.get('inbound_nat_rules', None)
self.inbound_nat_pools = kwargs.get('inbound_nat_pools', None)
self.outbound_rules = kwargs.get('outbound_rules', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class LoadBalancerBackendAddressPoolListResult(msrest.serialization.Model):
"""Response for ListBackendAddressPool API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of backend address pools in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.BackendAddressPool]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[BackendAddressPool]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerBackendAddressPoolListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerFrontendIPConfigurationListResult(msrest.serialization.Model):
"""Response for ListFrontendIPConfiguration API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of frontend IP configurations in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.FrontendIPConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[FrontendIPConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerFrontendIPConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerListResult(msrest.serialization.Model):
"""Response for ListLoadBalancers API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancers in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.LoadBalancer]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancer]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerLoadBalancingRuleListResult(msrest.serialization.Model):
"""Response for ListLoadBalancingRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancing rules in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.LoadBalancingRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancingRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerLoadBalancingRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerOutboundRuleListResult(msrest.serialization.Model):
"""Response for ListOutboundRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of outbound rules in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.OutboundRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[OutboundRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerOutboundRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerProbeListResult(msrest.serialization.Model):
"""Response for ListProbe API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of probes in a load balancer.
:type value: list[~azure.mgmt.network.v2019_04_01.models.Probe]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[Probe]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerProbeListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LoadBalancerSku(msrest.serialization.Model):
"""SKU of a load balancer.
:param name: Name of a load balancer SKU. Possible values include: "Basic", "Standard".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.LoadBalancerSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancerSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class LoadBalancingRule(SubResource):
"""A load balancing rule for a load balancer.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param frontend_ip_configuration: A reference to frontend IP addresses.
:type frontend_ip_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param backend_address_pool: A reference to a pool of DIPs. Inbound traffic is randomly load
balanced across IPs in the backend IPs.
:type backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param probe: The reference of the load balancer probe used by the load balancing rule.
:type probe: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param protocol: The reference to the transport protocol used by the load balancing rule.
Possible values include: "Udp", "Tcp", "All".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.TransportProtocol
:param load_distribution: The load distribution policy for this rule. Possible values include:
"Default", "SourceIP", "SourceIPProtocol".
:type load_distribution: str or ~azure.mgmt.network.v2019_04_01.models.LoadDistribution
:param frontend_port: The port for the external endpoint. Port numbers for each rule must be
unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0
enables "Any Port".
:type frontend_port: int
:param backend_port: The port used for internal connections on the endpoint. Acceptable values
are between 0 and 65535. Note that value 0 enables "Any Port".
:type backend_port: int
:param idle_timeout_in_minutes: The timeout for the TCP idle connection. The value can be set
between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the
protocol is set to TCP.
:type idle_timeout_in_minutes: int
:param enable_floating_ip: Configures a virtual machine's endpoint for the floating IP
capability required to configure a SQL AlwaysOn Availability Group. This setting is required
when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed
after you create the endpoint.
:type enable_floating_ip: bool
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param disable_outbound_snat: Configures SNAT for the VMs in the backend pool to use the
publicIP address specified in the frontend of the load balancing rule.
:type disable_outbound_snat: bool
:param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'probe': {'key': 'properties.probe', 'type': 'SubResource'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'load_distribution': {'key': 'properties.loadDistribution', 'type': 'str'},
'frontend_port': {'key': 'properties.frontendPort', 'type': 'int'},
'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'disable_outbound_snat': {'key': 'properties.disableOutboundSnat', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LoadBalancingRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.probe = kwargs.get('probe', None)
self.protocol = kwargs.get('protocol', None)
self.load_distribution = kwargs.get('load_distribution', None)
self.frontend_port = kwargs.get('frontend_port', None)
self.backend_port = kwargs.get('backend_port', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.disable_outbound_snat = kwargs.get('disable_outbound_snat', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class LocalNetworkGateway(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param local_network_address_space: Local network site address space.
:type local_network_address_space: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param gateway_ip_address: IP address of local network gateway.
:type gateway_ip_address: str
:param bgp_settings: Local network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2019_04_01.models.BgpSettings
:param resource_guid: The resource GUID property of the LocalNetworkGateway resource.
:type resource_guid: str
:ivar provisioning_state: The provisioning state of the LocalNetworkGateway resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'local_network_address_space': {'key': 'properties.localNetworkAddressSpace', 'type': 'AddressSpace'},
'gateway_ip_address': {'key': 'properties.gatewayIpAddress', 'type': 'str'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LocalNetworkGateway, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.local_network_address_space = kwargs.get('local_network_address_space', None)
self.gateway_ip_address = kwargs.get('gateway_ip_address', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = None
class LocalNetworkGatewayListResult(msrest.serialization.Model):
"""Response for ListLocalNetworkGateways API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of local network gateways that exists in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.LocalNetworkGateway]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LocalNetworkGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LocalNetworkGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class LogSpecification(msrest.serialization.Model):
"""Description of logging specification.
:param name: The name of the specification.
:type name: str
:param display_name: The display name of the specification.
:type display_name: str
:param blob_duration: Duration of the blob.
:type blob_duration: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'blob_duration': {'key': 'blobDuration', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(LogSpecification, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.blob_duration = kwargs.get('blob_duration', None)
class ManagedServiceIdentity(msrest.serialization.Model):
"""Identity for the resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of the system assigned identity. This property will only
be provided for a system assigned identity.
:vartype principal_id: str
:ivar tenant_id: The tenant id of the system assigned identity. This property will only be
provided for a system assigned identity.
:vartype tenant_id: str
:param type: The type of identity used for the resource. The type 'SystemAssigned,
UserAssigned' includes both an implicitly created identity and a set of user assigned
identities. The type 'None' will remove any identities from the virtual machine. Possible
values include: "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned", "None".
:type type: str or ~azure.mgmt.network.v2019_04_01.models.ResourceIdentityType
:param user_assigned_identities: The list of user identities associated with resource. The user
identity dictionary key references will be ARM resource ids in the form:
'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
:type user_assigned_identities: dict[str,
~azure.mgmt.network.v2019_04_01.models.Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties]
"""
_validation = {
'principal_id': {'readonly': True},
'tenant_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties}'},
}
def __init__(
self,
**kwargs
):
super(ManagedServiceIdentity, self).__init__(**kwargs)
self.principal_id = None
self.tenant_id = None
self.type = kwargs.get('type', None)
self.user_assigned_identities = kwargs.get('user_assigned_identities', None)
class MatchCondition(msrest.serialization.Model):
"""Define match conditions.
All required parameters must be populated in order to send to Azure.
:param match_variables: Required. List of match variables.
:type match_variables: list[~azure.mgmt.network.v2019_04_01.models.MatchVariable]
:param operator: Required. Describes operator to be matched. Possible values include:
"IPMatch", "Equal", "Contains", "LessThan", "GreaterThan", "LessThanOrEqual",
"GreaterThanOrEqual", "BeginsWith", "EndsWith", "Regex".
:type operator: str or ~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallOperator
:param negation_conditon: Describes if this is negate condition or not.
:type negation_conditon: bool
:param match_values: Required. Match value.
:type match_values: list[str]
:param transforms: List of transforms.
:type transforms: list[str or
~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallTransform]
"""
_validation = {
'match_variables': {'required': True},
'operator': {'required': True},
'match_values': {'required': True},
}
_attribute_map = {
'match_variables': {'key': 'matchVariables', 'type': '[MatchVariable]'},
'operator': {'key': 'operator', 'type': 'str'},
'negation_conditon': {'key': 'negationConditon', 'type': 'bool'},
'match_values': {'key': 'matchValues', 'type': '[str]'},
'transforms': {'key': 'transforms', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(MatchCondition, self).__init__(**kwargs)
self.match_variables = kwargs['match_variables']
self.operator = kwargs['operator']
self.negation_conditon = kwargs.get('negation_conditon', None)
self.match_values = kwargs['match_values']
self.transforms = kwargs.get('transforms', None)
class MatchedRule(msrest.serialization.Model):
"""Matched rule.
:param rule_name: Name of the matched network security rule.
:type rule_name: str
:param action: The network traffic is allowed or denied. Possible values are 'Allow' and
'Deny'.
:type action: str
"""
_attribute_map = {
'rule_name': {'key': 'ruleName', 'type': 'str'},
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MatchedRule, self).__init__(**kwargs)
self.rule_name = kwargs.get('rule_name', None)
self.action = kwargs.get('action', None)
class MatchVariable(msrest.serialization.Model):
"""Define match variables.
All required parameters must be populated in order to send to Azure.
:param variable_name: Required. Match Variable. Possible values include: "RemoteAddr",
"RequestMethod", "QueryString", "PostArgs", "RequestUri", "RequestHeaders", "RequestBody",
"RequestCookies".
:type variable_name: str or
~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallMatchVariable
:param selector: Describes field of the matchVariable collection.
:type selector: str
"""
_validation = {
'variable_name': {'required': True},
}
_attribute_map = {
'variable_name': {'key': 'variableName', 'type': 'str'},
'selector': {'key': 'selector', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MatchVariable, self).__init__(**kwargs)
self.variable_name = kwargs['variable_name']
self.selector = kwargs.get('selector', None)
class MetricSpecification(msrest.serialization.Model):
"""Description of metrics specification.
:param name: The name of the metric.
:type name: str
:param display_name: The display name of the metric.
:type display_name: str
:param display_description: The description of the metric.
:type display_description: str
:param unit: Units the metric to be displayed in.
:type unit: str
:param aggregation_type: The aggregation type.
:type aggregation_type: str
:param availabilities: List of availability.
:type availabilities: list[~azure.mgmt.network.v2019_04_01.models.Availability]
:param enable_regional_mdm_account: Whether regional MDM account enabled.
:type enable_regional_mdm_account: bool
:param fill_gap_with_zero: Whether gaps would be filled with zeros.
:type fill_gap_with_zero: bool
:param metric_filter_pattern: Pattern for the filter of the metric.
:type metric_filter_pattern: str
:param dimensions: List of dimensions.
:type dimensions: list[~azure.mgmt.network.v2019_04_01.models.Dimension]
:param is_internal: Whether the metric is internal.
:type is_internal: bool
:param source_mdm_account: The source MDM account.
:type source_mdm_account: str
:param source_mdm_namespace: The source MDM namespace.
:type source_mdm_namespace: str
:param resource_id_dimension_name_override: The resource Id dimension name override.
:type resource_id_dimension_name_override: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'display_description': {'key': 'displayDescription', 'type': 'str'},
'unit': {'key': 'unit', 'type': 'str'},
'aggregation_type': {'key': 'aggregationType', 'type': 'str'},
'availabilities': {'key': 'availabilities', 'type': '[Availability]'},
'enable_regional_mdm_account': {'key': 'enableRegionalMdmAccount', 'type': 'bool'},
'fill_gap_with_zero': {'key': 'fillGapWithZero', 'type': 'bool'},
'metric_filter_pattern': {'key': 'metricFilterPattern', 'type': 'str'},
'dimensions': {'key': 'dimensions', 'type': '[Dimension]'},
'is_internal': {'key': 'isInternal', 'type': 'bool'},
'source_mdm_account': {'key': 'sourceMdmAccount', 'type': 'str'},
'source_mdm_namespace': {'key': 'sourceMdmNamespace', 'type': 'str'},
'resource_id_dimension_name_override': {'key': 'resourceIdDimensionNameOverride', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(MetricSpecification, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display_name = kwargs.get('display_name', None)
self.display_description = kwargs.get('display_description', None)
self.unit = kwargs.get('unit', None)
self.aggregation_type = kwargs.get('aggregation_type', None)
self.availabilities = kwargs.get('availabilities', None)
self.enable_regional_mdm_account = kwargs.get('enable_regional_mdm_account', None)
self.fill_gap_with_zero = kwargs.get('fill_gap_with_zero', None)
self.metric_filter_pattern = kwargs.get('metric_filter_pattern', None)
self.dimensions = kwargs.get('dimensions', None)
self.is_internal = kwargs.get('is_internal', None)
self.source_mdm_account = kwargs.get('source_mdm_account', None)
self.source_mdm_namespace = kwargs.get('source_mdm_namespace', None)
self.resource_id_dimension_name_override = kwargs.get('resource_id_dimension_name_override', None)
class NatGateway(Resource):
"""Nat Gateway resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The nat gateway SKU.
:type sku: ~azure.mgmt.network.v2019_04_01.models.NatGatewaySku
:param zones: A list of availability zones denoting the zone in which Nat Gateway should be
deployed.
:type zones: list[str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param idle_timeout_in_minutes: The idle timeout of the nat gateway.
:type idle_timeout_in_minutes: int
:param public_ip_addresses: An array of public ip addresses associated with the nat gateway
resource.
:type public_ip_addresses: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param public_ip_prefixes: An array of public ip prefixes associated with the nat gateway
resource.
:type public_ip_prefixes: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar subnets: An array of references to the subnets using this nat gateway resource.
:vartype subnets: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param resource_guid: The resource GUID property of the nat gateway resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the NatGateway resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'subnets': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'NatGatewaySku'},
'zones': {'key': 'zones', 'type': '[str]'},
'etag': {'key': 'etag', 'type': 'str'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'public_ip_addresses': {'key': 'properties.publicIpAddresses', 'type': '[SubResource]'},
'public_ip_prefixes': {'key': 'properties.publicIpPrefixes', 'type': '[SubResource]'},
'subnets': {'key': 'properties.subnets', 'type': '[SubResource]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGateway, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.zones = kwargs.get('zones', None)
self.etag = kwargs.get('etag', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.public_ip_addresses = kwargs.get('public_ip_addresses', None)
self.public_ip_prefixes = kwargs.get('public_ip_prefixes', None)
self.subnets = None
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class NatGatewayListResult(msrest.serialization.Model):
"""Response for ListNatGateways API service call.
:param value: A list of Nat Gateways that exists in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NatGateway]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NatGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NatGatewaySku(msrest.serialization.Model):
"""SKU of nat gateway.
:param name: Name of Nat Gateway SKU. Possible values include: "Standard".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.NatGatewaySkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NatGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class NetworkConfigurationDiagnosticParameters(msrest.serialization.Model):
"""Parameters to get network configuration diagnostic.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the target resource to perform network
configuration diagnostic. Valid options are VM, NetworkInterface, VMSS/NetworkInterface and
Application Gateway.
:type target_resource_id: str
:param verbosity_level: Verbosity level. Possible values include: "Normal", "Minimum", "Full".
:type verbosity_level: str or ~azure.mgmt.network.v2019_04_01.models.VerbosityLevel
:param profiles: Required. List of network configuration diagnostic profiles.
:type profiles:
list[~azure.mgmt.network.v2019_04_01.models.NetworkConfigurationDiagnosticProfile]
"""
_validation = {
'target_resource_id': {'required': True},
'profiles': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'verbosity_level': {'key': 'verbosityLevel', 'type': 'str'},
'profiles': {'key': 'profiles', 'type': '[NetworkConfigurationDiagnosticProfile]'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.verbosity_level = kwargs.get('verbosity_level', None)
self.profiles = kwargs['profiles']
class NetworkConfigurationDiagnosticProfile(msrest.serialization.Model):
"""Parameters to compare with network configuration.
All required parameters must be populated in order to send to Azure.
:param direction: Required. The direction of the traffic. Possible values include: "Inbound",
"Outbound".
:type direction: str or ~azure.mgmt.network.v2019_04_01.models.Direction
:param protocol: Required. Protocol to be verified on. Accepted values are '*', TCP, UDP.
:type protocol: str
:param source: Required. Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag.
:type source: str
:param destination: Required. Traffic destination. Accepted values are: '*', IP Address/CIDR,
Service Tag.
:type destination: str
:param destination_port: Required. Traffic destination port. Accepted values are '*', port (for
example, 3389) and port range (for example, 80-100).
:type destination_port: str
"""
_validation = {
'direction': {'required': True},
'protocol': {'required': True},
'source': {'required': True},
'destination': {'required': True},
'destination_port': {'required': True},
}
_attribute_map = {
'direction': {'key': 'direction', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'},
'destination': {'key': 'destination', 'type': 'str'},
'destination_port': {'key': 'destinationPort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticProfile, self).__init__(**kwargs)
self.direction = kwargs['direction']
self.protocol = kwargs['protocol']
self.source = kwargs['source']
self.destination = kwargs['destination']
self.destination_port = kwargs['destination_port']
class NetworkConfigurationDiagnosticResponse(msrest.serialization.Model):
"""Results of network configuration diagnostic on the target resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar results: List of network configuration diagnostic results.
:vartype results:
list[~azure.mgmt.network.v2019_04_01.models.NetworkConfigurationDiagnosticResult]
"""
_validation = {
'results': {'readonly': True},
}
_attribute_map = {
'results': {'key': 'results', 'type': '[NetworkConfigurationDiagnosticResult]'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticResponse, self).__init__(**kwargs)
self.results = None
class NetworkConfigurationDiagnosticResult(msrest.serialization.Model):
"""Network configuration diagnostic result corresponded to provided traffic query.
:param profile: Network configuration diagnostic profile.
:type profile: ~azure.mgmt.network.v2019_04_01.models.NetworkConfigurationDiagnosticProfile
:param network_security_group_result: Network security group result.
:type network_security_group_result:
~azure.mgmt.network.v2019_04_01.models.NetworkSecurityGroupResult
"""
_attribute_map = {
'profile': {'key': 'profile', 'type': 'NetworkConfigurationDiagnosticProfile'},
'network_security_group_result': {'key': 'networkSecurityGroupResult', 'type': 'NetworkSecurityGroupResult'},
}
def __init__(
self,
**kwargs
):
super(NetworkConfigurationDiagnosticResult, self).__init__(**kwargs)
self.profile = kwargs.get('profile', None)
self.network_security_group_result = kwargs.get('network_security_group_result', None)
class NetworkIntentPolicy(Resource):
"""Network Intent Policy resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkIntentPolicy, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
class NetworkIntentPolicyConfiguration(msrest.serialization.Model):
"""Details of NetworkIntentPolicyConfiguration for PrepareNetworkPoliciesRequest.
:param network_intent_policy_name: The name of the Network Intent Policy for storing in target
subscription.
:type network_intent_policy_name: str
:param source_network_intent_policy: Source network intent policy.
:type source_network_intent_policy: ~azure.mgmt.network.v2019_04_01.models.NetworkIntentPolicy
"""
_attribute_map = {
'network_intent_policy_name': {'key': 'networkIntentPolicyName', 'type': 'str'},
'source_network_intent_policy': {'key': 'sourceNetworkIntentPolicy', 'type': 'NetworkIntentPolicy'},
}
def __init__(
self,
**kwargs
):
super(NetworkIntentPolicyConfiguration, self).__init__(**kwargs)
self.network_intent_policy_name = kwargs.get('network_intent_policy_name', None)
self.source_network_intent_policy = kwargs.get('source_network_intent_policy', None)
class NetworkInterface(Resource):
"""A network interface in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar virtual_machine: The reference of a virtual machine.
:vartype virtual_machine: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param network_security_group: The reference of the NetworkSecurityGroup resource.
:type network_security_group: ~azure.mgmt.network.v2019_04_01.models.NetworkSecurityGroup
:ivar private_endpoint: A reference to the private endpoint to which the network interface is
linked.
:vartype private_endpoint: ~azure.mgmt.network.v2019_04_01.models.PrivateEndpoint
:param ip_configurations: A list of IPConfigurations of the network interface.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration]
:param tap_configurations: A list of TapConfigurations of the network interface.
:type tap_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceTapConfiguration]
:param dns_settings: The DNS settings in network interface.
:type dns_settings: ~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceDnsSettings
:param mac_address: The MAC address of the network interface.
:type mac_address: str
:param primary: Gets whether this is a primary network interface on a virtual machine.
:type primary: bool
:param enable_accelerated_networking: If the network interface is accelerated networking
enabled.
:type enable_accelerated_networking: bool
:param enable_ip_forwarding: Indicates whether IP forwarding is enabled on this network
interface.
:type enable_ip_forwarding: bool
:ivar hosted_workloads: A list of references to linked BareMetal resources.
:vartype hosted_workloads: list[str]
:param resource_guid: The resource GUID property of the network interface resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the public IP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_machine': {'readonly': True},
'private_endpoint': {'readonly': True},
'hosted_workloads': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_machine': {'key': 'properties.virtualMachine', 'type': 'SubResource'},
'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'},
'tap_configurations': {'key': 'properties.tapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'},
'dns_settings': {'key': 'properties.dnsSettings', 'type': 'NetworkInterfaceDnsSettings'},
'mac_address': {'key': 'properties.macAddress', 'type': 'str'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'enable_accelerated_networking': {'key': 'properties.enableAcceleratedNetworking', 'type': 'bool'},
'enable_ip_forwarding': {'key': 'properties.enableIPForwarding', 'type': 'bool'},
'hosted_workloads': {'key': 'properties.hostedWorkloads', 'type': '[str]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterface, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.virtual_machine = None
self.network_security_group = kwargs.get('network_security_group', None)
self.private_endpoint = None
self.ip_configurations = kwargs.get('ip_configurations', None)
self.tap_configurations = kwargs.get('tap_configurations', None)
self.dns_settings = kwargs.get('dns_settings', None)
self.mac_address = kwargs.get('mac_address', None)
self.primary = kwargs.get('primary', None)
self.enable_accelerated_networking = kwargs.get('enable_accelerated_networking', None)
self.enable_ip_forwarding = kwargs.get('enable_ip_forwarding', None)
self.hosted_workloads = None
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class NetworkInterfaceAssociation(msrest.serialization.Model):
"""Network interface and its custom security rules.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Network interface ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
class NetworkInterfaceDnsSettings(msrest.serialization.Model):
"""DNS settings of a network interface.
:param dns_servers: List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure
provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be
the only value in dnsServers collection.
:type dns_servers: list[str]
:param applied_dns_servers: If the VM that uses this NIC is part of an Availability Set, then
this list will have the union of all DNS servers from all NICs that are part of the
Availability Set. This property is what is configured on each of those VMs.
:type applied_dns_servers: list[str]
:param internal_dns_name_label: Relative DNS name for this NIC used for internal communications
between VMs in the same virtual network.
:type internal_dns_name_label: str
:param internal_fqdn: Fully qualified DNS name supporting internal communications between VMs
in the same virtual network.
:type internal_fqdn: str
:param internal_domain_name_suffix: Even if internalDnsNameLabel is not specified, a DNS entry
is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the
VM name with the value of internalDomainNameSuffix.
:type internal_domain_name_suffix: str
"""
_attribute_map = {
'dns_servers': {'key': 'dnsServers', 'type': '[str]'},
'applied_dns_servers': {'key': 'appliedDnsServers', 'type': '[str]'},
'internal_dns_name_label': {'key': 'internalDnsNameLabel', 'type': 'str'},
'internal_fqdn': {'key': 'internalFqdn', 'type': 'str'},
'internal_domain_name_suffix': {'key': 'internalDomainNameSuffix', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceDnsSettings, self).__init__(**kwargs)
self.dns_servers = kwargs.get('dns_servers', None)
self.applied_dns_servers = kwargs.get('applied_dns_servers', None)
self.internal_dns_name_label = kwargs.get('internal_dns_name_label', None)
self.internal_fqdn = kwargs.get('internal_fqdn', None)
self.internal_domain_name_suffix = kwargs.get('internal_domain_name_suffix', None)
class NetworkInterfaceIPConfiguration(SubResource):
"""IPConfiguration in a network interface.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param virtual_network_taps: The reference to Virtual Network Taps.
:type virtual_network_taps: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkTap]
:param application_gateway_backend_address_pools: The reference of
ApplicationGatewayBackendAddressPool resource.
:type application_gateway_backend_address_pools:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendAddressPool]
:param load_balancer_backend_address_pools: The reference of LoadBalancerBackendAddressPool
resource.
:type load_balancer_backend_address_pools:
list[~azure.mgmt.network.v2019_04_01.models.BackendAddressPool]
:param load_balancer_inbound_nat_rules: A list of references of LoadBalancerInboundNatRules.
:type load_balancer_inbound_nat_rules:
list[~azure.mgmt.network.v2019_04_01.models.InboundNatRule]
:param private_ip_address: Private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param private_ip_address_version: Available from Api-Version 2016-03-30 onwards, it represents
whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values
include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2019_04_01.models.IPVersion
:param subnet: Subnet bound to the IP configuration.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:param primary: Gets whether this is a primary customer address on the network interface.
:type primary: bool
:param public_ip_address: Public IP address bound to the IP configuration.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.PublicIPAddress
:param application_security_groups: Application security groups in which the IP configuration
is included.
:type application_security_groups:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationSecurityGroup]
:param provisioning_state: The provisioning state of the network interface IP configuration.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_network_taps': {'key': 'properties.virtualNetworkTaps', 'type': '[VirtualNetworkTap]'},
'application_gateway_backend_address_pools': {'key': 'properties.applicationGatewayBackendAddressPools', 'type': '[ApplicationGatewayBackendAddressPool]'},
'load_balancer_backend_address_pools': {'key': 'properties.loadBalancerBackendAddressPools', 'type': '[BackendAddressPool]'},
'load_balancer_inbound_nat_rules': {'key': 'properties.loadBalancerInboundNatRules', 'type': '[InboundNatRule]'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'PublicIPAddress'},
'application_security_groups': {'key': 'properties.applicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.virtual_network_taps = kwargs.get('virtual_network_taps', None)
self.application_gateway_backend_address_pools = kwargs.get('application_gateway_backend_address_pools', None)
self.load_balancer_backend_address_pools = kwargs.get('load_balancer_backend_address_pools', None)
self.load_balancer_inbound_nat_rules = kwargs.get('load_balancer_inbound_nat_rules', None)
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
self.subnet = kwargs.get('subnet', None)
self.primary = kwargs.get('primary', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.application_security_groups = kwargs.get('application_security_groups', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class NetworkInterfaceIPConfigurationListResult(msrest.serialization.Model):
"""Response for list ip configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ip configurations.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterfaceIPConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceIPConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceListResult(msrest.serialization.Model):
"""Response for the ListNetworkInterface API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of network interfaces in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterface]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterface]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceLoadBalancerListResult(msrest.serialization.Model):
"""Response for list ip configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of load balancers.
:type value: list[~azure.mgmt.network.v2019_04_01.models.LoadBalancer]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[LoadBalancer]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceLoadBalancerListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkInterfaceTapConfiguration(SubResource):
"""Tap configuration in a Network Interface.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar type: Sub Resource type.
:vartype type: str
:param virtual_network_tap: The reference of the Virtual Network Tap resource.
:type virtual_network_tap: ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkTap
:ivar provisioning_state: The provisioning state of the network interface tap configuration.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'virtual_network_tap': {'key': 'properties.virtualNetworkTap', 'type': 'VirtualNetworkTap'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceTapConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.type = None
self.virtual_network_tap = kwargs.get('virtual_network_tap', None)
self.provisioning_state = None
class NetworkInterfaceTapConfigurationListResult(msrest.serialization.Model):
"""Response for list tap configurations API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of tap configurations.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceTapConfiguration]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkInterfaceTapConfiguration]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkInterfaceTapConfigurationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class NetworkProfile(Resource):
"""Network profile resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param container_network_interfaces: List of child container network interfaces.
:type container_network_interfaces:
list[~azure.mgmt.network.v2019_04_01.models.ContainerNetworkInterface]
:param container_network_interface_configurations: List of chid container network interface
configurations.
:type container_network_interface_configurations:
list[~azure.mgmt.network.v2019_04_01.models.ContainerNetworkInterfaceConfiguration]
:ivar resource_guid: The resource GUID property of the network interface resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the resource.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'container_network_interfaces': {'key': 'properties.containerNetworkInterfaces', 'type': '[ContainerNetworkInterface]'},
'container_network_interface_configurations': {'key': 'properties.containerNetworkInterfaceConfigurations', 'type': '[ContainerNetworkInterfaceConfiguration]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkProfile, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.container_network_interfaces = kwargs.get('container_network_interfaces', None)
self.container_network_interface_configurations = kwargs.get('container_network_interface_configurations', None)
self.resource_guid = None
self.provisioning_state = None
class NetworkProfileListResult(msrest.serialization.Model):
"""Response for ListNetworkProfiles API service call.
:param value: A list of network profiles that exist in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkProfile]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkProfile]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkProfileListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NetworkSecurityGroup(Resource):
"""NetworkSecurityGroup resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param security_rules: A collection of security rules of the network security group.
:type security_rules: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
:param default_security_rules: The default security rules of network security group.
:type default_security_rules: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
:ivar network_interfaces: A collection of references to network interfaces.
:vartype network_interfaces: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterface]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2019_04_01.models.Subnet]
:param resource_guid: The resource GUID property of the network security group resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the public IP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'network_interfaces': {'readonly': True},
'subnets': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'security_rules': {'key': 'properties.securityRules', 'type': '[SecurityRule]'},
'default_security_rules': {'key': 'properties.defaultSecurityRules', 'type': '[SecurityRule]'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroup, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.security_rules = kwargs.get('security_rules', None)
self.default_security_rules = kwargs.get('default_security_rules', None)
self.network_interfaces = None
self.subnets = None
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class NetworkSecurityGroupListResult(msrest.serialization.Model):
"""Response for ListNetworkSecurityGroups API service call.
:param value: A list of NetworkSecurityGroup resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkSecurityGroup]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkSecurityGroup]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroupListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class NetworkSecurityGroupResult(msrest.serialization.Model):
"""Network configuration diagnostic result corresponded provided traffic query.
Variables are only populated by the server, and will be ignored when sending a request.
:param security_rule_access_result: The network traffic is allowed or denied. Possible values
include: "Allow", "Deny".
:type security_rule_access_result: str or
~azure.mgmt.network.v2019_04_01.models.SecurityRuleAccess
:ivar evaluated_network_security_groups: List of results network security groups diagnostic.
:vartype evaluated_network_security_groups:
list[~azure.mgmt.network.v2019_04_01.models.EvaluatedNetworkSecurityGroup]
"""
_validation = {
'evaluated_network_security_groups': {'readonly': True},
}
_attribute_map = {
'security_rule_access_result': {'key': 'securityRuleAccessResult', 'type': 'str'},
'evaluated_network_security_groups': {'key': 'evaluatedNetworkSecurityGroups', 'type': '[EvaluatedNetworkSecurityGroup]'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityGroupResult, self).__init__(**kwargs)
self.security_rule_access_result = kwargs.get('security_rule_access_result', None)
self.evaluated_network_security_groups = None
class NetworkSecurityRulesEvaluationResult(msrest.serialization.Model):
"""Network security rules evaluation result.
:param name: Name of the network security rule.
:type name: str
:param protocol_matched: Value indicating whether protocol is matched.
:type protocol_matched: bool
:param source_matched: Value indicating whether source is matched.
:type source_matched: bool
:param source_port_matched: Value indicating whether source port is matched.
:type source_port_matched: bool
:param destination_matched: Value indicating whether destination is matched.
:type destination_matched: bool
:param destination_port_matched: Value indicating whether destination port is matched.
:type destination_port_matched: bool
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'protocol_matched': {'key': 'protocolMatched', 'type': 'bool'},
'source_matched': {'key': 'sourceMatched', 'type': 'bool'},
'source_port_matched': {'key': 'sourcePortMatched', 'type': 'bool'},
'destination_matched': {'key': 'destinationMatched', 'type': 'bool'},
'destination_port_matched': {'key': 'destinationPortMatched', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(NetworkSecurityRulesEvaluationResult, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.protocol_matched = kwargs.get('protocol_matched', None)
self.source_matched = kwargs.get('source_matched', None)
self.source_port_matched = kwargs.get('source_port_matched', None)
self.destination_matched = kwargs.get('destination_matched', None)
self.destination_port_matched = kwargs.get('destination_port_matched', None)
class NetworkWatcher(Resource):
"""Network watcher in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NetworkWatcher, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.provisioning_state = None
class NetworkWatcherListResult(msrest.serialization.Model):
"""Response for ListNetworkWatchers API service call.
:param value: List of network watcher resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.NetworkWatcher]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[NetworkWatcher]'},
}
def __init__(
self,
**kwargs
):
super(NetworkWatcherListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class NextHopParameters(msrest.serialization.Model):
"""Parameters that define the source and destination endpoint.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The resource identifier of the target resource against
which the action is to be performed.
:type target_resource_id: str
:param source_ip_address: Required. The source IP address.
:type source_ip_address: str
:param destination_ip_address: Required. The destination IP address.
:type destination_ip_address: str
:param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is
enabled on any of the nics, then this parameter must be specified. Otherwise optional).
:type target_nic_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
'source_ip_address': {'required': True},
'destination_ip_address': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'source_ip_address': {'key': 'sourceIPAddress', 'type': 'str'},
'destination_ip_address': {'key': 'destinationIPAddress', 'type': 'str'},
'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NextHopParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.source_ip_address = kwargs['source_ip_address']
self.destination_ip_address = kwargs['destination_ip_address']
self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None)
class NextHopResult(msrest.serialization.Model):
"""The information about next hop from the specified VM.
:param next_hop_type: Next hop type. Possible values include: "Internet", "VirtualAppliance",
"VirtualNetworkGateway", "VnetLocal", "HyperNetGateway", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2019_04_01.models.NextHopType
:param next_hop_ip_address: Next hop IP Address.
:type next_hop_ip_address: str
:param route_table_id: The resource identifier for the route table associated with the route
being returned. If the route being returned does not correspond to any user created routes then
this field will be the string 'System Route'.
:type route_table_id: str
"""
_attribute_map = {
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
'route_table_id': {'key': 'routeTableId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(NextHopResult, self).__init__(**kwargs)
self.next_hop_type = kwargs.get('next_hop_type', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.route_table_id = kwargs.get('route_table_id', None)
class Operation(msrest.serialization.Model):
"""Network REST API operation definition.
:param name: Operation name: {provider}/{resource}/{operation}.
:type name: str
:param display: Display metadata associated with the operation.
:type display: ~azure.mgmt.network.v2019_04_01.models.OperationDisplay
:param origin: Origin of the operation.
:type origin: str
:param service_specification: Specification of the service.
:type service_specification:
~azure.mgmt.network.v2019_04_01.models.OperationPropertiesFormatServiceSpecification
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplay'},
'origin': {'key': 'origin', 'type': 'str'},
'service_specification': {'key': 'properties.serviceSpecification', 'type': 'OperationPropertiesFormatServiceSpecification'},
}
def __init__(
self,
**kwargs
):
super(Operation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.display = kwargs.get('display', None)
self.origin = kwargs.get('origin', None)
self.service_specification = kwargs.get('service_specification', None)
class OperationDisplay(msrest.serialization.Model):
"""Display metadata associated with the operation.
:param provider: Service provider: Microsoft Network.
:type provider: str
:param resource: Resource on which the operation is performed.
:type resource: str
:param operation: Type of the operation: get, read, delete, etc.
:type operation: str
:param description: Description of the operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.resource = kwargs.get('resource', None)
self.operation = kwargs.get('operation', None)
self.description = kwargs.get('description', None)
class OperationListResult(msrest.serialization.Model):
"""Result of the request to list Network operations. It contains a list of operations and a URL link to get the next set of results.
:param value: List of Network operations supported by the Network resource provider.
:type value: list[~azure.mgmt.network.v2019_04_01.models.Operation]
:param next_link: URL to get the next set of operation list results if there are any.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class OperationPropertiesFormatServiceSpecification(msrest.serialization.Model):
"""Specification of the service.
:param metric_specifications: Operation service specification.
:type metric_specifications: list[~azure.mgmt.network.v2019_04_01.models.MetricSpecification]
:param log_specifications: Operation log specification.
:type log_specifications: list[~azure.mgmt.network.v2019_04_01.models.LogSpecification]
"""
_attribute_map = {
'metric_specifications': {'key': 'metricSpecifications', 'type': '[MetricSpecification]'},
'log_specifications': {'key': 'logSpecifications', 'type': '[LogSpecification]'},
}
def __init__(
self,
**kwargs
):
super(OperationPropertiesFormatServiceSpecification, self).__init__(**kwargs)
self.metric_specifications = kwargs.get('metric_specifications', None)
self.log_specifications = kwargs.get('log_specifications', None)
class OutboundRule(SubResource):
"""Outbound rule of the load balancer.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param allocated_outbound_ports: The number of outbound ports to be used for NAT.
:type allocated_outbound_ports: int
:param frontend_ip_configurations: The Frontend IP addresses of the load balancer.
:type frontend_ip_configurations: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param backend_address_pool: A reference to a pool of DIPs. Outbound traffic is randomly load
balanced across IPs in the backend IPs.
:type backend_address_pool: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param protocol: The protocol for the outbound rule in load balancer. Possible values include:
"Tcp", "Udp", "All".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.LoadBalancerOutboundRuleProtocol
:param enable_tcp_reset: Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected
connection termination. This element is only used when the protocol is set to TCP.
:type enable_tcp_reset: bool
:param idle_timeout_in_minutes: The timeout for the TCP idle connection.
:type idle_timeout_in_minutes: int
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'allocated_outbound_ports': {'key': 'properties.allocatedOutboundPorts', 'type': 'int'},
'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[SubResource]'},
'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'enable_tcp_reset': {'key': 'properties.enableTcpReset', 'type': 'bool'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(OutboundRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.allocated_outbound_ports = kwargs.get('allocated_outbound_ports', None)
self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None)
self.backend_address_pool = kwargs.get('backend_address_pool', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.protocol = kwargs.get('protocol', None)
self.enable_tcp_reset = kwargs.get('enable_tcp_reset', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
class P2SVpnGateway(Resource):
"""P2SVpnGateway Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_hub: The VirtualHub to which the gateway belongs.
:type virtual_hub: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param vpn_gateway_scale_unit: The scale unit for this p2s vpn gateway.
:type vpn_gateway_scale_unit: int
:param p2_s_vpn_server_configuration: The P2SVpnServerConfiguration to which the p2sVpnGateway
is attached to.
:type p2_s_vpn_server_configuration: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param vpn_client_address_pool: The reference of the address space resource which represents
Address space for P2S VpnClient.
:type vpn_client_address_pool: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param custom_routes: The reference of the address space resource which represents the custom
routes specified by the customer for P2SVpnGateway and P2S VpnClient.
:type custom_routes: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:ivar vpn_client_connection_health: All P2S VPN clients' connection health status.
:vartype vpn_client_connection_health:
~azure.mgmt.network.v2019_04_01.models.VpnClientConnectionHealth
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'vpn_client_connection_health': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'},
'p2_s_vpn_server_configuration': {'key': 'properties.p2SVpnServerConfiguration', 'type': 'SubResource'},
'vpn_client_address_pool': {'key': 'properties.vpnClientAddressPool', 'type': 'AddressSpace'},
'custom_routes': {'key': 'properties.customRoutes', 'type': 'AddressSpace'},
'vpn_client_connection_health': {'key': 'properties.vpnClientConnectionHealth', 'type': 'VpnClientConnectionHealth'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnGateway, self).__init__(**kwargs)
self.etag = None
self.virtual_hub = kwargs.get('virtual_hub', None)
self.provisioning_state = None
self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None)
self.p2_s_vpn_server_configuration = kwargs.get('p2_s_vpn_server_configuration', None)
self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None)
self.custom_routes = kwargs.get('custom_routes', None)
self.vpn_client_connection_health = None
class P2SVpnProfileParameters(msrest.serialization.Model):
"""Vpn Client Parameters for package generation.
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2019_04_01.models.AuthenticationMethod
"""
_attribute_map = {
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnProfileParameters, self).__init__(**kwargs)
self.authentication_method = kwargs.get('authentication_method', None)
class P2SVpnServerConfigRadiusClientRootCertificate(SubResource):
"""Radius client root certificate of P2SVpnServerConfiguration.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param thumbprint: The Radius client root certificate thumbprint.
:type thumbprint: str
:ivar provisioning_state: The provisioning state of the Radius client root certificate
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnServerConfigRadiusClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.thumbprint = kwargs.get('thumbprint', None)
self.provisioning_state = None
class P2SVpnServerConfigRadiusServerRootCertificate(SubResource):
"""Radius Server root certificate of P2SVpnServerConfiguration.
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: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param public_cert_data: Required. The certificate public data.
:type public_cert_data: str
:ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration Radius Server
root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'public_cert_data': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnServerConfigRadiusServerRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.public_cert_data = kwargs['public_cert_data']
self.provisioning_state = None
class P2SVpnServerConfiguration(SubResource):
"""P2SVpnServerConfiguration Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param name_properties_name: The name of the P2SVpnServerConfiguration that is unique within a
VirtualWan in a resource group. This name can be used to access the resource along with Paren
VirtualWan resource name.
:type name_properties_name: str
:param vpn_protocols: VPN protocols for the P2SVpnServerConfiguration.
:type vpn_protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.VpnGatewayTunnelingProtocol]
:param p2_s_vpn_server_config_vpn_client_root_certificates: VPN client root certificate of
P2SVpnServerConfiguration.
:type p2_s_vpn_server_config_vpn_client_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfigVpnClientRootCertificate]
:param p2_s_vpn_server_config_vpn_client_revoked_certificates: VPN client revoked certificate
of P2SVpnServerConfiguration.
:type p2_s_vpn_server_config_vpn_client_revoked_certificates:
list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfigVpnClientRevokedCertificate]
:param p2_s_vpn_server_config_radius_server_root_certificates: Radius Server root certificate
of P2SVpnServerConfiguration.
:type p2_s_vpn_server_config_radius_server_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfigRadiusServerRootCertificate]
:param p2_s_vpn_server_config_radius_client_root_certificates: Radius client root certificate
of P2SVpnServerConfiguration.
:type p2_s_vpn_server_config_radius_client_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfigRadiusClientRootCertificate]
:param vpn_client_ipsec_policies: VpnClientIpsecPolicies for P2SVpnServerConfiguration.
:type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2019_04_01.models.IpsecPolicy]
:param radius_server_address: The radius server address property of the
P2SVpnServerConfiguration resource for point to site client connection.
:type radius_server_address: str
:param radius_server_secret: The radius secret property of the P2SVpnServerConfiguration
resource for point to site client connection.
:type radius_server_secret: str
:ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:ivar p2_s_vpn_gateways: List of references to P2SVpnGateways.
:vartype p2_s_vpn_gateways: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param etag_properties_etag: A unique read-only string that changes whenever the resource is
updated.
:type etag_properties_etag: str
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
'p2_s_vpn_gateways': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'name_properties_name': {'key': 'properties.name', 'type': 'str'},
'vpn_protocols': {'key': 'properties.vpnProtocols', 'type': '[str]'},
'p2_s_vpn_server_config_vpn_client_root_certificates': {'key': 'properties.p2SVpnServerConfigVpnClientRootCertificates', 'type': '[P2SVpnServerConfigVpnClientRootCertificate]'},
'p2_s_vpn_server_config_vpn_client_revoked_certificates': {'key': 'properties.p2SVpnServerConfigVpnClientRevokedCertificates', 'type': '[P2SVpnServerConfigVpnClientRevokedCertificate]'},
'p2_s_vpn_server_config_radius_server_root_certificates': {'key': 'properties.p2SVpnServerConfigRadiusServerRootCertificates', 'type': '[P2SVpnServerConfigRadiusServerRootCertificate]'},
'p2_s_vpn_server_config_radius_client_root_certificates': {'key': 'properties.p2SVpnServerConfigRadiusClientRootCertificates', 'type': '[P2SVpnServerConfigRadiusClientRootCertificate]'},
'vpn_client_ipsec_policies': {'key': 'properties.vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'},
'radius_server_address': {'key': 'properties.radiusServerAddress', 'type': 'str'},
'radius_server_secret': {'key': 'properties.radiusServerSecret', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'p2_s_vpn_gateways': {'key': 'properties.p2SVpnGateways', 'type': '[SubResource]'},
'etag_properties_etag': {'key': 'properties.etag', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnServerConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.name_properties_name = kwargs.get('name_properties_name', None)
self.vpn_protocols = kwargs.get('vpn_protocols', None)
self.p2_s_vpn_server_config_vpn_client_root_certificates = kwargs.get('p2_s_vpn_server_config_vpn_client_root_certificates', None)
self.p2_s_vpn_server_config_vpn_client_revoked_certificates = kwargs.get('p2_s_vpn_server_config_vpn_client_revoked_certificates', None)
self.p2_s_vpn_server_config_radius_server_root_certificates = kwargs.get('p2_s_vpn_server_config_radius_server_root_certificates', None)
self.p2_s_vpn_server_config_radius_client_root_certificates = kwargs.get('p2_s_vpn_server_config_radius_client_root_certificates', None)
self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None)
self.radius_server_address = kwargs.get('radius_server_address', None)
self.radius_server_secret = kwargs.get('radius_server_secret', None)
self.provisioning_state = None
self.p2_s_vpn_gateways = None
self.etag_properties_etag = kwargs.get('etag_properties_etag', None)
class P2SVpnServerConfigVpnClientRevokedCertificate(SubResource):
"""VPN client revoked certificate of P2SVpnServerConfiguration.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param thumbprint: The revoked VPN client certificate thumbprint.
:type thumbprint: str
:ivar provisioning_state: The provisioning state of the VPN client revoked certificate
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnServerConfigVpnClientRevokedCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.thumbprint = kwargs.get('thumbprint', None)
self.provisioning_state = None
class P2SVpnServerConfigVpnClientRootCertificate(SubResource):
"""VPN client root certificate of P2SVpnServerConfiguration.
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: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param public_cert_data: Required. The certificate public data.
:type public_cert_data: str
:ivar provisioning_state: The provisioning state of the P2SVpnServerConfiguration VPN client
root certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'public_cert_data': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(P2SVpnServerConfigVpnClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.public_cert_data = kwargs['public_cert_data']
self.provisioning_state = None
class PacketCapture(msrest.serialization.Model):
"""Parameters that define the create packet capture operation.
All required parameters must be populated in order to send to Azure.
:param target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. Describes the storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2019_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2019_04_01.models.PacketCaptureFilter]
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
}
_attribute_map = {
'target': {'key': 'properties.target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'},
}
def __init__(
self,
**kwargs
):
super(PacketCapture, self).__init__(**kwargs)
self.target = kwargs['target']
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs['storage_location']
self.filters = kwargs.get('filters', None)
class PacketCaptureFilter(msrest.serialization.Model):
"""Filter that is applied to packet capture request. Multiple filters can be applied.
:param protocol: Protocol to be filtered on. Possible values include: "TCP", "UDP", "Any".
Default value: "Any".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.PcProtocol
:param local_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single
address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5"? for multiple entries.
Multiple ranges not currently supported. Mixing ranges with multiple entries not currently
supported. Default = null.
:type local_ip_address: str
:param remote_ip_address: Local IP Address to be filtered on. Notation: "127.0.0.1" for single
address entry. "127.0.0.1-127.0.0.255" for range. "127.0.0.1;127.0.0.5;" for multiple entries.
Multiple ranges not currently supported. Mixing ranges with multiple entries not currently
supported. Default = null.
:type remote_ip_address: str
:param local_port: Local port to be filtered on. Notation: "80" for single port entry."80-85"
for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing
ranges with multiple entries not currently supported. Default = null.
:type local_port: str
:param remote_port: Remote port to be filtered on. Notation: "80" for single port entry."80-85"
for range. "80;443;" for multiple entries. Multiple ranges not currently supported. Mixing
ranges with multiple entries not currently supported. Default = null.
:type remote_port: str
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'local_ip_address': {'key': 'localIPAddress', 'type': 'str'},
'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'},
'local_port': {'key': 'localPort', 'type': 'str'},
'remote_port': {'key': 'remotePort', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureFilter, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', "Any")
self.local_ip_address = kwargs.get('local_ip_address', None)
self.remote_ip_address = kwargs.get('remote_ip_address', None)
self.local_port = kwargs.get('local_port', None)
self.remote_port = kwargs.get('remote_port', None)
class PacketCaptureListResult(msrest.serialization.Model):
"""List of packet capture sessions.
:param value: Information about packet capture sessions.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PacketCaptureResult]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PacketCaptureResult]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class PacketCaptureParameters(msrest.serialization.Model):
"""Parameters that define the create packet capture operation.
All required parameters must be populated in order to send to Azure.
:param target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. Describes the storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2019_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2019_04_01.models.PacketCaptureFilter]
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
}
_attribute_map = {
'target': {'key': 'target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureParameters, self).__init__(**kwargs)
self.target = kwargs['target']
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs['storage_location']
self.filters = kwargs.get('filters', None)
class PacketCaptureQueryStatusResult(msrest.serialization.Model):
"""Status of packet capture session.
:param name: The name of the packet capture resource.
:type name: str
:param id: The ID of the packet capture resource.
:type id: str
:param capture_start_time: The start time of the packet capture session.
:type capture_start_time: ~datetime.datetime
:param packet_capture_status: The status of the packet capture session. Possible values
include: "NotStarted", "Running", "Stopped", "Error", "Unknown".
:type packet_capture_status: str or ~azure.mgmt.network.v2019_04_01.models.PcStatus
:param stop_reason: The reason the current packet capture session was stopped.
:type stop_reason: str
:param packet_capture_error: List of errors of packet capture session.
:type packet_capture_error: list[str or ~azure.mgmt.network.v2019_04_01.models.PcError]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'capture_start_time': {'key': 'captureStartTime', 'type': 'iso-8601'},
'packet_capture_status': {'key': 'packetCaptureStatus', 'type': 'str'},
'stop_reason': {'key': 'stopReason', 'type': 'str'},
'packet_capture_error': {'key': 'packetCaptureError', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureQueryStatusResult, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.capture_start_time = kwargs.get('capture_start_time', None)
self.packet_capture_status = kwargs.get('packet_capture_status', None)
self.stop_reason = kwargs.get('stop_reason', None)
self.packet_capture_error = kwargs.get('packet_capture_error', None)
class PacketCaptureResult(msrest.serialization.Model):
"""Information about packet capture session.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: Name of the packet capture session.
:vartype name: str
:ivar id: ID of the packet capture operation.
:vartype id: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param target: The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Describes the storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2019_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2019_04_01.models.PacketCaptureFilter]
:ivar provisioning_state: The provisioning state of the packet capture session. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'target': {'key': 'properties.target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.etag = kwargs.get('etag', "A unique read-only string that changes whenever the resource is updated.")
self.target = kwargs.get('target', None)
self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0)
self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824)
self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000)
self.storage_location = kwargs.get('storage_location', None)
self.filters = kwargs.get('filters', None)
self.provisioning_state = None
class PacketCaptureResultProperties(PacketCaptureParameters):
"""Describes the properties of a packet capture session.
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 target: Required. The ID of the targeted resource, only VM is currently supported.
:type target: str
:param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes
are truncated.
:type bytes_to_capture_per_packet: int
:param total_bytes_per_session: Maximum size of the capture output.
:type total_bytes_per_session: int
:param time_limit_in_seconds: Maximum duration of the capture session in seconds.
:type time_limit_in_seconds: int
:param storage_location: Required. Describes the storage location for a packet capture session.
:type storage_location: ~azure.mgmt.network.v2019_04_01.models.PacketCaptureStorageLocation
:param filters: A list of packet capture filters.
:type filters: list[~azure.mgmt.network.v2019_04_01.models.PacketCaptureFilter]
:ivar provisioning_state: The provisioning state of the packet capture session. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'target': {'required': True},
'storage_location': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'target': {'key': 'target', 'type': 'str'},
'bytes_to_capture_per_packet': {'key': 'bytesToCapturePerPacket', 'type': 'int'},
'total_bytes_per_session': {'key': 'totalBytesPerSession', 'type': 'int'},
'time_limit_in_seconds': {'key': 'timeLimitInSeconds', 'type': 'int'},
'storage_location': {'key': 'storageLocation', 'type': 'PacketCaptureStorageLocation'},
'filters': {'key': 'filters', 'type': '[PacketCaptureFilter]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureResultProperties, self).__init__(**kwargs)
self.provisioning_state = None
class PacketCaptureStorageLocation(msrest.serialization.Model):
"""Describes the storage location for a packet capture session.
:param storage_id: The ID of the storage account to save the packet capture session. Required
if no local file path is provided.
:type storage_id: str
:param storage_path: The URI of the storage path to save the packet capture. Must be a
well-formed URI describing the location to save the packet capture.
:type storage_path: str
:param file_path: A valid local path on the targeting VM. Must include the name of the capture
file (*.cap). For linux virtual machine it must start with /var/captures. Required if no
storage ID is provided, otherwise optional.
:type file_path: str
"""
_attribute_map = {
'storage_id': {'key': 'storageId', 'type': 'str'},
'storage_path': {'key': 'storagePath', 'type': 'str'},
'file_path': {'key': 'filePath', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PacketCaptureStorageLocation, self).__init__(**kwargs)
self.storage_id = kwargs.get('storage_id', None)
self.storage_path = kwargs.get('storage_path', None)
self.file_path = kwargs.get('file_path', None)
class PatchRouteFilter(SubResource):
"""Route Filter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:vartype name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param rules: Collection of RouteFilterRules contained within a route filter.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.RouteFilterRule]
:param peerings: A collection of references to express route circuit peerings.
:type peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:param ipv6_peerings: A collection of references to express route circuit ipv6 peerings.
:type ipv6_peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PatchRouteFilter, self).__init__(**kwargs)
self.name = None
self.etag = None
self.type = None
self.tags = kwargs.get('tags', None)
self.rules = kwargs.get('rules', None)
self.peerings = kwargs.get('peerings', None)
self.ipv6_peerings = kwargs.get('ipv6_peerings', None)
self.provisioning_state = None
class PatchRouteFilterRule(SubResource):
"""Route Filter Rule Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:vartype name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param access: The access type of the rule. Possible values include: "Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.Access
:param route_filter_rule_type: The rule type of the rule. Possible values include: "Community".
:type route_filter_rule_type: str or ~azure.mgmt.network.v2019_04_01.models.RouteFilterRuleType
:param communities: The collection for bgp community values to filter on. e.g.
['12076:5010','12076:5020'].
:type communities: list[str]
:ivar provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'},
'communities': {'key': 'properties.communities', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PatchRouteFilterRule, self).__init__(**kwargs)
self.name = None
self.etag = None
self.access = kwargs.get('access', None)
self.route_filter_rule_type = kwargs.get('route_filter_rule_type', None)
self.communities = kwargs.get('communities', None)
self.provisioning_state = None
class PeerExpressRouteCircuitConnection(SubResource):
"""Peer Express Route Circuit Connection in an ExpressRouteCircuitPeering resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Type of the resource.
:vartype type: str
:param express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the circuit.
:type express_route_circuit_peering: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param peer_express_route_circuit_peering: Reference to Express Route Circuit Private Peering
Resource of the peered circuit.
:type peer_express_route_circuit_peering: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param address_prefix: /29 IP address space to carve out Customer addresses for tunnels.
:type address_prefix: str
:ivar circuit_connection_status: Express Route Circuit connection state. Possible values
include: "Connected", "Connecting", "Disconnected".
:vartype circuit_connection_status: str or
~azure.mgmt.network.v2019_04_01.models.CircuitConnectionStatus
:param connection_name: The name of the express route circuit connection resource.
:type connection_name: str
:param auth_resource_guid: The resource guid of the authorization used for the express route
circuit connection.
:type auth_resource_guid: str
:ivar provisioning_state: Provisioning state of the peer express route circuit connection
resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'circuit_connection_status': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'express_route_circuit_peering': {'key': 'properties.expressRouteCircuitPeering', 'type': 'SubResource'},
'peer_express_route_circuit_peering': {'key': 'properties.peerExpressRouteCircuitPeering', 'type': 'SubResource'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'circuit_connection_status': {'key': 'properties.circuitConnectionStatus', 'type': 'str'},
'connection_name': {'key': 'properties.connectionName', 'type': 'str'},
'auth_resource_guid': {'key': 'properties.authResourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PeerExpressRouteCircuitConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.express_route_circuit_peering = kwargs.get('express_route_circuit_peering', None)
self.peer_express_route_circuit_peering = kwargs.get('peer_express_route_circuit_peering', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.circuit_connection_status = None
self.connection_name = kwargs.get('connection_name', None)
self.auth_resource_guid = kwargs.get('auth_resource_guid', None)
self.provisioning_state = None
class PeerExpressRouteCircuitConnectionListResult(msrest.serialization.Model):
"""Response for ListPeeredConnections API service call retrieves all global reach peer circuit connections that belongs to a Private Peering for an ExpressRouteCircuit.
:param value: The global reach peer circuit connection associated with Private Peering in an
ExpressRoute Circuit.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PeerExpressRouteCircuitConnection]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PeerExpressRouteCircuitConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PeerExpressRouteCircuitConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PolicySettings(msrest.serialization.Model):
"""Defines contents of a web application firewall global configuration.
:param enabled_state: Describes if the policy is in enabled state or disabled state. Possible
values include: "Disabled", "Enabled".
:type enabled_state: str or
~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallEnabledState
:param mode: Describes if it is in detection mode or prevention mode at policy level. Possible
values include: "Prevention", "Detection".
:type mode: str or ~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallMode
"""
_attribute_map = {
'enabled_state': {'key': 'enabledState', 'type': 'str'},
'mode': {'key': 'mode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PolicySettings, self).__init__(**kwargs)
self.enabled_state = kwargs.get('enabled_state', None)
self.mode = kwargs.get('mode', None)
class PrepareNetworkPoliciesRequest(msrest.serialization.Model):
"""Details of PrepareNetworkPolicies for Subnet.
:param service_name: The name of the service for which subnet is being prepared for.
:type service_name: str
:param resource_group_name: The name of the resource group where the Network Intent Policy will
be stored.
:type resource_group_name: str
:param network_intent_policy_configurations: A list of NetworkIntentPolicyConfiguration.
:type network_intent_policy_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkIntentPolicyConfiguration]
"""
_attribute_map = {
'service_name': {'key': 'serviceName', 'type': 'str'},
'resource_group_name': {'key': 'resourceGroupName', 'type': 'str'},
'network_intent_policy_configurations': {'key': 'networkIntentPolicyConfigurations', 'type': '[NetworkIntentPolicyConfiguration]'},
}
def __init__(
self,
**kwargs
):
super(PrepareNetworkPoliciesRequest, self).__init__(**kwargs)
self.service_name = kwargs.get('service_name', None)
self.resource_group_name = kwargs.get('resource_group_name', None)
self.network_intent_policy_configurations = kwargs.get('network_intent_policy_configurations', None)
class PrivateEndpoint(Resource):
"""Private endpoint resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param subnet: The ID of the subnet from which the private IP will be allocated.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:ivar network_interfaces: Gets an array of references to the network interfaces created for
this private endpoint.
:vartype network_interfaces: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterface]
:ivar provisioning_state: The provisioning state of the private endpoint. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param private_link_service_connections: A grouping of information about the connection to the
remote resource.
:type private_link_service_connections:
list[~azure.mgmt.network.v2019_04_01.models.PrivateLinkServiceConnection]
:param manual_private_link_service_connections: A grouping of information about the connection
to the remote resource. Used when the network admin does not have access to approve connections
to the remote resource.
:type manual_private_link_service_connections:
list[~azure.mgmt.network.v2019_04_01.models.PrivateLinkServiceConnection]
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'network_interfaces': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_link_service_connections': {'key': 'properties.privateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'},
'manual_private_link_service_connections': {'key': 'properties.manualPrivateLinkServiceConnections', 'type': '[PrivateLinkServiceConnection]'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpoint, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.subnet = kwargs.get('subnet', None)
self.network_interfaces = None
self.provisioning_state = None
self.private_link_service_connections = kwargs.get('private_link_service_connections', None)
self.manual_private_link_service_connections = kwargs.get('manual_private_link_service_connections', None)
class PrivateEndpointConnection(SubResource):
"""PrivateEndpointConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar type: The resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param private_endpoint: The resource of private end point.
:type private_endpoint: ~azure.mgmt.network.v2019_04_01.models.PrivateEndpoint
:param private_link_service_connection_state: A collection of information about the state of
the connection between service consumer and provider.
:type private_link_service_connection_state:
~azure.mgmt.network.v2019_04_01.models.PrivateLinkServiceConnectionState
:ivar provisioning_state: The provisioning state of the private endpoint connection. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpointConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.private_endpoint = kwargs.get('private_endpoint', None)
self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None)
self.provisioning_state = None
class PrivateEndpointListResult(msrest.serialization.Model):
"""Response for the ListPrivateEndpoints API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Gets a list of private endpoint resources in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PrivateEndpoint]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateEndpoint]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateEndpointListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class PrivateLinkService(Resource):
"""Private link service resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param load_balancer_frontend_ip_configurations: An array of references to the load balancer IP
configurations.
:type load_balancer_frontend_ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.FrontendIPConfiguration]
:param ip_configurations: An array of references to the private link service IP configuration.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.PrivateLinkServiceIpConfiguration]
:ivar network_interfaces: Gets an array of references to the network interfaces created for
this private link service.
:vartype network_interfaces: list[~azure.mgmt.network.v2019_04_01.models.NetworkInterface]
:ivar provisioning_state: The provisioning state of the private link service. Possible values
include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param private_endpoint_connections: An array of list about connections to the private
endpoint.
:type private_endpoint_connections:
list[~azure.mgmt.network.v2019_04_01.models.PrivateEndpointConnection]
:param visibility: The visibility list of the private link service.
:type visibility: ~azure.mgmt.network.v2019_04_01.models.PrivateLinkServicePropertiesVisibility
:param auto_approval: The auto-approval list of the private link service.
:type auto_approval:
~azure.mgmt.network.v2019_04_01.models.PrivateLinkServicePropertiesAutoApproval
:param fqdns: The list of Fqdn.
:type fqdns: list[str]
:ivar alias: The alias of the private link service.
:vartype alias: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'network_interfaces': {'readonly': True},
'provisioning_state': {'readonly': True},
'alias': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'load_balancer_frontend_ip_configurations': {'key': 'properties.loadBalancerFrontendIpConfigurations', 'type': '[FrontendIPConfiguration]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[PrivateLinkServiceIpConfiguration]'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[PrivateEndpointConnection]'},
'visibility': {'key': 'properties.visibility', 'type': 'PrivateLinkServicePropertiesVisibility'},
'auto_approval': {'key': 'properties.autoApproval', 'type': 'PrivateLinkServicePropertiesAutoApproval'},
'fqdns': {'key': 'properties.fqdns', 'type': '[str]'},
'alias': {'key': 'properties.alias', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkService, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.load_balancer_frontend_ip_configurations = kwargs.get('load_balancer_frontend_ip_configurations', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.network_interfaces = None
self.provisioning_state = None
self.private_endpoint_connections = kwargs.get('private_endpoint_connections', None)
self.visibility = kwargs.get('visibility', None)
self.auto_approval = kwargs.get('auto_approval', None)
self.fqdns = kwargs.get('fqdns', None)
self.alias = None
class PrivateLinkServiceConnection(SubResource):
"""PrivateLinkServiceConnection resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar type: The resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar provisioning_state: The provisioning state of the private link service connection.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param private_link_service_id: The resource id of private link service.
:type private_link_service_id: str
:param group_ids: The ID(s) of the group(s) obtained from the remote resource that this private
endpoint should connect to.
:type group_ids: list[str]
:param request_message: A message passed to the owner of the remote resource with this
connection request. Restricted to 140 chars.
:type request_message: str
:param private_link_service_connection_state: A collection of read-only information about the
state of the connection to the remote resource.
:type private_link_service_connection_state:
~azure.mgmt.network.v2019_04_01.models.PrivateLinkServiceConnectionState
"""
_validation = {
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_link_service_id': {'key': 'properties.privateLinkServiceId', 'type': 'str'},
'group_ids': {'key': 'properties.groupIds', 'type': '[str]'},
'request_message': {'key': 'properties.requestMessage', 'type': 'str'},
'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionState'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.type = None
self.etag = None
self.provisioning_state = None
self.private_link_service_id = kwargs.get('private_link_service_id', None)
self.group_ids = kwargs.get('group_ids', None)
self.request_message = kwargs.get('request_message', None)
self.private_link_service_connection_state = kwargs.get('private_link_service_connection_state', None)
class PrivateLinkServiceConnectionState(msrest.serialization.Model):
"""A collection of information about the state of the connection between service consumer and provider.
:param status: Indicates whether the connection has been Approved/Rejected/Removed by the owner
of the service.
:type status: str
:param description: The reason for approval/rejection of the connection.
:type description: str
:param actions_required: A message indicating if changes on the service provider require any
updates on the consumer.
:type actions_required: str
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'actions_required': {'key': 'actionsRequired', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceConnectionState, self).__init__(**kwargs)
self.status = kwargs.get('status', None)
self.description = kwargs.get('description', None)
self.actions_required = kwargs.get('actions_required', None)
class PrivateLinkServiceIpConfiguration(SubResource):
"""The private link service ip configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of private link service ip configuration.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: The resource type.
:vartype type: str
:param private_ip_address: The private IP address of the IP configuration.
:type private_ip_address: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param subnet: The reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.Subnet
:param primary: Whether the ip configuration is primary or not.
:type primary: bool
:ivar provisioning_state: The provisioning state of the private link service ip configuration.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param private_ip_address_version: Available from Api-Version 2016-03-30 onwards, it represents
whether the specific ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values
include: "IPv4", "IPv6".
:type private_ip_address_version: str or ~azure.mgmt.network.v2019_04_01.models.IPVersion
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'private_ip_address': {'key': 'properties.privateIPAddress', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'Subnet'},
'primary': {'key': 'properties.primary', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_ip_address_version': {'key': 'properties.privateIPAddressVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceIpConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.private_ip_address = kwargs.get('private_ip_address', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.primary = kwargs.get('primary', None)
self.provisioning_state = None
self.private_ip_address_version = kwargs.get('private_ip_address_version', None)
class PrivateLinkServiceListResult(msrest.serialization.Model):
"""Response for the ListPrivateLinkService API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Gets a list of PrivateLinkService resources in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PrivateLinkService]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[PrivateLinkService]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ResourceSet(msrest.serialization.Model):
"""The base resource set for visibility and auto-approval.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ResourceSet, self).__init__(**kwargs)
self.subscriptions = kwargs.get('subscriptions', None)
class PrivateLinkServicePropertiesAutoApproval(ResourceSet):
"""The auto-approval list of the private link service.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServicePropertiesAutoApproval, self).__init__(**kwargs)
class PrivateLinkServicePropertiesVisibility(ResourceSet):
"""The visibility list of the private link service.
:param subscriptions: The list of subscriptions.
:type subscriptions: list[str]
"""
_attribute_map = {
'subscriptions': {'key': 'subscriptions', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServicePropertiesVisibility, self).__init__(**kwargs)
class PrivateLinkServiceVisibility(msrest.serialization.Model):
"""Response for the CheckPrivateLinkServiceVisibility API service call.
:param visible: Private Link Service Visibility (True/False).
:type visible: bool
"""
_attribute_map = {
'visible': {'key': 'visible', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(PrivateLinkServiceVisibility, self).__init__(**kwargs)
self.visible = kwargs.get('visible', None)
class Probe(SubResource):
"""A load balancer probe.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Gets name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar load_balancing_rules: The load balancer rules that use this probe.
:vartype load_balancing_rules: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param protocol: The protocol of the end point. If 'Tcp' is specified, a received ACK is
required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response
from the specifies URI is required for the probe to be successful. Possible values include:
"Http", "Tcp", "Https".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.ProbeProtocol
:param port: The port for communicating the probe. Possible values range from 1 to 65535,
inclusive.
:type port: int
:param interval_in_seconds: The interval, in seconds, for how frequently to probe the endpoint
for health status. Typically, the interval is slightly less than half the allocated timeout
period (in seconds) which allows two full probes before taking the instance out of rotation.
The default value is 15, the minimum value is 5.
:type interval_in_seconds: int
:param number_of_probes: The number of probes where if no response, will result in stopping
further traffic from being delivered to the endpoint. This values allows endpoints to be taken
out of rotation faster or slower than the typical times used in Azure.
:type number_of_probes: int
:param request_path: The URI used for requesting health status from the VM. Path is required if
a protocol is set to http. Otherwise, it is not allowed. There is no default value.
:type request_path: str
:param provisioning_state: Gets the provisioning state of the public IP resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'load_balancing_rules': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'port': {'key': 'properties.port', 'type': 'int'},
'interval_in_seconds': {'key': 'properties.intervalInSeconds', 'type': 'int'},
'number_of_probes': {'key': 'properties.numberOfProbes', 'type': 'int'},
'request_path': {'key': 'properties.requestPath', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Probe, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.load_balancing_rules = None
self.protocol = kwargs.get('protocol', None)
self.port = kwargs.get('port', None)
self.interval_in_seconds = kwargs.get('interval_in_seconds', None)
self.number_of_probes = kwargs.get('number_of_probes', None)
self.request_path = kwargs.get('request_path', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ProtocolConfiguration(msrest.serialization.Model):
"""Configuration of the protocol.
:param http_configuration: HTTP configuration of the connectivity check.
:type http_configuration: ~azure.mgmt.network.v2019_04_01.models.HTTPConfiguration
"""
_attribute_map = {
'http_configuration': {'key': 'HTTPConfiguration', 'type': 'HTTPConfiguration'},
}
def __init__(
self,
**kwargs
):
super(ProtocolConfiguration, self).__init__(**kwargs)
self.http_configuration = kwargs.get('http_configuration', None)
class ProtocolCustomSettingsFormat(msrest.serialization.Model):
"""DDoS custom policy properties.
:param protocol: The protocol for which the DDoS protection policy is being customized.
Possible values include: "Tcp", "Udp", "Syn".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.DdosCustomPolicyProtocol
:param trigger_rate_override: The customized DDoS protection trigger rate.
:type trigger_rate_override: str
:param source_rate_override: The customized DDoS protection source rate.
:type source_rate_override: str
:param trigger_sensitivity_override: The customized DDoS protection trigger rate sensitivity
degrees. High: Trigger rate set with most sensitivity w.r.t. normal traffic. Default: Trigger
rate set with moderate sensitivity w.r.t. normal traffic. Low: Trigger rate set with less
sensitivity w.r.t. normal traffic. Relaxed: Trigger rate set with least sensitivity w.r.t.
normal traffic. Possible values include: "Relaxed", "Low", "Default", "High".
:type trigger_sensitivity_override: str or
~azure.mgmt.network.v2019_04_01.models.DdosCustomPolicyTriggerSensitivityOverride
"""
_attribute_map = {
'protocol': {'key': 'protocol', 'type': 'str'},
'trigger_rate_override': {'key': 'triggerRateOverride', 'type': 'str'},
'source_rate_override': {'key': 'sourceRateOverride', 'type': 'str'},
'trigger_sensitivity_override': {'key': 'triggerSensitivityOverride', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ProtocolCustomSettingsFormat, self).__init__(**kwargs)
self.protocol = kwargs.get('protocol', None)
self.trigger_rate_override = kwargs.get('trigger_rate_override', None)
self.source_rate_override = kwargs.get('source_rate_override', None)
self.trigger_sensitivity_override = kwargs.get('trigger_sensitivity_override', None)
class PublicIPAddress(Resource):
"""Public IP address resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The public IP address SKU.
:type sku: ~azure.mgmt.network.v2019_04_01.models.PublicIPAddressSku
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:param public_ip_allocation_method: The public IP address allocation method. Possible values
include: "Static", "Dynamic".
:type public_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param public_ip_address_version: The public IP address version. Possible values include:
"IPv4", "IPv6".
:type public_ip_address_version: str or ~azure.mgmt.network.v2019_04_01.models.IPVersion
:ivar ip_configuration: The IP configuration associated with the public IP address.
:vartype ip_configuration: ~azure.mgmt.network.v2019_04_01.models.IPConfiguration
:param dns_settings: The FQDN of the DNS record associated with the public IP address.
:type dns_settings: ~azure.mgmt.network.v2019_04_01.models.PublicIPAddressDnsSettings
:param ddos_settings: The DDoS protection custom policy associated with the public IP address.
:type ddos_settings: ~azure.mgmt.network.v2019_04_01.models.DdosSettings
:param ip_tags: The list of tags associated with the public IP address.
:type ip_tags: list[~azure.mgmt.network.v2019_04_01.models.IpTag]
:param ip_address: The IP address associated with the public IP address resource.
:type ip_address: str
:param public_ip_prefix: The Public IP Prefix this Public IP Address should be allocated from.
:type public_ip_prefix: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param idle_timeout_in_minutes: The idle timeout of the public IP address.
:type idle_timeout_in_minutes: int
:param resource_guid: The resource GUID property of the public IP resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the PublicIP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'ip_configuration': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'PublicIPAddressSku'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'public_ip_allocation_method': {'key': 'properties.publicIPAllocationMethod', 'type': 'str'},
'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'},
'ip_configuration': {'key': 'properties.ipConfiguration', 'type': 'IPConfiguration'},
'dns_settings': {'key': 'properties.dnsSettings', 'type': 'PublicIPAddressDnsSettings'},
'ddos_settings': {'key': 'properties.ddosSettings', 'type': 'DdosSettings'},
'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'public_ip_prefix': {'key': 'properties.publicIPPrefix', 'type': 'SubResource'},
'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddress, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = kwargs.get('etag', None)
self.zones = kwargs.get('zones', None)
self.public_ip_allocation_method = kwargs.get('public_ip_allocation_method', None)
self.public_ip_address_version = kwargs.get('public_ip_address_version', None)
self.ip_configuration = None
self.dns_settings = kwargs.get('dns_settings', None)
self.ddos_settings = kwargs.get('ddos_settings', None)
self.ip_tags = kwargs.get('ip_tags', None)
self.ip_address = kwargs.get('ip_address', None)
self.public_ip_prefix = kwargs.get('public_ip_prefix', None)
self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class PublicIPAddressDnsSettings(msrest.serialization.Model):
"""Contains FQDN of the DNS record associated with the public IP address.
:param domain_name_label: Gets or sets the Domain name label.The concatenation of the domain
name label and the regionalized DNS zone make up the fully qualified domain name associated
with the public IP address. If a domain name label is specified, an A DNS record is created for
the public IP in the Microsoft Azure DNS system.
:type domain_name_label: str
:param fqdn: Gets the FQDN, Fully qualified domain name of the A DNS record associated with the
public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone.
:type fqdn: str
:param reverse_fqdn: Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name
that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record
is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN.
:type reverse_fqdn: str
"""
_attribute_map = {
'domain_name_label': {'key': 'domainNameLabel', 'type': 'str'},
'fqdn': {'key': 'fqdn', 'type': 'str'},
'reverse_fqdn': {'key': 'reverseFqdn', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressDnsSettings, self).__init__(**kwargs)
self.domain_name_label = kwargs.get('domain_name_label', None)
self.fqdn = kwargs.get('fqdn', None)
self.reverse_fqdn = kwargs.get('reverse_fqdn', None)
class PublicIPAddressListResult(msrest.serialization.Model):
"""Response for ListPublicIpAddresses API service call.
:param value: A list of public IP addresses that exists in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PublicIPAddress]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PublicIPAddress]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PublicIPAddressSku(msrest.serialization.Model):
"""SKU of a public IP address.
:param name: Name of a public IP address SKU. Possible values include: "Basic", "Standard".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.PublicIPAddressSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPAddressSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class PublicIPPrefix(Resource):
"""Public IP prefix resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param sku: The public IP prefix SKU.
:type sku: ~azure.mgmt.network.v2019_04_01.models.PublicIPPrefixSku
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param zones: A list of availability zones denoting the IP allocated for the resource needs to
come from.
:type zones: list[str]
:param public_ip_address_version: The public IP address version. Possible values include:
"IPv4", "IPv6".
:type public_ip_address_version: str or ~azure.mgmt.network.v2019_04_01.models.IPVersion
:param ip_tags: The list of tags associated with the public IP prefix.
:type ip_tags: list[~azure.mgmt.network.v2019_04_01.models.IpTag]
:param prefix_length: The Length of the Public IP Prefix.
:type prefix_length: int
:param ip_prefix: The allocated Prefix.
:type ip_prefix: str
:param public_ip_addresses: The list of all referenced PublicIPAddresses.
:type public_ip_addresses:
list[~azure.mgmt.network.v2019_04_01.models.ReferencedPublicIpAddress]
:ivar load_balancer_frontend_ip_configuration: The reference to load balancer frontend IP
configuration associated with the public IP prefix.
:vartype load_balancer_frontend_ip_configuration:
~azure.mgmt.network.v2019_04_01.models.SubResource
:param resource_guid: The resource GUID property of the public IP prefix resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the Public IP prefix resource. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'load_balancer_frontend_ip_configuration': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'sku': {'key': 'sku', 'type': 'PublicIPPrefixSku'},
'etag': {'key': 'etag', 'type': 'str'},
'zones': {'key': 'zones', 'type': '[str]'},
'public_ip_address_version': {'key': 'properties.publicIPAddressVersion', 'type': 'str'},
'ip_tags': {'key': 'properties.ipTags', 'type': '[IpTag]'},
'prefix_length': {'key': 'properties.prefixLength', 'type': 'int'},
'ip_prefix': {'key': 'properties.ipPrefix', 'type': 'str'},
'public_ip_addresses': {'key': 'properties.publicIPAddresses', 'type': '[ReferencedPublicIpAddress]'},
'load_balancer_frontend_ip_configuration': {'key': 'properties.loadBalancerFrontendIpConfiguration', 'type': 'SubResource'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefix, self).__init__(**kwargs)
self.sku = kwargs.get('sku', None)
self.etag = kwargs.get('etag', None)
self.zones = kwargs.get('zones', None)
self.public_ip_address_version = kwargs.get('public_ip_address_version', None)
self.ip_tags = kwargs.get('ip_tags', None)
self.prefix_length = kwargs.get('prefix_length', None)
self.ip_prefix = kwargs.get('ip_prefix', None)
self.public_ip_addresses = kwargs.get('public_ip_addresses', None)
self.load_balancer_frontend_ip_configuration = None
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class PublicIPPrefixListResult(msrest.serialization.Model):
"""Response for ListPublicIpPrefixes API service call.
:param value: A list of public IP prefixes that exists in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.PublicIPPrefix]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[PublicIPPrefix]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefixListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class PublicIPPrefixSku(msrest.serialization.Model):
"""SKU of a public IP prefix.
:param name: Name of a public IP prefix SKU. Possible values include: "Standard".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.PublicIPPrefixSkuName
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(PublicIPPrefixSku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
class QueryTroubleshootingParameters(msrest.serialization.Model):
"""Parameters that define the resource to query the troubleshooting result.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource ID to query the troubleshooting
result.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(QueryTroubleshootingParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class ReferencedPublicIpAddress(msrest.serialization.Model):
"""Reference to a public IP address.
:param id: The PublicIPAddress Reference.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ReferencedPublicIpAddress, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class ResourceNavigationLink(SubResource):
"""ResourceNavigationLink resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param linked_resource_type: Resource type of the linked resource.
:type linked_resource_type: str
:param link: Link to the external resource.
:type link: str
:ivar provisioning_state: Provisioning state of the ResourceNavigationLink resource.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'},
'link': {'key': 'properties.link', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceNavigationLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = None
self.linked_resource_type = kwargs.get('linked_resource_type', None)
self.link = kwargs.get('link', None)
self.provisioning_state = None
class ResourceNavigationLinksListResult(msrest.serialization.Model):
"""Response for ResourceNavigationLinks_List operation.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The resource navigation links in a subnet.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ResourceNavigationLink]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ResourceNavigationLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ResourceNavigationLinksListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class RetentionPolicyParameters(msrest.serialization.Model):
"""Parameters that define the retention policy for flow log.
:param days: Number of days to retain flow log records.
:type days: int
:param enabled: Flag to enable/disable retention.
:type enabled: bool
"""
_attribute_map = {
'days': {'key': 'days', 'type': 'int'},
'enabled': {'key': 'enabled', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(RetentionPolicyParameters, self).__init__(**kwargs)
self.days = kwargs.get('days', 0)
self.enabled = kwargs.get('enabled', False)
class Route(SubResource):
"""Route resource.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param address_prefix: The destination CIDR to which the route applies.
:type address_prefix: str
:param next_hop_type: The type of Azure hop the packet should be sent to. Possible values
include: "VirtualNetworkGateway", "VnetLocal", "Internet", "VirtualAppliance", "None".
:type next_hop_type: str or ~azure.mgmt.network.v2019_04_01.models.RouteNextHopType
:param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are
only allowed in routes where the next hop type is VirtualAppliance.
:type next_hop_ip_address: str
:param provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'next_hop_type': {'key': 'properties.nextHopType', 'type': 'str'},
'next_hop_ip_address': {'key': 'properties.nextHopIpAddress', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Route, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.next_hop_type = kwargs.get('next_hop_type', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class RouteFilter(Resource):
"""Route Filter Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rules: Collection of RouteFilterRules contained within a route filter.
:type rules: list[~azure.mgmt.network.v2019_04_01.models.RouteFilterRule]
:param peerings: A collection of references to express route circuit peerings.
:type peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:param ipv6_peerings: A collection of references to express route circuit ipv6 peerings.
:type ipv6_peerings: list[~azure.mgmt.network.v2019_04_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'},
'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'},
'ipv6_peerings': {'key': 'properties.ipv6Peerings', 'type': '[ExpressRouteCircuitPeering]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilter, self).__init__(**kwargs)
self.etag = None
self.rules = kwargs.get('rules', None)
self.peerings = kwargs.get('peerings', None)
self.ipv6_peerings = kwargs.get('ipv6_peerings', None)
self.provisioning_state = None
class RouteFilterListResult(msrest.serialization.Model):
"""Response for the ListRouteFilters API service call.
:param value: Gets a list of route filters in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.RouteFilter]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteFilter]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteFilterRule(SubResource):
"""Route Filter Rule Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param location: Resource location.
:type location: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param access: The access type of the rule. Possible values include: "Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.Access
:param route_filter_rule_type: The rule type of the rule. Possible values include: "Community".
:type route_filter_rule_type: str or ~azure.mgmt.network.v2019_04_01.models.RouteFilterRuleType
:param communities: The collection for bgp community values to filter on. e.g.
['12076:5010','12076:5020'].
:type communities: list[str]
:ivar provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'access': {'key': 'properties.access', 'type': 'str'},
'route_filter_rule_type': {'key': 'properties.routeFilterRuleType', 'type': 'str'},
'communities': {'key': 'properties.communities', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.location = kwargs.get('location', None)
self.etag = None
self.access = kwargs.get('access', None)
self.route_filter_rule_type = kwargs.get('route_filter_rule_type', None)
self.communities = kwargs.get('communities', None)
self.provisioning_state = None
class RouteFilterRuleListResult(msrest.serialization.Model):
"""Response for the ListRouteFilterRules API service call.
:param value: Gets a list of RouteFilterRules in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.RouteFilterRule]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteFilterRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteFilterRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteListResult(msrest.serialization.Model):
"""Response for the ListRoute API service call.
:param value: Gets a list of routes in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.Route]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Route]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class RouteTable(Resource):
"""Route table resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param routes: Collection of routes contained within a route table.
:type routes: list[~azure.mgmt.network.v2019_04_01.models.Route]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2019_04_01.models.Subnet]
:param disable_bgp_route_propagation: Gets or sets whether to disable the routes learned by BGP
on that route table. True means disable.
:type disable_bgp_route_propagation: bool
:param provisioning_state: The provisioning state of the resource. Possible values are:
'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'subnets': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'routes': {'key': 'properties.routes', 'type': '[Route]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'disable_bgp_route_propagation': {'key': 'properties.disableBgpRoutePropagation', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteTable, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.routes = kwargs.get('routes', None)
self.subnets = None
self.disable_bgp_route_propagation = kwargs.get('disable_bgp_route_propagation', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class RouteTableListResult(msrest.serialization.Model):
"""Response for the ListRouteTable API service call.
:param value: Gets a list of route tables in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.RouteTable]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[RouteTable]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(RouteTableListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class SecurityGroupNetworkInterface(msrest.serialization.Model):
"""Network interface and all its associated security rules.
:param id: ID of the network interface.
:type id: str
:param security_rule_associations: All security rules associated with the network interface.
:type security_rule_associations:
~azure.mgmt.network.v2019_04_01.models.SecurityRuleAssociations
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rule_associations': {'key': 'securityRuleAssociations', 'type': 'SecurityRuleAssociations'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupNetworkInterface, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.security_rule_associations = kwargs.get('security_rule_associations', None)
class SecurityGroupViewParameters(msrest.serialization.Model):
"""Parameters that define the VM to check security groups for.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. ID of the target VM.
:type target_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupViewParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
class SecurityGroupViewResult(msrest.serialization.Model):
"""The information about security rules applied to the specified VM.
:param network_interfaces: List of network interfaces on the specified VM.
:type network_interfaces:
list[~azure.mgmt.network.v2019_04_01.models.SecurityGroupNetworkInterface]
"""
_attribute_map = {
'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetworkInterface]'},
}
def __init__(
self,
**kwargs
):
super(SecurityGroupViewResult, self).__init__(**kwargs)
self.network_interfaces = kwargs.get('network_interfaces', None)
class SecurityRule(SubResource):
"""Network security rule.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param description: A description for this rule. Restricted to 140 chars.
:type description: str
:param protocol: Network protocol this rule applies to. Possible values include: "Tcp", "Udp",
"Icmp", "Esp", "*".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.SecurityRuleProtocol
:param source_port_range: The source port or range. Integer or range between 0 and 65535.
Asterisk '*' can also be used to match all ports.
:type source_port_range: str
:param destination_port_range: The destination port or range. Integer or range between 0 and
65535. Asterisk '*' can also be used to match all ports.
:type destination_port_range: str
:param source_address_prefix: The CIDR or source IP range. Asterisk '*' can also be used to
match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet'
can also be used. If this is an ingress rule, specifies where network traffic originates from.
:type source_address_prefix: str
:param source_address_prefixes: The CIDR or source IP ranges.
:type source_address_prefixes: list[str]
:param source_application_security_groups: The application security group specified as source.
:type source_application_security_groups:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationSecurityGroup]
:param destination_address_prefix: The destination address prefix. CIDR or destination IP
range. Asterisk '*' can also be used to match all source IPs. Default tags such as
'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used.
:type destination_address_prefix: str
:param destination_address_prefixes: The destination address prefixes. CIDR or destination IP
ranges.
:type destination_address_prefixes: list[str]
:param destination_application_security_groups: The application security group specified as
destination.
:type destination_application_security_groups:
list[~azure.mgmt.network.v2019_04_01.models.ApplicationSecurityGroup]
:param source_port_ranges: The source port ranges.
:type source_port_ranges: list[str]
:param destination_port_ranges: The destination port ranges.
:type destination_port_ranges: list[str]
:param access: The network traffic is allowed or denied. Possible values include: "Allow",
"Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.SecurityRuleAccess
:param priority: The priority of the rule. The value can be between 100 and 4096. The priority
number must be unique for each rule in the collection. The lower the priority number, the
higher the priority of the rule.
:type priority: int
:param direction: The direction of the rule. The direction specifies if rule will be evaluated
on incoming or outgoing traffic. Possible values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2019_04_01.models.SecurityRuleDirection
:param provisioning_state: The provisioning state of the public IP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'protocol': {'key': 'properties.protocol', 'type': 'str'},
'source_port_range': {'key': 'properties.sourcePortRange', 'type': 'str'},
'destination_port_range': {'key': 'properties.destinationPortRange', 'type': 'str'},
'source_address_prefix': {'key': 'properties.sourceAddressPrefix', 'type': 'str'},
'source_address_prefixes': {'key': 'properties.sourceAddressPrefixes', 'type': '[str]'},
'source_application_security_groups': {'key': 'properties.sourceApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'destination_address_prefix': {'key': 'properties.destinationAddressPrefix', 'type': 'str'},
'destination_address_prefixes': {'key': 'properties.destinationAddressPrefixes', 'type': '[str]'},
'destination_application_security_groups': {'key': 'properties.destinationApplicationSecurityGroups', 'type': '[ApplicationSecurityGroup]'},
'source_port_ranges': {'key': 'properties.sourcePortRanges', 'type': '[str]'},
'destination_port_ranges': {'key': 'properties.destinationPortRanges', 'type': '[str]'},
'access': {'key': 'properties.access', 'type': 'str'},
'priority': {'key': 'properties.priority', 'type': 'int'},
'direction': {'key': 'properties.direction', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.description = kwargs.get('description', None)
self.protocol = kwargs.get('protocol', None)
self.source_port_range = kwargs.get('source_port_range', None)
self.destination_port_range = kwargs.get('destination_port_range', None)
self.source_address_prefix = kwargs.get('source_address_prefix', None)
self.source_address_prefixes = kwargs.get('source_address_prefixes', None)
self.source_application_security_groups = kwargs.get('source_application_security_groups', None)
self.destination_address_prefix = kwargs.get('destination_address_prefix', None)
self.destination_address_prefixes = kwargs.get('destination_address_prefixes', None)
self.destination_application_security_groups = kwargs.get('destination_application_security_groups', None)
self.source_port_ranges = kwargs.get('source_port_ranges', None)
self.destination_port_ranges = kwargs.get('destination_port_ranges', None)
self.access = kwargs.get('access', None)
self.priority = kwargs.get('priority', None)
self.direction = kwargs.get('direction', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class SecurityRuleAssociations(msrest.serialization.Model):
"""All security rules associated with the network interface.
:param network_interface_association: Network interface and it's custom security rules.
:type network_interface_association:
~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceAssociation
:param subnet_association: Subnet and it's custom security rules.
:type subnet_association: ~azure.mgmt.network.v2019_04_01.models.SubnetAssociation
:param default_security_rules: Collection of default security rules of the network security
group.
:type default_security_rules: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
:param effective_security_rules: Collection of effective security rules.
:type effective_security_rules:
list[~azure.mgmt.network.v2019_04_01.models.EffectiveNetworkSecurityRule]
"""
_attribute_map = {
'network_interface_association': {'key': 'networkInterfaceAssociation', 'type': 'NetworkInterfaceAssociation'},
'subnet_association': {'key': 'subnetAssociation', 'type': 'SubnetAssociation'},
'default_security_rules': {'key': 'defaultSecurityRules', 'type': '[SecurityRule]'},
'effective_security_rules': {'key': 'effectiveSecurityRules', 'type': '[EffectiveNetworkSecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(SecurityRuleAssociations, self).__init__(**kwargs)
self.network_interface_association = kwargs.get('network_interface_association', None)
self.subnet_association = kwargs.get('subnet_association', None)
self.default_security_rules = kwargs.get('default_security_rules', None)
self.effective_security_rules = kwargs.get('effective_security_rules', None)
class SecurityRuleListResult(msrest.serialization.Model):
"""Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a network security group.
:param value: The security rules in a network security group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[SecurityRule]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SecurityRuleListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ServiceAssociationLink(SubResource):
"""ServiceAssociationLink resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param type: Resource type.
:type type: str
:param linked_resource_type: Resource type of the linked resource.
:type linked_resource_type: str
:param link: Link to the external resource.
:type link: str
:ivar provisioning_state: Provisioning state of the ServiceAssociationLink resource.
:vartype provisioning_state: str
:param allow_delete: If true, the resource can be deleted.
:type allow_delete: bool
:param locations: A list of locations.
:type locations: list[str]
"""
_validation = {
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'linked_resource_type': {'key': 'properties.linkedResourceType', 'type': 'str'},
'link': {'key': 'properties.link', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'allow_delete': {'key': 'properties.allowDelete', 'type': 'bool'},
'locations': {'key': 'properties.locations', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ServiceAssociationLink, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.type = kwargs.get('type', None)
self.linked_resource_type = kwargs.get('linked_resource_type', None)
self.link = kwargs.get('link', None)
self.provisioning_state = None
self.allow_delete = kwargs.get('allow_delete', None)
self.locations = kwargs.get('locations', None)
class ServiceAssociationLinksListResult(msrest.serialization.Model):
"""Response for ServiceAssociationLinks_List operation.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: The service association links in a subnet.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ServiceAssociationLink]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceAssociationLink]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceAssociationLinksListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ServiceEndpointPolicy(Resource):
"""Service End point policy resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param service_endpoint_policy_definitions: A collection of service endpoint policy definitions
of the service endpoint policy.
:type service_endpoint_policy_definitions:
list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPolicyDefinition]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2019_04_01.models.Subnet]
:ivar resource_guid: The resource GUID property of the service endpoint policy resource.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the service endpoint policy. Possible
values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'subnets': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'service_endpoint_policy_definitions': {'key': 'properties.serviceEndpointPolicyDefinitions', 'type': '[ServiceEndpointPolicyDefinition]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicy, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.service_endpoint_policy_definitions = kwargs.get('service_endpoint_policy_definitions', None)
self.subnets = None
self.resource_guid = None
self.provisioning_state = None
class ServiceEndpointPolicyDefinition(SubResource):
"""Service Endpoint policy definitions.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param description: A description for this rule. Restricted to 140 chars.
:type description: str
:param service: Service endpoint name.
:type service: str
:param service_resources: A list of service resources.
:type service_resources: list[str]
:ivar provisioning_state: The provisioning state of the service end point policy definition.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'description': {'key': 'properties.description', 'type': 'str'},
'service': {'key': 'properties.service', 'type': 'str'},
'service_resources': {'key': 'properties.serviceResources', 'type': '[str]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyDefinition, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.description = kwargs.get('description', None)
self.service = kwargs.get('service', None)
self.service_resources = kwargs.get('service_resources', None)
self.provisioning_state = None
class ServiceEndpointPolicyDefinitionListResult(msrest.serialization.Model):
"""Response for ListServiceEndpointPolicyDefinition API service call. Retrieves all service endpoint policy definition that belongs to a service endpoint policy.
:param value: The service endpoint policy definition in a service endpoint policy.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPolicyDefinition]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceEndpointPolicyDefinition]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyDefinitionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class ServiceEndpointPolicyListResult(msrest.serialization.Model):
"""Response for ListServiceEndpointPolicies API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of ServiceEndpointPolicy resources.
:type value: list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPolicy]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[ServiceEndpointPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPolicyListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class ServiceEndpointPropertiesFormat(msrest.serialization.Model):
"""The service endpoint properties.
:param service: The type of the endpoint service.
:type service: str
:param locations: A list of locations.
:type locations: list[str]
:param provisioning_state: The provisioning state of the resource.
:type provisioning_state: str
"""
_attribute_map = {
'service': {'key': 'service', 'type': 'str'},
'locations': {'key': 'locations', 'type': '[str]'},
'provisioning_state': {'key': 'provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceEndpointPropertiesFormat, self).__init__(**kwargs)
self.service = kwargs.get('service', None)
self.locations = kwargs.get('locations', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class ServiceTagInformation(msrest.serialization.Model):
"""The service tag information.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar properties: Properties of the service tag information.
:vartype properties:
~azure.mgmt.network.v2019_04_01.models.ServiceTagInformationPropertiesFormat
:ivar name: The name of service tag.
:vartype name: str
:ivar id: The ID of service tag.
:vartype id: str
"""
_validation = {
'properties': {'readonly': True},
'name': {'readonly': True},
'id': {'readonly': True},
}
_attribute_map = {
'properties': {'key': 'properties', 'type': 'ServiceTagInformationPropertiesFormat'},
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagInformation, self).__init__(**kwargs)
self.properties = None
self.name = None
self.id = None
class ServiceTagInformationPropertiesFormat(msrest.serialization.Model):
"""Properties of the service tag information.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar change_number: The iteration number of service tag.
:vartype change_number: str
:ivar region: The region of service tag.
:vartype region: str
:ivar system_service: The name of system service.
:vartype system_service: str
:ivar address_prefixes: The list of IP address prefixes.
:vartype address_prefixes: list[str]
"""
_validation = {
'change_number': {'readonly': True},
'region': {'readonly': True},
'system_service': {'readonly': True},
'address_prefixes': {'readonly': True},
}
_attribute_map = {
'change_number': {'key': 'changeNumber', 'type': 'str'},
'region': {'key': 'region', 'type': 'str'},
'system_service': {'key': 'systemService', 'type': 'str'},
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagInformationPropertiesFormat, self).__init__(**kwargs)
self.change_number = None
self.region = None
self.system_service = None
self.address_prefixes = None
class ServiceTagsListResult(msrest.serialization.Model):
"""Response for the ListServiceTags API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name: The name of the cloud.
:vartype name: str
:ivar id: The ID of the cloud.
:vartype id: str
:ivar type: The azure resource type.
:vartype type: str
:ivar change_number: The iteration number.
:vartype change_number: str
:ivar cloud: The name of the cloud.
:vartype cloud: str
:ivar values: The list of service tag information resources.
:vartype values: list[~azure.mgmt.network.v2019_04_01.models.ServiceTagInformation]
"""
_validation = {
'name': {'readonly': True},
'id': {'readonly': True},
'type': {'readonly': True},
'change_number': {'readonly': True},
'cloud': {'readonly': True},
'values': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'change_number': {'key': 'changeNumber', 'type': 'str'},
'cloud': {'key': 'cloud', 'type': 'str'},
'values': {'key': 'values', 'type': '[ServiceTagInformation]'},
}
def __init__(
self,
**kwargs
):
super(ServiceTagsListResult, self).__init__(**kwargs)
self.name = None
self.id = None
self.type = None
self.change_number = None
self.cloud = None
self.values = None
class Subnet(SubResource):
"""Subnet in a virtual network resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param address_prefix: The address prefix for the subnet.
:type address_prefix: str
:param address_prefixes: List of address prefixes for the subnet.
:type address_prefixes: list[str]
:param network_security_group: The reference of the NetworkSecurityGroup resource.
:type network_security_group: ~azure.mgmt.network.v2019_04_01.models.NetworkSecurityGroup
:param route_table: The reference of the RouteTable resource.
:type route_table: ~azure.mgmt.network.v2019_04_01.models.RouteTable
:param nat_gateway: Nat gateway associated with this subnet.
:type nat_gateway: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param service_endpoints: An array of service endpoints.
:type service_endpoints:
list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPropertiesFormat]
:param service_endpoint_policies: An array of service endpoint policies.
:type service_endpoint_policies:
list[~azure.mgmt.network.v2019_04_01.models.ServiceEndpointPolicy]
:ivar private_endpoints: An array of references to private endpoints.
:vartype private_endpoints: list[~azure.mgmt.network.v2019_04_01.models.PrivateEndpoint]
:ivar ip_configurations: Gets an array of references to the network interface IP configurations
using subnet.
:vartype ip_configurations: list[~azure.mgmt.network.v2019_04_01.models.IPConfiguration]
:ivar ip_configuration_profiles: Array of IP configuration profiles which reference this
subnet.
:vartype ip_configuration_profiles:
list[~azure.mgmt.network.v2019_04_01.models.IPConfigurationProfile]
:param resource_navigation_links: Gets an array of references to the external resources using
subnet.
:type resource_navigation_links:
list[~azure.mgmt.network.v2019_04_01.models.ResourceNavigationLink]
:param service_association_links: Gets an array of references to services injecting into this
subnet.
:type service_association_links:
list[~azure.mgmt.network.v2019_04_01.models.ServiceAssociationLink]
:param delegations: Gets an array of references to the delegations on the subnet.
:type delegations: list[~azure.mgmt.network.v2019_04_01.models.Delegation]
:ivar purpose: A read-only string identifying the intention of use for this subnet based on
delegations and other user-defined properties.
:vartype purpose: str
:param provisioning_state: The provisioning state of the resource.
:type provisioning_state: str
:param private_endpoint_network_policies: Enable or Disable private end point on the subnet.
:type private_endpoint_network_policies: str
:param private_link_service_network_policies: Enable or Disable private link service on the
subnet.
:type private_link_service_network_policies: str
"""
_validation = {
'private_endpoints': {'readonly': True},
'ip_configurations': {'readonly': True},
'ip_configuration_profiles': {'readonly': True},
'purpose': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'address_prefixes': {'key': 'properties.addressPrefixes', 'type': '[str]'},
'network_security_group': {'key': 'properties.networkSecurityGroup', 'type': 'NetworkSecurityGroup'},
'route_table': {'key': 'properties.routeTable', 'type': 'RouteTable'},
'nat_gateway': {'key': 'properties.natGateway', 'type': 'SubResource'},
'service_endpoints': {'key': 'properties.serviceEndpoints', 'type': '[ServiceEndpointPropertiesFormat]'},
'service_endpoint_policies': {'key': 'properties.serviceEndpointPolicies', 'type': '[ServiceEndpointPolicy]'},
'private_endpoints': {'key': 'properties.privateEndpoints', 'type': '[PrivateEndpoint]'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[IPConfiguration]'},
'ip_configuration_profiles': {'key': 'properties.ipConfigurationProfiles', 'type': '[IPConfigurationProfile]'},
'resource_navigation_links': {'key': 'properties.resourceNavigationLinks', 'type': '[ResourceNavigationLink]'},
'service_association_links': {'key': 'properties.serviceAssociationLinks', 'type': '[ServiceAssociationLink]'},
'delegations': {'key': 'properties.delegations', 'type': '[Delegation]'},
'purpose': {'key': 'properties.purpose', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'private_endpoint_network_policies': {'key': 'properties.privateEndpointNetworkPolicies', 'type': 'str'},
'private_link_service_network_policies': {'key': 'properties.privateLinkServiceNetworkPolicies', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Subnet, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.address_prefixes = kwargs.get('address_prefixes', None)
self.network_security_group = kwargs.get('network_security_group', None)
self.route_table = kwargs.get('route_table', None)
self.nat_gateway = kwargs.get('nat_gateway', None)
self.service_endpoints = kwargs.get('service_endpoints', None)
self.service_endpoint_policies = kwargs.get('service_endpoint_policies', None)
self.private_endpoints = None
self.ip_configurations = None
self.ip_configuration_profiles = None
self.resource_navigation_links = kwargs.get('resource_navigation_links', None)
self.service_association_links = kwargs.get('service_association_links', None)
self.delegations = kwargs.get('delegations', None)
self.purpose = None
self.provisioning_state = kwargs.get('provisioning_state', None)
self.private_endpoint_network_policies = kwargs.get('private_endpoint_network_policies', None)
self.private_link_service_network_policies = kwargs.get('private_link_service_network_policies', None)
class SubnetAssociation(msrest.serialization.Model):
"""Subnet and it's custom security rules.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Subnet ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules: list[~azure.mgmt.network.v2019_04_01.models.SecurityRule]
"""
_validation = {
'id': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'security_rules': {'key': 'securityRules', 'type': '[SecurityRule]'},
}
def __init__(
self,
**kwargs
):
super(SubnetAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = kwargs.get('security_rules', None)
class SubnetListResult(msrest.serialization.Model):
"""Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network.
:param value: The subnets in a virtual network.
:type value: list[~azure.mgmt.network.v2019_04_01.models.Subnet]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Subnet]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(SubnetListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class TagsObject(msrest.serialization.Model):
"""Tags object for patch operations.
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(TagsObject, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
class Topology(msrest.serialization.Model):
"""Topology of the specified resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: GUID representing the operation id.
:vartype id: str
:ivar created_date_time: The datetime when the topology was initially created for the resource
group.
:vartype created_date_time: ~datetime.datetime
:ivar last_modified: The datetime when the topology was last modified.
:vartype last_modified: ~datetime.datetime
:param resources: A list of topology resources.
:type resources: list[~azure.mgmt.network.v2019_04_01.models.TopologyResource]
"""
_validation = {
'id': {'readonly': True},
'created_date_time': {'readonly': True},
'last_modified': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'created_date_time': {'key': 'createdDateTime', 'type': 'iso-8601'},
'last_modified': {'key': 'lastModified', 'type': 'iso-8601'},
'resources': {'key': 'resources', 'type': '[TopologyResource]'},
}
def __init__(
self,
**kwargs
):
super(Topology, self).__init__(**kwargs)
self.id = None
self.created_date_time = None
self.last_modified = None
self.resources = kwargs.get('resources', None)
class TopologyAssociation(msrest.serialization.Model):
"""Resources that have an association with the parent resource.
:param name: The name of the resource that is associated with the parent resource.
:type name: str
:param resource_id: The ID of the resource that is associated with the parent resource.
:type resource_id: str
:param association_type: The association type of the child resource to the parent resource.
Possible values include: "Associated", "Contains".
:type association_type: str or ~azure.mgmt.network.v2019_04_01.models.AssociationType
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'resource_id': {'key': 'resourceId', 'type': 'str'},
'association_type': {'key': 'associationType', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TopologyAssociation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.resource_id = kwargs.get('resource_id', None)
self.association_type = kwargs.get('association_type', None)
class TopologyParameters(msrest.serialization.Model):
"""Parameters that define the representation of topology.
:param target_resource_group_name: The name of the target resource group to perform topology
on.
:type target_resource_group_name: str
:param target_virtual_network: The reference of the Virtual Network resource.
:type target_virtual_network: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param target_subnet: The reference of the Subnet resource.
:type target_subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
"""
_attribute_map = {
'target_resource_group_name': {'key': 'targetResourceGroupName', 'type': 'str'},
'target_virtual_network': {'key': 'targetVirtualNetwork', 'type': 'SubResource'},
'target_subnet': {'key': 'targetSubnet', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(TopologyParameters, self).__init__(**kwargs)
self.target_resource_group_name = kwargs.get('target_resource_group_name', None)
self.target_virtual_network = kwargs.get('target_virtual_network', None)
self.target_subnet = kwargs.get('target_subnet', None)
class TopologyResource(msrest.serialization.Model):
"""The network resource topology information for the given resource group.
:param name: Name of the resource.
:type name: str
:param id: ID of the resource.
:type id: str
:param location: Resource location.
:type location: str
:param associations: Holds the associations the resource has with other resources in the
resource group.
:type associations: list[~azure.mgmt.network.v2019_04_01.models.TopologyAssociation]
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'associations': {'key': 'associations', 'type': '[TopologyAssociation]'},
}
def __init__(
self,
**kwargs
):
super(TopologyResource, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.id = kwargs.get('id', None)
self.location = kwargs.get('location', None)
self.associations = kwargs.get('associations', None)
class TrafficAnalyticsConfigurationProperties(msrest.serialization.Model):
"""Parameters that define the configuration of traffic analytics.
All required parameters must be populated in order to send to Azure.
:param enabled: Required. Flag to enable/disable traffic analytics.
:type enabled: bool
:param workspace_id: Required. The resource guid of the attached workspace.
:type workspace_id: str
:param workspace_region: Required. The location of the attached workspace.
:type workspace_region: str
:param workspace_resource_id: Required. Resource Id of the attached workspace.
:type workspace_resource_id: str
:param traffic_analytics_interval: The interval in minutes which would decide how frequently TA
service should do flow analytics.
:type traffic_analytics_interval: int
"""
_validation = {
'enabled': {'required': True},
'workspace_id': {'required': True},
'workspace_region': {'required': True},
'workspace_resource_id': {'required': True},
}
_attribute_map = {
'enabled': {'key': 'enabled', 'type': 'bool'},
'workspace_id': {'key': 'workspaceId', 'type': 'str'},
'workspace_region': {'key': 'workspaceRegion', 'type': 'str'},
'workspace_resource_id': {'key': 'workspaceResourceId', 'type': 'str'},
'traffic_analytics_interval': {'key': 'trafficAnalyticsInterval', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(TrafficAnalyticsConfigurationProperties, self).__init__(**kwargs)
self.enabled = kwargs['enabled']
self.workspace_id = kwargs['workspace_id']
self.workspace_region = kwargs['workspace_region']
self.workspace_resource_id = kwargs['workspace_resource_id']
self.traffic_analytics_interval = kwargs.get('traffic_analytics_interval', None)
class TrafficAnalyticsProperties(msrest.serialization.Model):
"""Parameters that define the configuration of traffic analytics.
All required parameters must be populated in order to send to Azure.
:param network_watcher_flow_analytics_configuration: Required. Parameters that define the
configuration of traffic analytics.
:type network_watcher_flow_analytics_configuration:
~azure.mgmt.network.v2019_04_01.models.TrafficAnalyticsConfigurationProperties
"""
_validation = {
'network_watcher_flow_analytics_configuration': {'required': True},
}
_attribute_map = {
'network_watcher_flow_analytics_configuration': {'key': 'networkWatcherFlowAnalyticsConfiguration', 'type': 'TrafficAnalyticsConfigurationProperties'},
}
def __init__(
self,
**kwargs
):
super(TrafficAnalyticsProperties, self).__init__(**kwargs)
self.network_watcher_flow_analytics_configuration = kwargs['network_watcher_flow_analytics_configuration']
class TroubleshootingDetails(msrest.serialization.Model):
"""Information gained from troubleshooting of specified resource.
:param id: The id of the get troubleshoot operation.
:type id: str
:param reason_type: Reason type of failure.
:type reason_type: str
:param summary: A summary of troubleshooting.
:type summary: str
:param detail: Details on troubleshooting results.
:type detail: str
:param recommended_actions: List of recommended actions.
:type recommended_actions:
list[~azure.mgmt.network.v2019_04_01.models.TroubleshootingRecommendedActions]
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'reason_type': {'key': 'reasonType', 'type': 'str'},
'summary': {'key': 'summary', 'type': 'str'},
'detail': {'key': 'detail', 'type': 'str'},
'recommended_actions': {'key': 'recommendedActions', 'type': '[TroubleshootingRecommendedActions]'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingDetails, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.reason_type = kwargs.get('reason_type', None)
self.summary = kwargs.get('summary', None)
self.detail = kwargs.get('detail', None)
self.recommended_actions = kwargs.get('recommended_actions', None)
class TroubleshootingParameters(msrest.serialization.Model):
"""Parameters that define the resource to troubleshoot.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The target resource to troubleshoot.
:type target_resource_id: str
:param storage_id: Required. The ID for the storage account to save the troubleshoot result.
:type storage_id: str
:param storage_path: Required. The path to the blob to save the troubleshoot result in.
:type storage_path: str
"""
_validation = {
'target_resource_id': {'required': True},
'storage_id': {'required': True},
'storage_path': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'storage_id': {'key': 'properties.storageId', 'type': 'str'},
'storage_path': {'key': 'properties.storagePath', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.storage_id = kwargs['storage_id']
self.storage_path = kwargs['storage_path']
class TroubleshootingRecommendedActions(msrest.serialization.Model):
"""Recommended actions based on discovered issues.
:param action_id: ID of the recommended action.
:type action_id: str
:param action_text: Description of recommended actions.
:type action_text: str
:param action_uri: The uri linking to a documentation for the recommended troubleshooting
actions.
:type action_uri: str
:param action_uri_text: The information from the URI for the recommended troubleshooting
actions.
:type action_uri_text: str
"""
_attribute_map = {
'action_id': {'key': 'actionId', 'type': 'str'},
'action_text': {'key': 'actionText', 'type': 'str'},
'action_uri': {'key': 'actionUri', 'type': 'str'},
'action_uri_text': {'key': 'actionUriText', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingRecommendedActions, self).__init__(**kwargs)
self.action_id = kwargs.get('action_id', None)
self.action_text = kwargs.get('action_text', None)
self.action_uri = kwargs.get('action_uri', None)
self.action_uri_text = kwargs.get('action_uri_text', None)
class TroubleshootingResult(msrest.serialization.Model):
"""Troubleshooting information gained from specified resource.
:param start_time: The start time of the troubleshooting.
:type start_time: ~datetime.datetime
:param end_time: The end time of the troubleshooting.
:type end_time: ~datetime.datetime
:param code: The result code of the troubleshooting.
:type code: str
:param results: Information from troubleshooting.
:type results: list[~azure.mgmt.network.v2019_04_01.models.TroubleshootingDetails]
"""
_attribute_map = {
'start_time': {'key': 'startTime', 'type': 'iso-8601'},
'end_time': {'key': 'endTime', 'type': 'iso-8601'},
'code': {'key': 'code', 'type': 'str'},
'results': {'key': 'results', 'type': '[TroubleshootingDetails]'},
}
def __init__(
self,
**kwargs
):
super(TroubleshootingResult, self).__init__(**kwargs)
self.start_time = kwargs.get('start_time', None)
self.end_time = kwargs.get('end_time', None)
self.code = kwargs.get('code', None)
self.results = kwargs.get('results', None)
class TunnelConnectionHealth(msrest.serialization.Model):
"""VirtualNetworkGatewayConnection properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar tunnel: Tunnel name.
:vartype tunnel: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar ingress_bytes_transferred: The Ingress Bytes Transferred in this connection.
:vartype ingress_bytes_transferred: long
:ivar egress_bytes_transferred: The Egress Bytes Transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar last_connection_established_utc_time: The time at which connection was established in Utc
format.
:vartype last_connection_established_utc_time: str
"""
_validation = {
'tunnel': {'readonly': True},
'connection_status': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'last_connection_established_utc_time': {'readonly': True},
}
_attribute_map = {
'tunnel': {'key': 'tunnel', 'type': 'str'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'},
'last_connection_established_utc_time': {'key': 'lastConnectionEstablishedUtcTime', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TunnelConnectionHealth, self).__init__(**kwargs)
self.tunnel = None
self.connection_status = None
self.ingress_bytes_transferred = None
self.egress_bytes_transferred = None
self.last_connection_established_utc_time = None
class Usage(msrest.serialization.Model):
"""Describes network resource usage.
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.
:ivar id: Resource identifier.
:vartype id: str
:param unit: Required. An enum describing the unit of measurement. Possible values include:
"Count".
:type unit: str or ~azure.mgmt.network.v2019_04_01.models.UsageUnit
:param current_value: Required. The current value of the usage.
:type current_value: long
:param limit: Required. The limit of usage.
:type limit: long
:param name: Required. The name of the type of usage.
:type name: ~azure.mgmt.network.v2019_04_01.models.UsageName
"""
_validation = {
'id': {'readonly': True},
'unit': {'required': True},
'current_value': {'required': True},
'limit': {'required': True},
'name': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'unit': {'key': 'unit', 'type': 'str'},
'current_value': {'key': 'currentValue', 'type': 'long'},
'limit': {'key': 'limit', 'type': 'long'},
'name': {'key': 'name', 'type': 'UsageName'},
}
def __init__(
self,
**kwargs
):
super(Usage, self).__init__(**kwargs)
self.id = None
self.unit = kwargs['unit']
self.current_value = kwargs['current_value']
self.limit = kwargs['limit']
self.name = kwargs['name']
class UsageName(msrest.serialization.Model):
"""The usage names.
:param value: A string describing the resource name.
:type value: str
:param localized_value: A localized string describing the resource name.
:type localized_value: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': 'str'},
'localized_value': {'key': 'localizedValue', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(UsageName, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.localized_value = kwargs.get('localized_value', None)
class UsagesListResult(msrest.serialization.Model):
"""The list usages operation response.
:param value: The list network resource usages.
:type value: list[~azure.mgmt.network.v2019_04_01.models.Usage]
:param next_link: URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Usage]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(UsagesListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VerificationIPFlowParameters(msrest.serialization.Model):
"""Parameters that define the IP flow to be verified.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the target resource to perform next-hop on.
:type target_resource_id: str
:param direction: Required. The direction of the packet represented as a 5-tuple. Possible
values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2019_04_01.models.Direction
:param protocol: Required. Protocol to be verified on. Possible values include: "TCP", "UDP".
:type protocol: str or ~azure.mgmt.network.v2019_04_01.models.IpFlowProtocol
:param local_port: Required. The local port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type local_port: str
:param remote_port: Required. The remote port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type remote_port: str
:param local_ip_address: Required. The local IP address. Acceptable values are valid IPv4
addresses.
:type local_ip_address: str
:param remote_ip_address: Required. The remote IP address. Acceptable values are valid IPv4
addresses.
:type remote_ip_address: str
:param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is
enabled on any of them, then this parameter must be specified. Otherwise optional).
:type target_nic_resource_id: str
"""
_validation = {
'target_resource_id': {'required': True},
'direction': {'required': True},
'protocol': {'required': True},
'local_port': {'required': True},
'remote_port': {'required': True},
'local_ip_address': {'required': True},
'remote_ip_address': {'required': True},
}
_attribute_map = {
'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
'direction': {'key': 'direction', 'type': 'str'},
'protocol': {'key': 'protocol', 'type': 'str'},
'local_port': {'key': 'localPort', 'type': 'str'},
'remote_port': {'key': 'remotePort', 'type': 'str'},
'local_ip_address': {'key': 'localIPAddress', 'type': 'str'},
'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'},
'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VerificationIPFlowParameters, self).__init__(**kwargs)
self.target_resource_id = kwargs['target_resource_id']
self.direction = kwargs['direction']
self.protocol = kwargs['protocol']
self.local_port = kwargs['local_port']
self.remote_port = kwargs['remote_port']
self.local_ip_address = kwargs['local_ip_address']
self.remote_ip_address = kwargs['remote_ip_address']
self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None)
class VerificationIPFlowResult(msrest.serialization.Model):
"""Results of IP flow verification on the target resource.
:param access: Indicates whether the traffic is allowed or denied. Possible values include:
"Allow", "Deny".
:type access: str or ~azure.mgmt.network.v2019_04_01.models.Access
:param rule_name: Name of the rule. If input is not matched against any security rule, it is
not displayed.
:type rule_name: str
"""
_attribute_map = {
'access': {'key': 'access', 'type': 'str'},
'rule_name': {'key': 'ruleName', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VerificationIPFlowResult, self).__init__(**kwargs)
self.access = kwargs.get('access', None)
self.rule_name = kwargs.get('rule_name', None)
class VirtualHub(Resource):
"""VirtualHub Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_wan: The VirtualWAN to which the VirtualHub belongs.
:type virtual_wan: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param vpn_gateway: The VpnGateway associated with this VirtualHub.
:type vpn_gateway: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param p2_s_vpn_gateway: The P2SVpnGateway associated with this VirtualHub.
:type p2_s_vpn_gateway: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param express_route_gateway: The expressRouteGateway associated with this VirtualHub.
:type express_route_gateway: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param virtual_network_connections: List of all vnet connections with this VirtualHub.
:type virtual_network_connections:
list[~azure.mgmt.network.v2019_04_01.models.HubVirtualNetworkConnection]
:param address_prefix: Address-prefix for this VirtualHub.
:type address_prefix: str
:param route_table: The routeTable associated with this virtual hub.
:type route_table: ~azure.mgmt.network.v2019_04_01.models.VirtualHubRouteTable
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'},
'vpn_gateway': {'key': 'properties.vpnGateway', 'type': 'SubResource'},
'p2_s_vpn_gateway': {'key': 'properties.p2SVpnGateway', 'type': 'SubResource'},
'express_route_gateway': {'key': 'properties.expressRouteGateway', 'type': 'SubResource'},
'virtual_network_connections': {'key': 'properties.virtualNetworkConnections', 'type': '[HubVirtualNetworkConnection]'},
'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'},
'route_table': {'key': 'properties.routeTable', 'type': 'VirtualHubRouteTable'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHub, self).__init__(**kwargs)
self.etag = None
self.virtual_wan = kwargs.get('virtual_wan', None)
self.vpn_gateway = kwargs.get('vpn_gateway', None)
self.p2_s_vpn_gateway = kwargs.get('p2_s_vpn_gateway', None)
self.express_route_gateway = kwargs.get('express_route_gateway', None)
self.virtual_network_connections = kwargs.get('virtual_network_connections', None)
self.address_prefix = kwargs.get('address_prefix', None)
self.route_table = kwargs.get('route_table', None)
self.provisioning_state = None
class VirtualHubId(msrest.serialization.Model):
"""Virtual Hub identifier.
:param id: The resource URI for the Virtual Hub where the ExpressRoute gateway is or will be
deployed. The Virtual Hub resource and the ExpressRoute gateway resource reside in the same
subscription.
:type id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubId, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
class VirtualHubRoute(msrest.serialization.Model):
"""VirtualHub route.
:param address_prefixes: List of all addressPrefixes.
:type address_prefixes: list[str]
:param next_hop_ip_address: NextHop ip address.
:type next_hop_ip_address: str
"""
_attribute_map = {
'address_prefixes': {'key': 'addressPrefixes', 'type': '[str]'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRoute, self).__init__(**kwargs)
self.address_prefixes = kwargs.get('address_prefixes', None)
self.next_hop_ip_address = kwargs.get('next_hop_ip_address', None)
class VirtualHubRouteTable(msrest.serialization.Model):
"""VirtualHub route table.
:param routes: List of all routes.
:type routes: list[~azure.mgmt.network.v2019_04_01.models.VirtualHubRoute]
"""
_attribute_map = {
'routes': {'key': 'routes', 'type': '[VirtualHubRoute]'},
}
def __init__(
self,
**kwargs
):
super(VirtualHubRouteTable, self).__init__(**kwargs)
self.routes = kwargs.get('routes', None)
class VirtualNetwork(Resource):
"""Virtual Network resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param address_space: The AddressSpace that contains an array of IP address ranges that can be
used by subnets.
:type address_space: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param dhcp_options: The dhcpOptions that contains an array of DNS servers available to VMs
deployed in the virtual network.
:type dhcp_options: ~azure.mgmt.network.v2019_04_01.models.DhcpOptions
:param subnets: A list of subnets in a Virtual Network.
:type subnets: list[~azure.mgmt.network.v2019_04_01.models.Subnet]
:param virtual_network_peerings: A list of peerings in a Virtual Network.
:type virtual_network_peerings:
list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkPeering]
:param resource_guid: The resourceGuid property of the Virtual Network resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the PublicIP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param enable_ddos_protection: Indicates if DDoS protection is enabled for all the protected
resources in the virtual network. It requires a DDoS protection plan associated with the
resource.
:type enable_ddos_protection: bool
:param enable_vm_protection: Indicates if VM protection is enabled for all the subnets in the
virtual network.
:type enable_vm_protection: bool
:param ddos_protection_plan: The DDoS protection plan associated with the virtual network.
:type ddos_protection_plan: ~azure.mgmt.network.v2019_04_01.models.SubResource
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'},
'dhcp_options': {'key': 'properties.dhcpOptions', 'type': 'DhcpOptions'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'virtual_network_peerings': {'key': 'properties.virtualNetworkPeerings', 'type': '[VirtualNetworkPeering]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'enable_ddos_protection': {'key': 'properties.enableDdosProtection', 'type': 'bool'},
'enable_vm_protection': {'key': 'properties.enableVmProtection', 'type': 'bool'},
'ddos_protection_plan': {'key': 'properties.ddosProtectionPlan', 'type': 'SubResource'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetwork, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.address_space = kwargs.get('address_space', None)
self.dhcp_options = kwargs.get('dhcp_options', None)
self.subnets = kwargs.get('subnets', None)
self.virtual_network_peerings = kwargs.get('virtual_network_peerings', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
self.enable_ddos_protection = kwargs.get('enable_ddos_protection', False)
self.enable_vm_protection = kwargs.get('enable_vm_protection', False)
self.ddos_protection_plan = kwargs.get('ddos_protection_plan', None)
class VirtualNetworkConnectionGatewayReference(msrest.serialization.Model):
"""A reference to VirtualNetworkGateway or LocalNetworkGateway resource.
All required parameters must be populated in order to send to Azure.
:param id: Required. The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
:type id: str
"""
_validation = {
'id': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkConnectionGatewayReference, self).__init__(**kwargs)
self.id = kwargs['id']
class VirtualNetworkGateway(Resource):
"""A common class for general resource information.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param ip_configurations: IP configurations for virtual network gateway.
:type ip_configurations:
list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayIPConfiguration]
:param gateway_type: The type of this virtual network gateway. Possible values include: "Vpn",
"ExpressRoute".
:type gateway_type: str or ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayType
:param vpn_type: The type of this virtual network gateway. Possible values include:
"PolicyBased", "RouteBased".
:type vpn_type: str or ~azure.mgmt.network.v2019_04_01.models.VpnType
:param enable_bgp: Whether BGP is enabled for this virtual network gateway or not.
:type enable_bgp: bool
:param active: ActiveActive flag.
:type active: bool
:param gateway_default_site: The reference of the LocalNetworkGateway resource which represents
local network site having default routes. Assign Null value in case of removing existing
default site setting.
:type gateway_default_site: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param sku: The reference of the VirtualNetworkGatewaySku resource which represents the SKU
selected for Virtual network gateway.
:type sku: ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewaySku
:param vpn_client_configuration: The reference of the VpnClientConfiguration resource which
represents the P2S VpnClient configurations.
:type vpn_client_configuration: ~azure.mgmt.network.v2019_04_01.models.VpnClientConfiguration
:param bgp_settings: Virtual network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2019_04_01.models.BgpSettings
:param custom_routes: The reference of the address space resource which represents the custom
routes address space specified by the customer for virtual network gateway and VpnClient.
:type custom_routes: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param resource_guid: The resource GUID property of the VirtualNetworkGateway resource.
:type resource_guid: str
:ivar provisioning_state: The provisioning state of the VirtualNetworkGateway resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualNetworkGatewayIPConfiguration]'},
'gateway_type': {'key': 'properties.gatewayType', 'type': 'str'},
'vpn_type': {'key': 'properties.vpnType', 'type': 'str'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'active': {'key': 'properties.activeActive', 'type': 'bool'},
'gateway_default_site': {'key': 'properties.gatewayDefaultSite', 'type': 'SubResource'},
'sku': {'key': 'properties.sku', 'type': 'VirtualNetworkGatewaySku'},
'vpn_client_configuration': {'key': 'properties.vpnClientConfiguration', 'type': 'VpnClientConfiguration'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'custom_routes': {'key': 'properties.customRoutes', 'type': 'AddressSpace'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGateway, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.ip_configurations = kwargs.get('ip_configurations', None)
self.gateway_type = kwargs.get('gateway_type', None)
self.vpn_type = kwargs.get('vpn_type', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.active = kwargs.get('active', None)
self.gateway_default_site = kwargs.get('gateway_default_site', None)
self.sku = kwargs.get('sku', None)
self.vpn_client_configuration = kwargs.get('vpn_client_configuration', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.custom_routes = kwargs.get('custom_routes', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = None
class VirtualNetworkGatewayConnection(Resource):
"""A common class for general resource information.
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: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param authorization_key: The authorizationKey.
:type authorization_key: str
:param virtual_network_gateway1: Required. The reference to virtual network gateway resource.
:type virtual_network_gateway1: ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGateway
:param virtual_network_gateway2: The reference to virtual network gateway resource.
:type virtual_network_gateway2: ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGateway
:param local_network_gateway2: The reference to local network gateway resource.
:type local_network_gateway2: ~azure.mgmt.network.v2019_04_01.models.LocalNetworkGateway
:param connection_type: Required. Gateway connection type. Possible values include: "IPsec",
"Vnet2Vnet", "ExpressRoute", "VPNClient".
:type connection_type: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionType
:param connection_protocol: Connection protocol used for this connection. Possible values
include: "IKEv2", "IKEv1".
:type connection_protocol: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionProtocol
:param routing_weight: The routing weight.
:type routing_weight: int
:param shared_key: The IPSec shared key.
:type shared_key: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar tunnel_connection_status: Collection of all tunnels' connection health status.
:vartype tunnel_connection_status:
list[~azure.mgmt.network.v2019_04_01.models.TunnelConnectionHealth]
:ivar egress_bytes_transferred: The egress bytes transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes transferred in this connection.
:vartype ingress_bytes_transferred: long
:param peer: The reference to peerings resource.
:type peer: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2019_04_01.models.IpsecPolicy]
:param resource_guid: The resource GUID property of the VirtualNetworkGatewayConnection
resource.
:type resource_guid: str
:ivar provisioning_state: The provisioning state of the VirtualNetworkGatewayConnection
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding.
:type express_route_gateway_bypass: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_network_gateway1': {'required': True},
'connection_type': {'required': True},
'connection_status': {'readonly': True},
'tunnel_connection_status': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkGateway'},
'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkGateway'},
'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'LocalNetworkGateway'},
'connection_type': {'key': 'properties.connectionType', 'type': 'str'},
'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'peer': {'key': 'properties.peer', 'type': 'SubResource'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnection, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.virtual_network_gateway1 = kwargs['virtual_network_gateway1']
self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None)
self.local_network_gateway2 = kwargs.get('local_network_gateway2', None)
self.connection_type = kwargs['connection_type']
self.connection_protocol = kwargs.get('connection_protocol', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.shared_key = kwargs.get('shared_key', None)
self.connection_status = None
self.tunnel_connection_status = None
self.egress_bytes_transferred = None
self.ingress_bytes_transferred = None
self.peer = kwargs.get('peer', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = None
self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None)
class VirtualNetworkGatewayConnectionListEntity(Resource):
"""A common class for general resource information.
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: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param authorization_key: The authorizationKey.
:type authorization_key: str
:param virtual_network_gateway1: Required. The reference to virtual network gateway resource.
:type virtual_network_gateway1:
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkConnectionGatewayReference
:param virtual_network_gateway2: The reference to virtual network gateway resource.
:type virtual_network_gateway2:
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkConnectionGatewayReference
:param local_network_gateway2: The reference to local network gateway resource.
:type local_network_gateway2:
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkConnectionGatewayReference
:param connection_type: Required. Gateway connection type. Possible values include: "IPsec",
"Vnet2Vnet", "ExpressRoute", "VPNClient".
:type connection_type: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionType
:param connection_protocol: Connection protocol used for this connection. Possible values
include: "IKEv2", "IKEv1".
:type connection_protocol: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionProtocol
:param routing_weight: The routing weight.
:type routing_weight: int
:param shared_key: The IPSec shared key.
:type shared_key: str
:ivar connection_status: Virtual Network Gateway connection status. Possible values include:
"Unknown", "Connecting", "Connected", "NotConnected".
:vartype connection_status: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionStatus
:ivar tunnel_connection_status: Collection of all tunnels' connection health status.
:vartype tunnel_connection_status:
list[~azure.mgmt.network.v2019_04_01.models.TunnelConnectionHealth]
:ivar egress_bytes_transferred: The egress bytes transferred in this connection.
:vartype egress_bytes_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes transferred in this connection.
:vartype ingress_bytes_transferred: long
:param peer: The reference to peerings resource.
:type peer: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2019_04_01.models.IpsecPolicy]
:param resource_guid: The resource GUID property of the VirtualNetworkGatewayConnection
resource.
:type resource_guid: str
:ivar provisioning_state: The provisioning state of the VirtualNetworkGatewayConnection
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param express_route_gateway_bypass: Bypass ExpressRoute Gateway for data forwarding.
:type express_route_gateway_bypass: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_network_gateway1': {'required': True},
'connection_type': {'required': True},
'connection_status': {'readonly': True},
'tunnel_connection_status': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'authorization_key': {'key': 'properties.authorizationKey', 'type': 'str'},
'virtual_network_gateway1': {'key': 'properties.virtualNetworkGateway1', 'type': 'VirtualNetworkConnectionGatewayReference'},
'virtual_network_gateway2': {'key': 'properties.virtualNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'local_network_gateway2': {'key': 'properties.localNetworkGateway2', 'type': 'VirtualNetworkConnectionGatewayReference'},
'connection_type': {'key': 'properties.connectionType', 'type': 'str'},
'connection_protocol': {'key': 'properties.connectionProtocol', 'type': 'str'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'tunnel_connection_status': {'key': 'properties.tunnelConnectionStatus', 'type': '[TunnelConnectionHealth]'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'peer': {'key': 'properties.peer', 'type': 'SubResource'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'express_route_gateway_bypass': {'key': 'properties.expressRouteGatewayBypass', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnectionListEntity, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.authorization_key = kwargs.get('authorization_key', None)
self.virtual_network_gateway1 = kwargs['virtual_network_gateway1']
self.virtual_network_gateway2 = kwargs.get('virtual_network_gateway2', None)
self.local_network_gateway2 = kwargs.get('local_network_gateway2', None)
self.connection_type = kwargs['connection_type']
self.connection_protocol = kwargs.get('connection_protocol', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.shared_key = kwargs.get('shared_key', None)
self.connection_status = None
self.tunnel_connection_status = None
self.egress_bytes_transferred = None
self.ingress_bytes_transferred = None
self.peer = kwargs.get('peer', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.resource_guid = kwargs.get('resource_guid', None)
self.provisioning_state = None
self.express_route_gateway_bypass = kwargs.get('express_route_gateway_bypass', None)
class VirtualNetworkGatewayConnectionListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworkGatewayConnections API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Gets a list of VirtualNetworkGatewayConnection resources that exists in a
resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnection]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGatewayConnection]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayConnectionListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewayIPConfiguration(SubResource):
"""IP configuration for virtual network gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param private_ip_allocation_method: The private IP address allocation method. Possible values
include: "Static", "Dynamic".
:type private_ip_allocation_method: str or
~azure.mgmt.network.v2019_04_01.models.IPAllocationMethod
:param subnet: The reference of the subnet resource.
:type subnet: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param public_ip_address: The reference of the public IP resource.
:type public_ip_address: ~azure.mgmt.network.v2019_04_01.models.SubResource
:ivar provisioning_state: The provisioning state of the public IP resource. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'private_ip_allocation_method': {'key': 'properties.privateIPAllocationMethod', 'type': 'str'},
'subnet': {'key': 'properties.subnet', 'type': 'SubResource'},
'public_ip_address': {'key': 'properties.publicIPAddress', 'type': 'SubResource'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayIPConfiguration, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.private_ip_allocation_method = kwargs.get('private_ip_allocation_method', None)
self.subnet = kwargs.get('subnet', None)
self.public_ip_address = kwargs.get('public_ip_address', None)
self.provisioning_state = None
class VirtualNetworkGatewayListConnectionsResult(msrest.serialization.Model):
"""Response for the VirtualNetworkGatewayListConnections API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Gets a list of VirtualNetworkGatewayConnection resources that exists in a
resource group.
:type value:
list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionListEntity]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGatewayConnectionListEntity]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayListConnectionsResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewayListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworkGateways API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: Gets a list of VirtualNetworkGateway resources that exists in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGateway]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkGateway]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewayListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = None
class VirtualNetworkGatewaySku(msrest.serialization.Model):
"""VirtualNetworkGatewaySku details.
:param name: Gateway SKU name. Possible values include: "Basic", "HighPerformance", "Standard",
"UltraPerformance", "VpnGw1", "VpnGw2", "VpnGw3", "VpnGw1AZ", "VpnGw2AZ", "VpnGw3AZ",
"ErGw1AZ", "ErGw2AZ", "ErGw3AZ".
:type name: str or ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewaySkuName
:param tier: Gateway SKU tier. Possible values include: "Basic", "HighPerformance", "Standard",
"UltraPerformance", "VpnGw1", "VpnGw2", "VpnGw3", "VpnGw1AZ", "VpnGw2AZ", "VpnGw3AZ",
"ErGw1AZ", "ErGw2AZ", "ErGw3AZ".
:type tier: str or ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewaySkuTier
:param capacity: The capacity.
:type capacity: int
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'tier': {'key': 'tier', 'type': 'str'},
'capacity': {'key': 'capacity', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkGatewaySku, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.tier = kwargs.get('tier', None)
self.capacity = kwargs.get('capacity', None)
class VirtualNetworkListResult(msrest.serialization.Model):
"""Response for the ListVirtualNetworks API service call.
:param value: Gets a list of VirtualNetwork resources in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetwork]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetwork]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkListUsageResult(msrest.serialization.Model):
"""Response for the virtual networks GetUsage API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: VirtualNetwork usage stats.
:vartype value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkUsage]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_validation = {
'value': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkUsage]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkListUsageResult, self).__init__(**kwargs)
self.value = None
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkPeering(SubResource):
"""Peerings in a virtual network resource.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param allow_virtual_network_access: Whether the VMs in the local virtual network space would
be able to access the VMs in remote virtual network space.
:type allow_virtual_network_access: bool
:param allow_forwarded_traffic: Whether the forwarded traffic from the VMs in the local virtual
network will be allowed/disallowed in remote virtual network.
:type allow_forwarded_traffic: bool
:param allow_gateway_transit: If gateway links can be used in remote virtual networking to link
to this virtual network.
:type allow_gateway_transit: bool
:param use_remote_gateways: If remote gateways can be used on this virtual network. If the flag
is set to true, and allowGatewayTransit on remote peering is also true, virtual network will
use gateways of remote virtual network for transit. Only one peering can have this flag set to
true. This flag cannot be set if virtual network already has a gateway.
:type use_remote_gateways: bool
:param remote_virtual_network: The reference of the remote virtual network. The remote virtual
network can be in the same or different region (preview). See here to register for the preview
and learn more
(https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering).
:type remote_virtual_network: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param remote_address_space: The reference of the remote virtual network address space.
:type remote_address_space: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param peering_state: The status of the virtual network peering. Possible values include:
"Initiated", "Connected", "Disconnected".
:type peering_state: str or ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkPeeringState
:param provisioning_state: The provisioning state of the resource.
:type provisioning_state: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'},
'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'},
'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'},
'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'},
'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'},
'remote_address_space': {'key': 'properties.remoteAddressSpace', 'type': 'AddressSpace'},
'peering_state': {'key': 'properties.peeringState', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkPeering, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.allow_virtual_network_access = kwargs.get('allow_virtual_network_access', None)
self.allow_forwarded_traffic = kwargs.get('allow_forwarded_traffic', None)
self.allow_gateway_transit = kwargs.get('allow_gateway_transit', None)
self.use_remote_gateways = kwargs.get('use_remote_gateways', None)
self.remote_virtual_network = kwargs.get('remote_virtual_network', None)
self.remote_address_space = kwargs.get('remote_address_space', None)
self.peering_state = kwargs.get('peering_state', None)
self.provisioning_state = kwargs.get('provisioning_state', None)
class VirtualNetworkPeeringListResult(msrest.serialization.Model):
"""Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual network.
:param value: The peerings in a virtual network.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkPeering]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkPeering]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkPeeringListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkTap(Resource):
"""Virtual Network Tap resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:ivar network_interface_tap_configurations: Specifies the list of resource IDs for the network
interface IP configuration that needs to be tapped.
:vartype network_interface_tap_configurations:
list[~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceTapConfiguration]
:ivar resource_guid: The resourceGuid property of the virtual network tap.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the virtual network tap. Possible values
are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
:param destination_network_interface_ip_configuration: The reference to the private IP Address
of the collector nic that will receive the tap.
:type destination_network_interface_ip_configuration:
~azure.mgmt.network.v2019_04_01.models.NetworkInterfaceIPConfiguration
:param destination_load_balancer_front_end_ip_configuration: The reference to the private IP
address on the internal Load Balancer that will receive the tap.
:type destination_load_balancer_front_end_ip_configuration:
~azure.mgmt.network.v2019_04_01.models.FrontendIPConfiguration
:param destination_port: The VXLAN destination port that will receive the tapped traffic.
:type destination_port: int
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'network_interface_tap_configurations': {'readonly': True},
'resource_guid': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'network_interface_tap_configurations': {'key': 'properties.networkInterfaceTapConfigurations', 'type': '[NetworkInterfaceTapConfiguration]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'destination_network_interface_ip_configuration': {'key': 'properties.destinationNetworkInterfaceIPConfiguration', 'type': 'NetworkInterfaceIPConfiguration'},
'destination_load_balancer_front_end_ip_configuration': {'key': 'properties.destinationLoadBalancerFrontEndIPConfiguration', 'type': 'FrontendIPConfiguration'},
'destination_port': {'key': 'properties.destinationPort', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkTap, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.network_interface_tap_configurations = None
self.resource_guid = None
self.provisioning_state = None
self.destination_network_interface_ip_configuration = kwargs.get('destination_network_interface_ip_configuration', None)
self.destination_load_balancer_front_end_ip_configuration = kwargs.get('destination_load_balancer_front_end_ip_configuration', None)
self.destination_port = kwargs.get('destination_port', None)
class VirtualNetworkTapListResult(msrest.serialization.Model):
"""Response for ListVirtualNetworkTap API service call.
:param value: A list of VirtualNetworkTaps in a resource group.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VirtualNetworkTap]
:param next_link: The URL to get the next set of results.
:type next_link: str
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VirtualNetworkTap]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkTapListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
self.next_link = kwargs.get('next_link', None)
class VirtualNetworkUsage(msrest.serialization.Model):
"""Usage details for subnet.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar current_value: Indicates number of IPs used from the Subnet.
:vartype current_value: float
:ivar id: Subnet identifier.
:vartype id: str
:ivar limit: Indicates the size of the subnet.
:vartype limit: float
:ivar name: The name containing common and localized value for usage.
:vartype name: ~azure.mgmt.network.v2019_04_01.models.VirtualNetworkUsageName
:ivar unit: Usage units. Returns 'Count'.
:vartype unit: str
"""
_validation = {
'current_value': {'readonly': True},
'id': {'readonly': True},
'limit': {'readonly': True},
'name': {'readonly': True},
'unit': {'readonly': True},
}
_attribute_map = {
'current_value': {'key': 'currentValue', 'type': 'float'},
'id': {'key': 'id', 'type': 'str'},
'limit': {'key': 'limit', 'type': 'float'},
'name': {'key': 'name', 'type': 'VirtualNetworkUsageName'},
'unit': {'key': 'unit', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkUsage, self).__init__(**kwargs)
self.current_value = None
self.id = None
self.limit = None
self.name = None
self.unit = None
class VirtualNetworkUsageName(msrest.serialization.Model):
"""Usage strings container.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar localized_value: Localized subnet size and usage string.
:vartype localized_value: str
:ivar value: Subnet size and usage string.
:vartype value: str
"""
_validation = {
'localized_value': {'readonly': True},
'value': {'readonly': True},
}
_attribute_map = {
'localized_value': {'key': 'localizedValue', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualNetworkUsageName, self).__init__(**kwargs)
self.localized_value = None
self.value = None
class VirtualWAN(Resource):
"""VirtualWAN Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param disable_vpn_encryption: Vpn encryption to be disabled or not.
:type disable_vpn_encryption: bool
:ivar virtual_hubs: List of VirtualHubs in the VirtualWAN.
:vartype virtual_hubs: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:ivar vpn_sites: List of VpnSites in the VirtualWAN.
:vartype vpn_sites: list[~azure.mgmt.network.v2019_04_01.models.SubResource]
:param security_provider_name: The Security Provider name.
:type security_provider_name: str
:param allow_branch_to_branch_traffic: True if branch to branch traffic is allowed.
:type allow_branch_to_branch_traffic: bool
:param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is allowed.
:type allow_vnet_to_vnet_traffic: bool
:ivar office365_local_breakout_category: The office local breakout category. Possible values
include: "Optimize", "OptimizeAndAllow", "All", "None".
:vartype office365_local_breakout_category: str or
~azure.mgmt.network.v2019_04_01.models.OfficeTrafficCategory
:param p2_s_vpn_server_configurations: List of all P2SVpnServerConfigurations associated with
the virtual wan.
:type p2_s_vpn_server_configurations:
list[~azure.mgmt.network.v2019_04_01.models.P2SVpnServerConfiguration]
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'virtual_hubs': {'readonly': True},
'vpn_sites': {'readonly': True},
'office365_local_breakout_category': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'},
'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'},
'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'},
'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'},
'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'},
'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'},
'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'},
'p2_s_vpn_server_configurations': {'key': 'properties.p2SVpnServerConfigurations', 'type': '[P2SVpnServerConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualWAN, self).__init__(**kwargs)
self.etag = None
self.disable_vpn_encryption = kwargs.get('disable_vpn_encryption', None)
self.virtual_hubs = None
self.vpn_sites = None
self.security_provider_name = kwargs.get('security_provider_name', None)
self.allow_branch_to_branch_traffic = kwargs.get('allow_branch_to_branch_traffic', None)
self.allow_vnet_to_vnet_traffic = kwargs.get('allow_vnet_to_vnet_traffic', None)
self.office365_local_breakout_category = None
self.p2_s_vpn_server_configurations = kwargs.get('p2_s_vpn_server_configurations', None)
self.provisioning_state = None
class VirtualWanSecurityProvider(msrest.serialization.Model):
"""Collection of SecurityProviders.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Name of the security provider.
:type name: str
:param url: Url of the security provider.
:type url: str
:ivar type: Name of the security provider. Possible values include: "External", "Native".
:vartype type: str or ~azure.mgmt.network.v2019_04_01.models.VirtualWanSecurityProviderType
"""
_validation = {
'type': {'readonly': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VirtualWanSecurityProvider, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.url = kwargs.get('url', None)
self.type = None
class VirtualWanSecurityProviders(msrest.serialization.Model):
"""Collection of SecurityProviders.
:param supported_providers: List of VirtualWAN security providers.
:type supported_providers:
list[~azure.mgmt.network.v2019_04_01.models.VirtualWanSecurityProvider]
"""
_attribute_map = {
'supported_providers': {'key': 'supportedProviders', 'type': '[VirtualWanSecurityProvider]'},
}
def __init__(
self,
**kwargs
):
super(VirtualWanSecurityProviders, self).__init__(**kwargs)
self.supported_providers = kwargs.get('supported_providers', None)
class VpnClientConfiguration(msrest.serialization.Model):
"""VpnClientConfiguration for P2S client.
:param vpn_client_address_pool: The reference of the address space resource which represents
Address space for P2S VpnClient.
:type vpn_client_address_pool: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param vpn_client_root_certificates: VpnClientRootCertificate for virtual network gateway.
:type vpn_client_root_certificates:
list[~azure.mgmt.network.v2019_04_01.models.VpnClientRootCertificate]
:param vpn_client_revoked_certificates: VpnClientRevokedCertificate for Virtual network
gateway.
:type vpn_client_revoked_certificates:
list[~azure.mgmt.network.v2019_04_01.models.VpnClientRevokedCertificate]
:param vpn_client_protocols: VpnClientProtocols for Virtual network gateway.
:type vpn_client_protocols: list[str or
~azure.mgmt.network.v2019_04_01.models.VpnClientProtocol]
:param vpn_client_ipsec_policies: VpnClientIpsecPolicies for virtual network gateway P2S
client.
:type vpn_client_ipsec_policies: list[~azure.mgmt.network.v2019_04_01.models.IpsecPolicy]
:param radius_server_address: The radius server address property of the VirtualNetworkGateway
resource for vpn client connection.
:type radius_server_address: str
:param radius_server_secret: The radius secret property of the VirtualNetworkGateway resource
for vpn client connection.
:type radius_server_secret: str
:param aad_tenant: The AADTenant property of the VirtualNetworkGateway resource for vpn client
connection used for AAD authentication.
:type aad_tenant: str
:param aad_audience: The AADAudience property of the VirtualNetworkGateway resource for vpn
client connection used for AAD authentication.
:type aad_audience: str
:param aad_issuer: The AADIssuer property of the VirtualNetworkGateway resource for vpn client
connection used for AAD authentication.
:type aad_issuer: str
"""
_attribute_map = {
'vpn_client_address_pool': {'key': 'vpnClientAddressPool', 'type': 'AddressSpace'},
'vpn_client_root_certificates': {'key': 'vpnClientRootCertificates', 'type': '[VpnClientRootCertificate]'},
'vpn_client_revoked_certificates': {'key': 'vpnClientRevokedCertificates', 'type': '[VpnClientRevokedCertificate]'},
'vpn_client_protocols': {'key': 'vpnClientProtocols', 'type': '[str]'},
'vpn_client_ipsec_policies': {'key': 'vpnClientIpsecPolicies', 'type': '[IpsecPolicy]'},
'radius_server_address': {'key': 'radiusServerAddress', 'type': 'str'},
'radius_server_secret': {'key': 'radiusServerSecret', 'type': 'str'},
'aad_tenant': {'key': 'aadTenant', 'type': 'str'},
'aad_audience': {'key': 'aadAudience', 'type': 'str'},
'aad_issuer': {'key': 'aadIssuer', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConfiguration, self).__init__(**kwargs)
self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None)
self.vpn_client_root_certificates = kwargs.get('vpn_client_root_certificates', None)
self.vpn_client_revoked_certificates = kwargs.get('vpn_client_revoked_certificates', None)
self.vpn_client_protocols = kwargs.get('vpn_client_protocols', None)
self.vpn_client_ipsec_policies = kwargs.get('vpn_client_ipsec_policies', None)
self.radius_server_address = kwargs.get('radius_server_address', None)
self.radius_server_secret = kwargs.get('radius_server_secret', None)
self.aad_tenant = kwargs.get('aad_tenant', None)
self.aad_audience = kwargs.get('aad_audience', None)
self.aad_issuer = kwargs.get('aad_issuer', None)
class VpnClientConnectionHealth(msrest.serialization.Model):
"""VpnClientConnectionHealth properties.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar total_ingress_bytes_transferred: Total of the Ingress Bytes Transferred in this P2S Vpn
connection.
:vartype total_ingress_bytes_transferred: long
:ivar total_egress_bytes_transferred: Total of the Egress Bytes Transferred in this connection.
:vartype total_egress_bytes_transferred: long
:param vpn_client_connections_count: The total of p2s vpn clients connected at this time to
this P2SVpnGateway.
:type vpn_client_connections_count: int
:param allocated_ip_addresses: List of allocated ip addresses to the connected p2s vpn clients.
:type allocated_ip_addresses: list[str]
"""
_validation = {
'total_ingress_bytes_transferred': {'readonly': True},
'total_egress_bytes_transferred': {'readonly': True},
}
_attribute_map = {
'total_ingress_bytes_transferred': {'key': 'totalIngressBytesTransferred', 'type': 'long'},
'total_egress_bytes_transferred': {'key': 'totalEgressBytesTransferred', 'type': 'long'},
'vpn_client_connections_count': {'key': 'vpnClientConnectionsCount', 'type': 'int'},
'allocated_ip_addresses': {'key': 'allocatedIpAddresses', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealth, self).__init__(**kwargs)
self.total_ingress_bytes_transferred = None
self.total_egress_bytes_transferred = None
self.vpn_client_connections_count = kwargs.get('vpn_client_connections_count', None)
self.allocated_ip_addresses = kwargs.get('allocated_ip_addresses', None)
class VpnClientConnectionHealthDetail(msrest.serialization.Model):
"""VPN client connection health detail.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar vpn_connection_id: The vpn client Id.
:vartype vpn_connection_id: str
:ivar vpn_connection_duration: The duration time of a connected vpn client.
:vartype vpn_connection_duration: long
:ivar vpn_connection_time: The start time of a connected vpn client.
:vartype vpn_connection_time: str
:ivar public_ip_address: The public Ip of a connected vpn client.
:vartype public_ip_address: str
:ivar private_ip_address: The assigned private Ip of a connected vpn client.
:vartype private_ip_address: str
:ivar vpn_user_name: The user name of a connected vpn client.
:vartype vpn_user_name: str
:ivar max_bandwidth: The max band width.
:vartype max_bandwidth: long
:ivar egress_packets_transferred: The egress packets per second.
:vartype egress_packets_transferred: long
:ivar egress_bytes_transferred: The egress bytes per second.
:vartype egress_bytes_transferred: long
:ivar ingress_packets_transferred: The ingress packets per second.
:vartype ingress_packets_transferred: long
:ivar ingress_bytes_transferred: The ingress bytes per second.
:vartype ingress_bytes_transferred: long
:ivar max_packets_per_second: The max packets transferred per second.
:vartype max_packets_per_second: long
"""
_validation = {
'vpn_connection_id': {'readonly': True},
'vpn_connection_duration': {'readonly': True},
'vpn_connection_time': {'readonly': True},
'public_ip_address': {'readonly': True},
'private_ip_address': {'readonly': True},
'vpn_user_name': {'readonly': True},
'max_bandwidth': {'readonly': True},
'egress_packets_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'ingress_packets_transferred': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'max_packets_per_second': {'readonly': True},
}
_attribute_map = {
'vpn_connection_id': {'key': 'vpnConnectionId', 'type': 'str'},
'vpn_connection_duration': {'key': 'vpnConnectionDuration', 'type': 'long'},
'vpn_connection_time': {'key': 'vpnConnectionTime', 'type': 'str'},
'public_ip_address': {'key': 'publicIpAddress', 'type': 'str'},
'private_ip_address': {'key': 'privateIpAddress', 'type': 'str'},
'vpn_user_name': {'key': 'vpnUserName', 'type': 'str'},
'max_bandwidth': {'key': 'maxBandwidth', 'type': 'long'},
'egress_packets_transferred': {'key': 'egressPacketsTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'egressBytesTransferred', 'type': 'long'},
'ingress_packets_transferred': {'key': 'ingressPacketsTransferred', 'type': 'long'},
'ingress_bytes_transferred': {'key': 'ingressBytesTransferred', 'type': 'long'},
'max_packets_per_second': {'key': 'maxPacketsPerSecond', 'type': 'long'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealthDetail, self).__init__(**kwargs)
self.vpn_connection_id = None
self.vpn_connection_duration = None
self.vpn_connection_time = None
self.public_ip_address = None
self.private_ip_address = None
self.vpn_user_name = None
self.max_bandwidth = None
self.egress_packets_transferred = None
self.egress_bytes_transferred = None
self.ingress_packets_transferred = None
self.ingress_bytes_transferred = None
self.max_packets_per_second = None
class VpnClientConnectionHealthDetailListResult(msrest.serialization.Model):
"""List of virtual network gateway vpn client connection health.
:param value: List of vpn client connection health.
:type value: list[~azure.mgmt.network.v2019_04_01.models.VpnClientConnectionHealthDetail]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[VpnClientConnectionHealthDetail]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientConnectionHealthDetailListResult, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class VpnClientIPsecParameters(msrest.serialization.Model):
"""An IPSec parameters for a virtual network gateway P2S connection.
All required parameters must be populated in order to send to Azure.
:param sa_life_time_seconds: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) lifetime in seconds for P2S client.
:type sa_life_time_seconds: int
:param sa_data_size_kilobytes: Required. The IPSec Security Association (also called Quick Mode
or Phase 2 SA) payload size in KB for P2S client..
:type sa_data_size_kilobytes: int
:param ipsec_encryption: Required. The IPSec encryption algorithm (IKE phase 1). Possible
values include: "None", "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES128", "GCMAES192",
"GCMAES256".
:type ipsec_encryption: str or ~azure.mgmt.network.v2019_04_01.models.IpsecEncryption
:param ipsec_integrity: Required. The IPSec integrity algorithm (IKE phase 1). Possible values
include: "MD5", "SHA1", "SHA256", "GCMAES128", "GCMAES192", "GCMAES256".
:type ipsec_integrity: str or ~azure.mgmt.network.v2019_04_01.models.IpsecIntegrity
:param ike_encryption: Required. The IKE encryption algorithm (IKE phase 2). Possible values
include: "DES", "DES3", "AES128", "AES192", "AES256", "GCMAES256", "GCMAES128".
:type ike_encryption: str or ~azure.mgmt.network.v2019_04_01.models.IkeEncryption
:param ike_integrity: Required. The IKE integrity algorithm (IKE phase 2). Possible values
include: "MD5", "SHA1", "SHA256", "SHA384", "GCMAES256", "GCMAES128".
:type ike_integrity: str or ~azure.mgmt.network.v2019_04_01.models.IkeIntegrity
:param dh_group: Required. The DH Group used in IKE Phase 1 for initial SA. Possible values
include: "None", "DHGroup1", "DHGroup2", "DHGroup14", "DHGroup2048", "ECP256", "ECP384",
"DHGroup24".
:type dh_group: str or ~azure.mgmt.network.v2019_04_01.models.DhGroup
:param pfs_group: Required. The Pfs Group used in IKE Phase 2 for new child SA. Possible values
include: "None", "PFS1", "PFS2", "PFS2048", "ECP256", "ECP384", "PFS24", "PFS14", "PFSMM".
:type pfs_group: str or ~azure.mgmt.network.v2019_04_01.models.PfsGroup
"""
_validation = {
'sa_life_time_seconds': {'required': True},
'sa_data_size_kilobytes': {'required': True},
'ipsec_encryption': {'required': True},
'ipsec_integrity': {'required': True},
'ike_encryption': {'required': True},
'ike_integrity': {'required': True},
'dh_group': {'required': True},
'pfs_group': {'required': True},
}
_attribute_map = {
'sa_life_time_seconds': {'key': 'saLifeTimeSeconds', 'type': 'int'},
'sa_data_size_kilobytes': {'key': 'saDataSizeKilobytes', 'type': 'int'},
'ipsec_encryption': {'key': 'ipsecEncryption', 'type': 'str'},
'ipsec_integrity': {'key': 'ipsecIntegrity', 'type': 'str'},
'ike_encryption': {'key': 'ikeEncryption', 'type': 'str'},
'ike_integrity': {'key': 'ikeIntegrity', 'type': 'str'},
'dh_group': {'key': 'dhGroup', 'type': 'str'},
'pfs_group': {'key': 'pfsGroup', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientIPsecParameters, self).__init__(**kwargs)
self.sa_life_time_seconds = kwargs['sa_life_time_seconds']
self.sa_data_size_kilobytes = kwargs['sa_data_size_kilobytes']
self.ipsec_encryption = kwargs['ipsec_encryption']
self.ipsec_integrity = kwargs['ipsec_integrity']
self.ike_encryption = kwargs['ike_encryption']
self.ike_integrity = kwargs['ike_integrity']
self.dh_group = kwargs['dh_group']
self.pfs_group = kwargs['pfs_group']
class VpnClientParameters(msrest.serialization.Model):
"""Vpn Client Parameters for package generation.
:param processor_architecture: VPN client Processor Architecture. Possible values include:
"Amd64", "X86".
:type processor_architecture: str or
~azure.mgmt.network.v2019_04_01.models.ProcessorArchitecture
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2019_04_01.models.AuthenticationMethod
:param radius_server_auth_certificate: The public certificate data for the radius server
authentication certificate as a Base-64 encoded string. Required only if external radius
authentication has been configured with EAPTLS authentication.
:type radius_server_auth_certificate: str
:param client_root_certificates: A list of client root certificates public certificate data
encoded as Base-64 strings. Optional parameter for external radius based authentication with
EAPTLS.
:type client_root_certificates: list[str]
"""
_attribute_map = {
'processor_architecture': {'key': 'processorArchitecture', 'type': 'str'},
'authentication_method': {'key': 'authenticationMethod', 'type': 'str'},
'radius_server_auth_certificate': {'key': 'radiusServerAuthCertificate', 'type': 'str'},
'client_root_certificates': {'key': 'clientRootCertificates', 'type': '[str]'},
}
def __init__(
self,
**kwargs
):
super(VpnClientParameters, self).__init__(**kwargs)
self.processor_architecture = kwargs.get('processor_architecture', None)
self.authentication_method = kwargs.get('authentication_method', None)
self.radius_server_auth_certificate = kwargs.get('radius_server_auth_certificate', None)
self.client_root_certificates = kwargs.get('client_root_certificates', None)
class VpnClientRevokedCertificate(SubResource):
"""VPN client revoked certificate of virtual network gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param thumbprint: The revoked VPN client certificate thumbprint.
:type thumbprint: str
:ivar provisioning_state: The provisioning state of the VPN client revoked certificate
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'thumbprint': {'key': 'properties.thumbprint', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientRevokedCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.thumbprint = kwargs.get('thumbprint', None)
self.provisioning_state = None
class VpnClientRootCertificate(SubResource):
"""VPN client root certificate of virtual network gateway.
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: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource is updated.
:type etag: str
:param public_cert_data: Required. The certificate public data.
:type public_cert_data: str
:ivar provisioning_state: The provisioning state of the VPN client root certificate resource.
Possible values are: 'Updating', 'Deleting', and 'Failed'.
:vartype provisioning_state: str
"""
_validation = {
'public_cert_data': {'required': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'public_cert_data': {'key': 'properties.publicCertData', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnClientRootCertificate, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = kwargs.get('etag', None)
self.public_cert_data = kwargs['public_cert_data']
self.provisioning_state = None
class VpnConnection(SubResource):
"""VpnConnection Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource that is unique within a resource group. This name can be
used to access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param remote_vpn_site: Id of the connected vpn site.
:type remote_vpn_site: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param routing_weight: Routing weight for vpn connection.
:type routing_weight: int
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connecting", "Connected", "NotConnected".
:vartype connection_status: str or ~azure.mgmt.network.v2019_04_01.models.VpnConnectionStatus
:param vpn_connection_protocol_type: Connection protocol used for this connection. Possible
values include: "IKEv2", "IKEv1".
:type vpn_connection_protocol_type: str or
~azure.mgmt.network.v2019_04_01.models.VirtualNetworkGatewayConnectionProtocol
:ivar ingress_bytes_transferred: Ingress bytes transferred.
:vartype ingress_bytes_transferred: long
:ivar egress_bytes_transferred: Egress bytes transferred.
:vartype egress_bytes_transferred: long
:param connection_bandwidth: Expected bandwidth in MBPS.
:type connection_bandwidth: int
:param shared_key: SharedKey for the vpn connection.
:type shared_key: str
:param enable_bgp: EnableBgp flag.
:type enable_bgp: bool
:param use_policy_based_traffic_selectors: Enable policy-based traffic selectors.
:type use_policy_based_traffic_selectors: bool
:param ipsec_policies: The IPSec Policies to be considered by this connection.
:type ipsec_policies: list[~azure.mgmt.network.v2019_04_01.models.IpsecPolicy]
:param enable_rate_limiting: EnableBgp flag.
:type enable_rate_limiting: bool
:param enable_internet_security: Enable internet security.
:type enable_internet_security: bool
:param use_local_azure_ip_address: Use local azure ip to initiate connection.
:type use_local_azure_ip_address: bool
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
"""
_validation = {
'etag': {'readonly': True},
'connection_status': {'readonly': True},
'ingress_bytes_transferred': {'readonly': True},
'egress_bytes_transferred': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'remote_vpn_site': {'key': 'properties.remoteVpnSite', 'type': 'SubResource'},
'routing_weight': {'key': 'properties.routingWeight', 'type': 'int'},
'connection_status': {'key': 'properties.connectionStatus', 'type': 'str'},
'vpn_connection_protocol_type': {'key': 'properties.vpnConnectionProtocolType', 'type': 'str'},
'ingress_bytes_transferred': {'key': 'properties.ingressBytesTransferred', 'type': 'long'},
'egress_bytes_transferred': {'key': 'properties.egressBytesTransferred', 'type': 'long'},
'connection_bandwidth': {'key': 'properties.connectionBandwidth', 'type': 'int'},
'shared_key': {'key': 'properties.sharedKey', 'type': 'str'},
'enable_bgp': {'key': 'properties.enableBgp', 'type': 'bool'},
'use_policy_based_traffic_selectors': {'key': 'properties.usePolicyBasedTrafficSelectors', 'type': 'bool'},
'ipsec_policies': {'key': 'properties.ipsecPolicies', 'type': '[IpsecPolicy]'},
'enable_rate_limiting': {'key': 'properties.enableRateLimiting', 'type': 'bool'},
'enable_internet_security': {'key': 'properties.enableInternetSecurity', 'type': 'bool'},
'use_local_azure_ip_address': {'key': 'properties.useLocalAzureIpAddress', 'type': 'bool'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnConnection, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.remote_vpn_site = kwargs.get('remote_vpn_site', None)
self.routing_weight = kwargs.get('routing_weight', None)
self.connection_status = None
self.vpn_connection_protocol_type = kwargs.get('vpn_connection_protocol_type', None)
self.ingress_bytes_transferred = None
self.egress_bytes_transferred = None
self.connection_bandwidth = kwargs.get('connection_bandwidth', None)
self.shared_key = kwargs.get('shared_key', None)
self.enable_bgp = kwargs.get('enable_bgp', None)
self.use_policy_based_traffic_selectors = kwargs.get('use_policy_based_traffic_selectors', None)
self.ipsec_policies = kwargs.get('ipsec_policies', None)
self.enable_rate_limiting = kwargs.get('enable_rate_limiting', None)
self.enable_internet_security = kwargs.get('enable_internet_security', None)
self.use_local_azure_ip_address = kwargs.get('use_local_azure_ip_address', None)
self.provisioning_state = None
class VpnDeviceScriptParameters(msrest.serialization.Model):
"""Vpn device configuration script generation parameters.
:param vendor: The vendor for the vpn device.
:type vendor: str
:param device_family: The device family for the vpn device.
:type device_family: str
:param firmware_version: The firmware version for the vpn device.
:type firmware_version: str
"""
_attribute_map = {
'vendor': {'key': 'vendor', 'type': 'str'},
'device_family': {'key': 'deviceFamily', 'type': 'str'},
'firmware_version': {'key': 'firmwareVersion', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnDeviceScriptParameters, self).__init__(**kwargs)
self.vendor = kwargs.get('vendor', None)
self.device_family = kwargs.get('device_family', None)
self.firmware_version = kwargs.get('firmware_version', None)
class VpnGateway(Resource):
"""VpnGateway Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_hub: The VirtualHub to which the gateway belongs.
:type virtual_hub: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param connections: List of all vpn connections to the gateway.
:type connections: list[~azure.mgmt.network.v2019_04_01.models.VpnConnection]
:param bgp_settings: Local network gateway's BGP speaker settings.
:type bgp_settings: ~azure.mgmt.network.v2019_04_01.models.BgpSettings
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param vpn_gateway_scale_unit: The scale unit for this vpn gateway.
:type vpn_gateway_scale_unit: int
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_hub': {'key': 'properties.virtualHub', 'type': 'SubResource'},
'connections': {'key': 'properties.connections', 'type': '[VpnConnection]'},
'bgp_settings': {'key': 'properties.bgpSettings', 'type': 'BgpSettings'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'vpn_gateway_scale_unit': {'key': 'properties.vpnGatewayScaleUnit', 'type': 'int'},
}
def __init__(
self,
**kwargs
):
super(VpnGateway, self).__init__(**kwargs)
self.etag = None
self.virtual_hub = kwargs.get('virtual_hub', None)
self.connections = kwargs.get('connections', None)
self.bgp_settings = kwargs.get('bgp_settings', None)
self.provisioning_state = None
self.vpn_gateway_scale_unit = kwargs.get('vpn_gateway_scale_unit', None)
class VpnProfileResponse(msrest.serialization.Model):
"""Vpn Profile Response for package generation.
:param profile_url: URL to the VPN profile.
:type profile_url: str
"""
_attribute_map = {
'profile_url': {'key': 'profileUrl', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnProfileResponse, self).__init__(**kwargs)
self.profile_url = kwargs.get('profile_url', None)
class VpnSite(Resource):
"""VpnSite Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param virtual_wan: The VirtualWAN to which the vpnSite belongs.
:type virtual_wan: ~azure.mgmt.network.v2019_04_01.models.SubResource
:param device_properties: The device properties.
:type device_properties: ~azure.mgmt.network.v2019_04_01.models.DeviceProperties
:param ip_address: The ip-address for the vpn-site.
:type ip_address: str
:param site_key: The key for vpn-site that can be used for connections.
:type site_key: str
:param address_space: The AddressSpace that contains an array of IP address ranges.
:type address_space: ~azure.mgmt.network.v2019_04_01.models.AddressSpace
:param bgp_properties: The set of bgp properties.
:type bgp_properties: ~azure.mgmt.network.v2019_04_01.models.BgpSettings
:ivar provisioning_state: The provisioning state of the resource. Possible values include:
"Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState
:param is_security_site: IsSecuritySite flag.
:type is_security_site: bool
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'etag': {'readonly': True},
'provisioning_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'virtual_wan': {'key': 'properties.virtualWan', 'type': 'SubResource'},
'device_properties': {'key': 'properties.deviceProperties', 'type': 'DeviceProperties'},
'ip_address': {'key': 'properties.ipAddress', 'type': 'str'},
'site_key': {'key': 'properties.siteKey', 'type': 'str'},
'address_space': {'key': 'properties.addressSpace', 'type': 'AddressSpace'},
'bgp_properties': {'key': 'properties.bgpProperties', 'type': 'BgpSettings'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'is_security_site': {'key': 'properties.isSecuritySite', 'type': 'bool'},
}
def __init__(
self,
**kwargs
):
super(VpnSite, self).__init__(**kwargs)
self.etag = None
self.virtual_wan = kwargs.get('virtual_wan', None)
self.device_properties = kwargs.get('device_properties', None)
self.ip_address = kwargs.get('ip_address', None)
self.site_key = kwargs.get('site_key', None)
self.address_space = kwargs.get('address_space', None)
self.bgp_properties = kwargs.get('bgp_properties', None)
self.provisioning_state = None
self.is_security_site = kwargs.get('is_security_site', None)
class VpnSiteId(msrest.serialization.Model):
"""VpnSite Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar vpn_site: The resource-uri of the vpn-site for which config is to be fetched.
:vartype vpn_site: str
"""
_validation = {
'vpn_site': {'readonly': True},
}
_attribute_map = {
'vpn_site': {'key': 'vpnSite', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(VpnSiteId, self).__init__(**kwargs)
self.vpn_site = None
class WebApplicationFirewallCustomRule(msrest.serialization.Model):
"""Defines contents of a web application rule.
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 name: Gets name of the resource that is unique within a policy. This name can be used to
access the resource.
:type name: str
:ivar etag: Gets a unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param priority: Required. Describes priority of the rule. Rules with a lower value will be
evaluated before rules with a higher value.
:type priority: int
:param rule_type: Required. Describes type of rule. Possible values include: "MatchRule",
"Invalid".
:type rule_type: str or ~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallRuleType
:param match_conditions: Required. List of match conditions.
:type match_conditions: list[~azure.mgmt.network.v2019_04_01.models.MatchCondition]
:param action: Required. Type of Actions. Possible values include: "Allow", "Block", "Log".
:type action: str or ~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallAction
"""
_validation = {
'name': {'max_length': 128, 'min_length': 0},
'etag': {'readonly': True},
'priority': {'required': True},
'rule_type': {'required': True},
'match_conditions': {'required': True},
'action': {'required': True},
}
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'priority': {'key': 'priority', 'type': 'int'},
'rule_type': {'key': 'ruleType', 'type': 'str'},
'match_conditions': {'key': 'matchConditions', 'type': '[MatchCondition]'},
'action': {'key': 'action', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallCustomRule, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.etag = None
self.priority = kwargs['priority']
self.rule_type = kwargs['rule_type']
self.match_conditions = kwargs['match_conditions']
self.action = kwargs['action']
class WebApplicationFirewallPolicy(Resource):
"""Defines web application firewall policy.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param etag: Gets a unique read-only string that changes whenever the resource is updated.
:type etag: str
:param policy_settings: Describes policySettings for policy.
:type policy_settings: ~azure.mgmt.network.v2019_04_01.models.PolicySettings
:param custom_rules: Describes custom rules inside the policy.
:type custom_rules:
list[~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallCustomRule]
:ivar application_gateways: A collection of references to application gateways.
:vartype application_gateways: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGateway]
:ivar provisioning_state: Provisioning state of the WebApplicationFirewallPolicy.
:vartype provisioning_state: str
:ivar resource_state: Resource status of the policy. Possible values include: "Creating",
"Enabling", "Enabled", "Disabling", "Disabled", "Deleting".
:vartype resource_state: str or
~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallPolicyResourceState
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'application_gateways': {'readonly': True},
'provisioning_state': {'readonly': True},
'resource_state': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'etag': {'key': 'etag', 'type': 'str'},
'policy_settings': {'key': 'properties.policySettings', 'type': 'PolicySettings'},
'custom_rules': {'key': 'properties.customRules', 'type': '[WebApplicationFirewallCustomRule]'},
'application_gateways': {'key': 'properties.applicationGateways', 'type': '[ApplicationGateway]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'resource_state': {'key': 'properties.resourceState', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallPolicy, self).__init__(**kwargs)
self.etag = kwargs.get('etag', None)
self.policy_settings = kwargs.get('policy_settings', None)
self.custom_rules = kwargs.get('custom_rules', None)
self.application_gateways = None
self.provisioning_state = None
self.resource_state = None
class WebApplicationFirewallPolicyListResult(msrest.serialization.Model):
"""Result of the request to list WebApplicationFirewallPolicies. It contains a list of WebApplicationFirewallPolicy objects and a URL link to get the next set of results.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of WebApplicationFirewallPolicies within a resource group.
:vartype value: list[~azure.mgmt.network.v2019_04_01.models.WebApplicationFirewallPolicy]
:ivar next_link: URL to get the next set of WebApplicationFirewallPolicy objects if there are
any.
:vartype next_link: str
"""
_validation = {
'value': {'readonly': True},
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type': '[WebApplicationFirewallPolicy]'},
'next_link': {'key': 'nextLink', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(WebApplicationFirewallPolicyListResult, self).__init__(**kwargs)
self.value = None
self.next_link = None
|
Azure/azure-sdk-for-python
|
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_04_01/models/_models.py
|
Python
|
mit
| 674,347 | 0.003676 |
# -*- coding: utf-8 -*-
# Main kivy import
import kivy
# Additional kivy imports
from kivy.app import App
from kivy.config import Config
# Screens
from screens import screenmanager
from screens.mainscreen import MainScreen
from screens.ingamescreen import IngameScreen
# Cause program to end if the required kivy version is not installed
kivy.require('1.8.0')
__author__ = 'ohaz'
# ---------------
# Config settings
# ---------------
# Multitouch emulation creates red dots on the screen. We don't need multitouch, so we disable it
Config.set('input', 'mouse', 'mouse,disable_multitouch')
# ---------------------
# Local initialisations
# ---------------------
# Initialise the screen manager (screens/screenmanager.py)
screenmanager.init()
# Add the two screens to it
screenmanager.set_screens([MainScreen(name='main_menu'), IngameScreen(name='ingame')])
# Start with the main menu screen
screenmanager.change_to('main_menu')
class ColoursApp(App):
"""
The main Class.
Only needed for the build function.
"""
def build(self):
"""
Method to build the app.
:return: the screenmanager
"""
return screenmanager.get_sm()
# Create the app and run it
if __name__ == '__main__':
ColoursApp().run()
|
ohaz/Colours
|
main.py
|
Python
|
apache-2.0
| 1,269 | 0.002364 |
import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.meta(server_roles='+smartproxy'),
pytest.mark.usefixtures('setup_provider'),
pytest.mark.tier(1),
pytest.mark.provider([ContainersProvider], scope='function'),
test_requirements.containers
]
AttributeToVerify = namedtuple('AttributeToVerify', ['table', 'attr', 'verifier'])
TESTED_ATTRIBUTES__openscap_off = (
AttributeToVerify('configuration', 'OpenSCAP Results', bool),
AttributeToVerify('configuration', 'OpenSCAP HTML', lambda val: val == 'Available'),
AttributeToVerify('configuration', 'Last scan', dateparser.parse)
)
TESTED_ATTRIBUTES__openscap_on = TESTED_ATTRIBUTES__openscap_off + (
AttributeToVerify('compliance', 'Status', lambda val: val.lower() != 'never verified'),
AttributeToVerify('compliance', 'History', lambda val: val == 'Available')
)
TEST_ITEMS = (
ContainersTestItem(Image, 'openscap_off', is_openscap=False,
tested_attr=TESTED_ATTRIBUTES__openscap_off),
ContainersTestItem(Image, 'openscap_on', is_openscap=True,
tested_attr=TESTED_ATTRIBUTES__openscap_on)
)
NUM_SELECTED_IMAGES = 1
@pytest.fixture(scope='function')
def delete_all_container_tasks(appliance):
col = appliance.collections.tasks.filter({'tab': 'AllTasks'})
col.delete_all()
@pytest.fixture(scope='function')
def random_image_instance(appliance):
collection = appliance.collections.container_images
# add filter for select only active(not archived) images from redHat registry
filter_image_collection = collection.filter({'active': True, 'redhat_registry': True})
return random.sample(filter_image_collection.all(), NUM_SELECTED_IMAGES).pop()
@pytest.mark.polarion('10030')
def test_manage_policies_navigation(random_image_instance):
"""
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
random_image_instance.assign_policy_profiles('OpenSCAP profile')
@pytest.mark.polarion('10031')
def test_check_compliance(random_image_instance):
"""
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
random_image_instance.assign_policy_profiles('OpenSCAP profile')
random_image_instance.check_compliance()
def get_table_attr(instance, table_name, attr):
# Trying to read the table <table_name> attribute <attr>
view = navigate_to(instance, 'Details', force=True)
table = getattr(view.entities, table_name, None)
if table:
return table.read().get(attr)
@pytest.mark.parametrize(('test_item'), TEST_ITEMS)
def test_containers_smartstate_analysis(provider, test_item, soft_assert,
delete_all_container_tasks,
random_image_instance):
"""
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
if test_item.is_openscap:
random_image_instance.assign_policy_profiles('OpenSCAP profile')
else:
random_image_instance.unassign_policy_profiles('OpenSCAP profile')
random_image_instance.perform_smartstate_analysis(wait_for_finish=True)
view = navigate_to(random_image_instance, 'Details')
for tbl, attr, verifier in test_item.tested_attr:
table = getattr(view.entities, tbl)
table_data = {k.lower(): v for k, v in table.read().items()}
if not soft_assert(attr.lower() in table_data,
f'{tbl} table has missing attribute \'{attr}\''):
continue
provider.refresh_provider_relationships()
wait_for_retval = wait_for(lambda: get_table_attr(random_image_instance, tbl, attr),
message='Trying to get attribute "{}" of table "{}"'.format(
attr, tbl),
delay=5, num_sec=120, silent_failure=True)
if not wait_for_retval:
soft_assert(False, 'Could not get attribute "{}" for "{}" table.'
.format(attr, tbl))
continue
value = wait_for_retval.out
soft_assert(verifier(value),
f'{tbl}.{attr} attribute has unexpected value ({value})')
@pytest.mark.parametrize(('test_item'), TEST_ITEMS)
def test_containers_smartstate_analysis_api(provider, test_item, soft_assert,
delete_all_container_tasks, random_image_instance):
"""
Test initiating a SmartState Analysis scan via the CFME API through the ManageIQ API Client
entity class.
RFE: BZ 1486362
Polarion:
assignee: juwatts
caseimportance: high
casecomponent: Containers
initialEstimate: 1/6h
"""
if test_item.is_openscap:
random_image_instance.assign_policy_profiles('OpenSCAP profile')
else:
random_image_instance.unassign_policy_profiles('OpenSCAP profile')
original_scan = random_image_instance.last_scan_attempt_on
random_image_instance.scan()
task = provider.appliance.collections.tasks.instantiate(
name=f"Container Image Analysis: '{random_image_instance.name}'", tab='AllTasks')
task.wait_for_finished()
soft_assert(original_scan != random_image_instance.last_scan_attempt_on,
'SmartState Anaysis scan has failed')
|
nachandr/cfme_tests
|
cfme/tests/containers/test_containers_smartstate_analysis.py
|
Python
|
gpl-2.0
| 5,838 | 0.002398 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Script to test TF-TRT INT8 conversion without calibration on Mnist model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.compiler.tf2tensorrt.python.ops import trt_ops
# pylint: enable=unused-import
from tensorflow.core.protobuf import config_pb2
from tensorflow.python import data
from tensorflow.python import keras
from tensorflow.python.compiler.tensorrt import trt_convert
from tensorflow.python.estimator.estimator import Estimator
from tensorflow.python.estimator.model_fn import EstimatorSpec
from tensorflow.python.estimator.model_fn import ModeKeys
from tensorflow.python.estimator.run_config import RunConfig
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import importer
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.layers import layers
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import metrics
from tensorflow.python.ops import nn
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary
from tensorflow.python.training import saver
from tensorflow.python.training.adam import AdamOptimizer
from tensorflow.python.training.checkpoint_management import latest_checkpoint
from tensorflow.python.training.training_util import get_global_step
INPUT_NODE_NAME = 'input'
OUTPUT_NODE_NAME = 'output'
class QuantizationAwareTrainingMNISTTest(test_util.TensorFlowTestCase):
def _BuildGraph(self, x):
def _Quantize(x, r):
x = gen_array_ops.quantize_and_dequantize_v2(x, -r, r)
return x
def _DenseLayer(x, num_inputs, num_outputs, quantization_range, name):
"""Dense layer with quantized outputs.
Args:
x: input to the dense layer
num_inputs: number of input columns of x
num_outputs: number of output columns
quantization_range: the min/max range for quantization
name: name of the variable scope
Returns:
The output of the layer.
"""
with variable_scope.variable_scope(name):
kernel = variable_scope.get_variable(
'kernel',
shape=[num_inputs, num_outputs],
dtype=dtypes.float32,
initializer=keras.initializers.glorot_uniform())
bias = variable_scope.get_variable(
'bias',
shape=[num_outputs],
dtype=dtypes.float32,
initializer=keras.initializers.zeros())
x = math_ops.matmul(x, kernel)
x = _Quantize(x, quantization_range)
x = nn.bias_add(x, bias)
x = _Quantize(x, quantization_range)
return x
x = _Quantize(x, 1)
# Conv + Bias + Relu6
x = layers.conv2d(x, filters=32, kernel_size=3, use_bias=True)
x = nn.relu6(x)
# Conv + Bias + Relu6
x = layers.conv2d(x, filters=64, kernel_size=3, use_bias=True)
x = nn.relu6(x)
# Reduce
x = math_ops.reduce_mean(x, [1, 2])
x = _Quantize(x, 6)
# FC1
x = _DenseLayer(x, 64, 512, 6, name='dense')
x = nn.relu6(x)
# FC2
x = _DenseLayer(x, 512, 10, 25, name='dense_1')
x = array_ops.identity(x, name=OUTPUT_NODE_NAME)
return x
def _GetGraphDef(self, use_trt, max_batch_size, model_dir):
"""Get the frozen mnist GraphDef.
Args:
use_trt: whether use TF-TRT to convert the graph.
max_batch_size: the max batch size to apply during TF-TRT conversion.
model_dir: the model directory to load the checkpoints.
Returns:
The frozen mnist GraphDef.
"""
graph = ops.Graph()
with self.session(graph=graph) as sess:
with graph.device('/GPU:0'):
x = array_ops.placeholder(
shape=(None, 28, 28, 1), dtype=dtypes.float32, name=INPUT_NODE_NAME)
self._BuildGraph(x)
# Load weights
mnist_saver = saver.Saver()
checkpoint_file = latest_checkpoint(model_dir)
mnist_saver.restore(sess, checkpoint_file)
# Freeze
graph_def = graph_util.convert_variables_to_constants(
sess, sess.graph_def, output_node_names=[OUTPUT_NODE_NAME])
# Convert with TF-TRT
if use_trt:
logging.info('Number of nodes before TF-TRT conversion: %d',
len(graph_def.node))
graph_def = trt_convert.create_inference_graph(
graph_def,
outputs=[OUTPUT_NODE_NAME],
max_batch_size=max_batch_size,
precision_mode='INT8',
# There is a 2GB GPU memory limit for each test, so we set
# max_workspace_size_bytes to 256MB to leave enough room for TF
# runtime to allocate GPU memory.
max_workspace_size_bytes=1 << 28,
minimum_segment_size=2,
use_calibration=False,
)
logging.info('Number of nodes after TF-TRT conversion: %d',
len(graph_def.node))
num_engines = len(
[1 for n in graph_def.node if str(n.op) == 'TRTEngineOp'])
self.assertEqual(1, num_engines)
return graph_def
def _Run(self, is_training, use_trt, batch_size, num_epochs, model_dir):
"""Train or evaluate the model.
Args:
is_training: whether to train or evaluate the model. In training mode,
quantization will be simulated where the quantize_and_dequantize_v2 are
placed.
use_trt: if true, use TRT INT8 mode for evaluation, which will perform
real quantization. Otherwise use native TensorFlow which will perform
simulated quantization. Ignored if is_training is True.
batch_size: batch size.
num_epochs: how many epochs to train. Ignored if is_training is False.
model_dir: where to save or load checkpoint.
Returns:
The Estimator evaluation result.
"""
# Get dataset
train_data, test_data = mnist.load_data()
def _PreprocessFn(x, y):
x = math_ops.cast(x, dtypes.float32)
x = array_ops.expand_dims(x, axis=2)
x = 2.0 * (x / 255.0) - 1.0
y = math_ops.cast(y, dtypes.int32)
return x, y
def _EvalInputFn():
mnist_x, mnist_y = test_data
dataset = data.Dataset.from_tensor_slices((mnist_x, mnist_y))
dataset = dataset.apply(
data.experimental.map_and_batch(
map_func=_PreprocessFn,
batch_size=batch_size,
num_parallel_calls=8))
dataset = dataset.repeat(count=1)
iterator = dataset.make_one_shot_iterator()
features, labels = iterator.get_next()
return features, labels
def _TrainInputFn():
mnist_x, mnist_y = train_data
dataset = data.Dataset.from_tensor_slices((mnist_x, mnist_y))
dataset = dataset.shuffle(2 * len(mnist_x))
dataset = dataset.apply(
data.experimental.map_and_batch(
map_func=_PreprocessFn,
batch_size=batch_size,
num_parallel_calls=8))
dataset = dataset.repeat(count=num_epochs)
iterator = dataset.make_one_shot_iterator()
features, labels = iterator.get_next()
return features, labels
def _ModelFn(features, labels, mode):
if is_training:
logits_out = self._BuildGraph(features)
else:
graph_def = self._GetGraphDef(use_trt, batch_size, model_dir)
logits_out = importer.import_graph_def(
graph_def,
input_map={INPUT_NODE_NAME: features},
return_elements=[OUTPUT_NODE_NAME + ':0'],
name='')[0]
loss = losses.sparse_softmax_cross_entropy(
labels=labels, logits=logits_out)
summary.scalar('loss', loss)
classes_out = math_ops.argmax(logits_out, axis=1, name='classes_out')
accuracy = metrics.accuracy(
labels=labels, predictions=classes_out, name='acc_op')
summary.scalar('accuracy', accuracy[1])
if mode == ModeKeys.EVAL:
return EstimatorSpec(
mode, loss=loss, eval_metric_ops={'accuracy': accuracy})
elif mode == ModeKeys.TRAIN:
optimizer = AdamOptimizer(learning_rate=1e-2)
train_op = optimizer.minimize(loss, global_step=get_global_step())
return EstimatorSpec(mode, loss=loss, train_op=train_op)
config_proto = config_pb2.ConfigProto()
config_proto.gpu_options.allow_growth = True
estimator = Estimator(
model_fn=_ModelFn,
model_dir=model_dir if is_training else None,
config=RunConfig(session_config=config_proto))
if is_training:
estimator.train(_TrainInputFn)
results = estimator.evaluate(_EvalInputFn)
logging.info('accuracy: %s', str(results['accuracy']))
return results
# To generate the checkpoint, set a different model_dir and call self._Run()
# by setting is_training=True and num_epochs=1000, e.g.:
# model_dir = '/tmp/quantization_mnist'
# self._Run(
# is_training=True,
# use_trt=False,
# batch_size=128,
# num_epochs=100,
# model_dir=model_dir)
def testEval(self):
if not trt_convert.is_tensorrt_enabled():
return
model_dir = test.test_src_dir_path('python/compiler/tensorrt/test/testdata')
accuracy_tf_native = self._Run(
is_training=False,
use_trt=False,
batch_size=128,
num_epochs=None,
model_dir=model_dir)['accuracy']
logging.info('accuracy_tf_native: %f', accuracy_tf_native)
self.assertAllClose(0.9662, accuracy_tf_native, rtol=1e-3, atol=1e-3)
if trt_convert.get_linked_tensorrt_version()[0] < 5:
return
accuracy_tf_trt = self._Run(
is_training=False,
use_trt=True,
batch_size=128,
num_epochs=None,
model_dir=model_dir)['accuracy']
logging.info('accuracy_tf_trt: %f', accuracy_tf_trt)
self.assertAllClose(0.9675, accuracy_tf_trt, rtol=1e-3, atol=1e-3)
if __name__ == '__main__':
test.main()
|
jendap/tensorflow
|
tensorflow/python/compiler/tensorrt/test/quantization_mnist_test.py
|
Python
|
apache-2.0
| 10,917 | 0.005954 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PortalTab'
db.create_table('lizard_box_portaltab', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('tab_type', self.gf('django.db.models.fields.IntegerField')(default=1)),
('destination_slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
('destination_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
))
db.send_create_signal('lizard_box', ['PortalTab'])
# Adding model 'LayoutPortalTab'
db.create_table('lizard_box_layoutportaltab', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('layout', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['lizard_box.Layout'])),
('portal_tab', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['lizard_box.PortalTab'])),
('index', self.gf('django.db.models.fields.IntegerField')(default=100)),
))
db.send_create_signal('lizard_box', ['LayoutPortalTab'])
# Changing field 'Box.url'
db.alter_column('lizard_box_box', 'url', self.gf('django.db.models.fields.CharField')(max_length=200, null=True))
def backwards(self, orm):
# Deleting model 'PortalTab'
db.delete_table('lizard_box_portaltab')
# Deleting model 'LayoutPortalTab'
db.delete_table('lizard_box_layoutportaltab')
# Changing field 'Box.url'
db.alter_column('lizard_box_box', 'url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True))
models = {
'lizard_box.box': {
'Meta': {'object_name': 'Box'},
'box_type': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'icon_class': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
'template': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'lizard_box.column': {
'Meta': {'object_name': 'Column'},
'boxes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['lizard_box.Box']", 'through': "orm['lizard_box.ColumnBox']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'index': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
'layout': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Layout']"}),
'width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})
},
'lizard_box.columnbox': {
'Meta': {'object_name': 'ColumnBox'},
'action_boxes': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'action_boxes'", 'symmetrical': 'False', 'to': "orm['lizard_box.Box']"}),
'box': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Box']"}),
'column': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Column']"}),
'height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'index': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'})
},
'lizard_box.layout': {
'Meta': {'object_name': 'Layout'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'portal_tabs': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['lizard_box.PortalTab']", 'through': "orm['lizard_box.LayoutPortalTab']", 'symmetrical': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '80'})
},
'lizard_box.layoutportaltab': {
'Meta': {'object_name': 'LayoutPortalTab'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'index': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
'layout': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.Layout']"}),
'portal_tab': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_box.PortalTab']"})
},
'lizard_box.portaltab': {
'Meta': {'object_name': 'PortalTab'},
'destination_slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'destination_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tab_type': ('django.db.models.fields.IntegerField', [], {'default': '1'})
}
}
complete_apps = ['lizard_box']
|
lizardsystem/lizard-box
|
lizard_box/migrations/0008_auto__add_portaltab__add_layoutportaltab__chg_field_box_url.py
|
Python
|
gpl-3.0
| 5,651 | 0.007963 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
import sys
from convutils import convutils
import bpn.cli
import bpn.structures
from defaults import (
SUPERDEBUG,
SUPERDEBUG_MODE,
LINKS_FIELDNAMES,
PARAMETERS_FIELDNAMES,
TRANSITIONS_FIELDNAMES,
DETAILED_TRANSITIONS_FIELDNAMES
)
# Configure all the logging stuff
import logging
logger = logging.getLogger('bpn.sabpn')
if SUPERDEBUG_MODE:
# A logging level below logging.DEBUG
logging.addLevelName(SUPERDEBUG, 'SUPERDEBUG')
logger.setLevel(SUPERDEBUG)
#stream_handler.setLevel(SUPERDEBUG)
import simulatedannealing
import states
import recorders
def main(argv=None):
cli_parser = bpn.cli.SaCli()
input_data = cli_parser.parse_args(argv)
logger.info("Constructing supporting data structures; this may "
"take a while...")
annotated_interactions = bpn.structures.AnnotatedInteractionsArray(
input_data.interactions_graph,
input_data.annotations_dict
)
logger.info("Considering %d candidate links in total." %
annotated_interactions.calc_num_links())
logger.info("Constructing Simulated Annealing")
if input_data.free_parameters:
logger.info("Using free parameter transitions.")
parameters_state_class = states.RandomTransitionParametersState
else:
parameters_state_class = states.PLNParametersState
if input_data.disable_swaps:
logger.info("Disabling swap transitions.")
links_state_class = states.NoSwapArrayLinksState
else:
links_state_class = states.ArrayLinksState
if input_data.detailed_transitions:
logger.info("Recording extra information for each state.")
transitions_csvfile = convutils.make_csv_dict_writer(
input_data.transitions_outfile,
DETAILED_TRANSITIONS_FIELDNAMES
)
else:
transitions_csvfile = convutils.make_csv_dict_writer(
input_data.transitions_outfile,
TRANSITIONS_FIELDNAMES
)
sa = simulatedannealing.ArraySimulatedAnnealing(
annotated_interactions,
input_data.activity_threshold,
input_data.transition_ratio,
num_steps=input_data.steps,
temperature=input_data.temperature,
end_temperature=input_data.end_temperature,
parameters_state_class=parameters_state_class,
links_state_class=links_state_class
)
logger.info("Beginning to Anneal. This may take a while...")
sa.run()
logger.info("Run completed.")
logger.info("Writing link results to %s" %
input_data.links_outfile.name)
links_out_csvwriter = convutils.make_csv_dict_writer(
input_data.links_outfile, LINKS_FIELDNAMES)
logger.info("Writing parameter results to %s" % (
input_data.parameters_outfile.name))
parameters_out_csvwriter = convutils.make_csv_dict_writer(
input_data.parameters_outfile, PARAMETERS_FIELDNAMES)
logger.info("Writing transitions data to %s." % (
input_data.transitions_outfile.name))
logger.info("Finished.")
if __name__ == '__main__':
main()
|
gotgenes/BiologicalProcessNetworks
|
bpn/mcmc/sabpn.py
|
Python
|
mit
| 3,485 | 0.003156 |
from misc_utils import get_config, get_logger, tokenize
from discourse_relation import DiscourseRelation
from collections import Counter, defaultdict
import json
import abc
import numpy as np
from os.path import join
import os
logger = get_logger(__name__)
class Resource(metaclass=abc.ABCMeta):
def __init__(self, path, classes):
self.path = path
self.classes = sorted(classes)
self.y_indices = {x: y for y, x in enumerate(self.classes)}
self.instances = list(self._load_instances(path))
@abc.abstractmethod
def _load_instances(self, path):
raise NotImplementedError("This class must be subclassed.")
class PDTBRelations(Resource):
def __init__(self, path, classes, separate_dual_classes, filter_type=None, skip_missing_classes=True):
self.skip_missing_classes = skip_missing_classes
self.separate_dual_classes = separate_dual_classes
self.filter_type = [] if filter_type is None else filter_type
super().__init__(path, classes)
def _load_instances(self, path):
with open(join(path, 'relations.json')) as file_:
for line in file_:
rel = DiscourseRelation(json.loads(line.strip()))
if (self.filter_type != [] or self.filter_type is not None) and rel.relation_type() not in self.filter_type:
continue
if self.separate_dual_classes:
for splitted in rel.split_up_senses():
if len(splitted.senses()) > 1:
raise ValueError("n_senses > 1")
if len(splitted.senses()) == 1 and splitted.senses()[0] not in self.y_indices:
if self.skip_missing_classes:
logger.debug("Sense class {} not in class list, skipping {}".format(splitted.senses()[0], splitted.relation_id()))
continue
yield splitted
else:
a_class_exist = any(r in self.y_indices for r in rel.senses())
if not a_class_exist:
if self.skip_missing_classes:
logger.debug("Sense {} classes not in class list, skipping {}".format(rel.senses(), rel.relation_id()))
continue
yield rel
def get_feature_tensor(self, extractors):
rels_feats = []
n_instances = 0
last_features_for_instance = None
for rel in self.instances:
n_instances += 1
feats = []
total_features_per_instance = 0
for extractor in extractors:
# These return matrices of shape (1, n_features)
# We concatenate them on axis 1
arg_rawtext = getattr(rel, extractor.argument)()
arg_tokenized = tokenize(arg_rawtext)
arg_feats = extractor.extract_features(arg_tokenized)
feats.append(arg_feats)
total_features_per_instance += extractor.n_features
if last_features_for_instance is not None:
# Making sure we have equal number of features per instance
assert total_features_per_instance == last_features_for_instance
rels_feats.append(np.concatenate(feats, axis=1))
feature_tensor = np.array(rels_feats)
assert_shape = (n_instances, 1, total_features_per_instance)
assert feature_tensor.shape == assert_shape, \
"Tensor shape mismatch. Is {}, should be {}".format(feature_tensor.shape, assert_shape)
return feature_tensor
def get_correct(self, indices=True):
"""
Returns answer indices.
"""
for rel in self.instances:
senses = rel.senses()
if self.separate_dual_classes:
if indices:
yield self.y_indices[senses[0]]
else:
yield senses[0]
else:
ys = [self.y_indices[sense] for sense in senses]
if indices:
yield ys
else:
yield senses
def store_results(self, results, store_path):
"""
Don't forget to use the official scoring script here.
"""
text_results = [self.classes[res] for res in results]
# Load test file
# Output json object with results
# Deal with multiple instances somehow
predicted_rels = []
for text_result, rel in zip(text_results, self.instances):
if rel.is_explicit():
rel_type = 'Explicit'
else:
rel_type = 'Implicit'
predicted_rels.append(rel.to_output_format(text_result, rel_type)) # turn string representation into list instance first
# Store test file
if not os.path.exists(store_path):
os.makedirs(store_path)
with open(join(store_path, 'output.json'), 'w') as w:
for rel in predicted_rels:
w.write(json.dumps(rel) + '\n')
logger.info("Stored predicted output at {}".format(store_path))
|
jimmycallin/master-thesis
|
architectures/svm_baseline/resources.py
|
Python
|
mit
| 5,218 | 0.002108 |
# -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest
class TestGroup(ModelTest):
"""Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(
group_name = "test_group",
display_name = "Test Group"
)
class TestUser(ModelTest):
"""Unit test case for the ``User`` model."""
klass = model.User
attrs = dict(
user_name = "ignucius",
email_address = "ignucius@example.org"
)
def test_obj_creation_username(self):
"""The obj constructor must set the user name right"""
eq_(self.obj.user_name, "ignucius")
def test_obj_creation_email(self):
"""The obj constructor must set the email right"""
eq_(self.obj.email_address, "ignucius@example.org")
def test_no_permissions_by_default(self):
"""User objects should have no permission by default."""
eq_(len(self.obj.permissions), 0)
def test_getting_by_email(self):
"""Users should be fetcheable by their email addresses"""
him = model.User.by_email_address("ignucius@example.org")
eq_(him, self.obj)
class TestPermission(ModelTest):
"""Unit test case for the ``Permission`` model."""
klass = model.Permission
attrs = dict(
permission_name = "test_permission",
description = "This is a test Description"
)
|
txdywy/wiki20
|
wiki20/tests/models/test_auth.py
|
Python
|
gpl-2.0
| 1,523 | 0.009849 |
from annoying.decorators import ajax_request, render_to
from blogs.views import blog_list
from django.db.models import Count
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from snipts.utils import get_lexers_list
from taggit.models import Tag
@render_to('homepage.html')
def homepage(request):
if request.blog_user:
return blog_list(request)
return {}
@ajax_request
def lexers(request):
lexers = get_lexers_list()
objects = []
for l in lexers:
try:
filters = l[2]
except IndexError:
filters = []
try:
mimetypes = l[3]
except IndexError:
mimetypes = []
objects.append({
'name': l[0],
'lexers': l[1],
'filters': filters,
'mimetypes': mimetypes
})
return {'objects': objects}
def login_redirect(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/' + request.user.username + '/')
else:
return HttpResponseRedirect('/')
@render_to('tags.html')
def tags(request):
all_tags = Tag.objects.filter(snipt__public=True).order_by('name')
all_tags = all_tags.annotate(count=Count('taggit_taggeditem_items__id'))
popular_tags = Tag.objects.filter(snipt__public=True)
popular_tags = popular_tags.annotate(
count=Count('taggit_taggeditem_items__id'))
popular_tags = popular_tags.order_by('-count')[:20]
popular_tags = sorted(popular_tags, key=lambda tag: tag.name)
return {
'all_tags': all_tags,
'tags': popular_tags
}
@ajax_request
def user_api_key(request):
if not request.user.is_authenticated():
return HttpResponseBadRequest()
return {
'api_key': request.user.api_key.key
}
|
nicksergeant/snipt
|
views.py
|
Python
|
mit
| 1,815 | 0.000551 |
""" Set-up script to install PyFAST locally
"""
from setuptools import setup
setup(name='pyfast',
version='0.1',
description='Tools for working with wind turbine simulator FAST',
url='https://github.com/jennirinker/PyFAST.git',
author='Jenni Rinker',
author_email='jennifer.m.rinker@gmail.com',
license='GPL',
packages=['pyfast'],
zip_safe=False)
|
jennirinker/PyFAST
|
setup.py
|
Python
|
gpl-3.0
| 395 | 0.002532 |
from dominoes import players
from dominoes import search
from dominoes.board import Board
from dominoes.domino import Domino
from dominoes.exceptions import EmptyBoardException
from dominoes.exceptions import EndsMismatchException
from dominoes.exceptions import GameInProgressException
from dominoes.exceptions import GameOverException
from dominoes.exceptions import NoSuchDominoException
from dominoes.exceptions import NoSuchPlayerException
from dominoes.exceptions import SeriesOverException
from dominoes.game import Game
from dominoes.hand import Hand
from dominoes.result import Result
from dominoes.series import Series
from dominoes.skinny_board import SkinnyBoard
|
abw333/dominoes
|
dominoes/__init__.py
|
Python
|
mit
| 675 | 0 |
# wsse/client/requests/tests/test_auth.py
# coding=utf-8
# pywsse
# Authors: Rushy Panchal, Naphat Sanguansin, Adam Libresco, Jérémie Lumbroso
# Date: September 1st, 2016
# Description: Test the requests authentication implementation
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from rest_framework import status
import requests
from wsse import settings
from wsse.compat import reverse_lazy
from wsse.server.django.wsse.models import UserSecret
from wsse.client.requests.auth import WSSEAuth
def setUpModule():
'''
Set up the module for running tests.
'''
# Set the nonce store to the Django store after saving the current settings
# so they can be restored later.
global __old_nonce_settings
__old_nonce_settings = (settings.NONCE_STORE, settings.NONCE_STORE_ARGS)
settings.NONCE_STORE = 'wsse.server.django.wsse.store.DjangoNonceStore'
settings.NONCE_STORE_ARGS = []
def tearDownModule():
'''
Tear down the module after running tests.
'''
# Restore the nonce settings.
settings.NONCE_STORE, settings.NONCE_STORE_ARGS = __old_nonce_settings
class TestWSSEAuth(StaticLiveServerTestCase):
'''
Test authenticating through the `WSSEAuth` handler.
'''
endpoint = reverse_lazy('api-test')
def setUp(self):
'''
Set up the test cases.
'''
self.user = User.objects.create(username = 'username')
self.user_secret = UserSecret.objects.create(user = self.user)
self.auth = WSSEAuth('username', self.user_secret.secret)
self.base_url = '{}{}'.format(self.live_server_url, self.endpoint)
def test_auth(self):
'''
Perform valid authentication. The user should be authenticated.
'''
response = requests.get(self.base_url, auth = self.auth)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_auth_reuse(self):
'''
Reuse the same authentication handler. Both requests should succeed.
'''
response_a = requests.get(self.base_url, auth = self.auth)
response_b = requests.get(self.base_url, auth = self.auth)
self.assertEqual(response_a.status_code, status.HTTP_200_OK)
self.assertEqual(response_b.status_code, status.HTTP_200_OK)
def test_auth_incorrect_password(self):
'''
Authneticate with an incorrect password. The authentication should fail.
'''
response = requests.get(self.base_url, auth = WSSEAuth('username',
'!' + self.user_secret.secret))
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_auth_nonexistent_username(self):
'''
Authneticate with a nonexistent user. The authentication should fail.
'''
response = requests.get(self.base_url, auth = WSSEAuth('nonexistentuser',
self.user_secret.secret))
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
PrincetonUniversity/pywsse
|
wsse/client/requests/tests/test_auth.py
|
Python
|
lgpl-3.0
| 2,780 | 0.026278 |
# -*- coding: utf-8 -*-
#
# This file is part of django-email-change.
#
# django-email-change adds support for email address change and confirmation.
#
# Development Web Site:
# - http://www.codetrax.org/projects/django-email-change
# Public Source Code Repository:
# - https://source.codetrax.org/hgroot/django-email-change
#
# Copyright 2010 George Notaras <gnot [at] g-loaded.eu>
#
# 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.
#
VERSION = (0, 2, 3, 'final', 0)
def get_version():
version = '%d.%d.%d' % (VERSION[0], VERSION[1], VERSION[2])
return version
|
novapost/django-email-change
|
src/email_change/__init__.py
|
Python
|
apache-2.0
| 1,088 | 0.001838 |
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, user, password):
wd = self.app.wd
self.app.open_home_page()
self.app.type_text("user", user)
self.app.type_text("pass", password)
wd.find_element_by_css_selector("input[value='Login']").click()
def ensure_login(self, user, password):
wd = self.app.wd
if self.is_logged_in():
if self.is_logged_in_as(user):
return
else:
self.logout()
self.login(user,password)
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Logout").click()
def ensure_logout(self):
wd = self.app.wd
if self.is_logged_in():
self.logout()
def is_logged_in(self):
wd = self.app.wd
return len(wd.find_elements_by_link_text("Logout"))> 0
def is_logged_in_as(self, user):
wd = self.app.wd
return self.get_logged_user() == user
def get_logged_user(self):
wd = self.app.wd
return wd.find_element_by_xpath("//form[@name='logout']/b").text[1:-1]
|
obutkalyuk/Python_15
|
fixture/session.py
|
Python
|
apache-2.0
| 1,157 | 0.002593 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm
fig = plt.figure()
ax = {}
ax["DropOut"] = fig.add_subplot(121)
ax["NoDropOut"] = fig.add_subplot(122)
dList = {}
dList["DropOut"] = ["DropOut1","DropOut2","DropOut3"]
dList["NoDropOut"] = ["NoDropOut1","NoDropOut2"]
def myPlot(ax,dName):
cList = ["black","blue","red","green","cyan"]
for i,dfile in enumerate(dName):
print dfile
d = pd.read_csv("Output_DropTest/%s/output.dat"%dfile)
dTrain = d[d["mode"]=="Train"]
dTest = d[d["mode"]=="Test" ]
ax.plot(dTrain.epoch, dTrain.accuracy*100., lineStyle="-" , color=cList[i], label=dfile)
ax.plot(dTest .epoch, dTest .accuracy*100., lineStyle="--", color=cList[i], label="")
ax.set_xlim(0,50)
ax.set_ylim(0,100)
ax.legend(loc=4,fontsize=8)
ax.grid()
for k in dList:
myPlot(ax[k],dList[k])
plt.show()
|
ysasaki6023/NeuralNetworkStudy
|
cifar02/analysis_DropTest.py
|
Python
|
mit
| 925 | 0.028108 |
from bayes_opt import BayesianOptimization
'''
Example of how to use this bayesian optimization package.
'''
# Lets find the maximum of a simple quadratic function of two variables
# We create the bayes_opt object and pass the function to be maximized
# together with the paraters names and their bounds.
bo = BayesianOptimization(lambda x, y: -x**2 -(y-1)**2 + 1, {'x': (-4, 4), 'y': (-3, 3)})
# One of the things we can do with this object is pass points
# which we want the algorithm to probe. A dictionary with the
# parameters names and a list of values to include in the search
# must be given.
bo.explore({'x': [-1, 3], 'y': [-2, 2]})
# Additionally, if we have any prior knowledge of the behaviour of
# the target function (even if not totally accurate) we can also
# tell that to the optimizer.
# Here we pass a dictionary with target values as keys of another
# dictionary with parameters names and their corresponding value.
bo.initialize({-2: {'x': 1, 'y': 0}, -1.251: {'x': 1, 'y': 1.5}})
# Once we are satisfied with the initialization conditions
# we let the algorithm do its magic by calling the maximize()
# method.
bo.maximize(n_iter=15)
# The output values can be accessed with self.res
print(bo.res['max'])
# If we are not satisfied with the current results we can pickup from
# where we left, maybe pass some more exploration points to the algorithm
# change any parameters we may choose, and the let it run again.
bo.explore({'x': [0.6], 'y': [-0.23]})
bo.maximize(n_iter=5, acq='pi')
# Finally, we take a look at the final results.
print(bo.res['max'])
print(bo.res['all'])
|
mpearmain/BayesBoost
|
examples/usage.py
|
Python
|
apache-2.0
| 1,604 | 0.00187 |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return tup
def symarray(prefix, shape):
import numpy as np
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbol('%s_%s' % (
prefix, '_'.join(map(str, index))))
return arr
def lambdify(args, exprs):
"""
lambdify mimics sympy.lambdify
"""
try:
nargs = len(args)
except TypeError:
args = (args,)
nargs = 1
try:
nexprs = len(exprs)
except TypeError:
exprs = (exprs,)
nexprs = 1
@_wrap_numbers
def f(*inp):
if len(inp) != nargs:
raise TypeError("Incorrect number of arguments")
try:
len(inp)
except TypeError:
inp = (inp,)
subsd = dict(zip(args, inp))
return [expr.subs(subsd).evalf() for expr in exprs][
0 if nexprs == 1 else slice(None)]
return f
class Lambdify(object):
"""
Lambdify mimics symengine.Lambdify
"""
def __init__(self, syms, exprs):
self.syms = syms
self.exprs = exprs
def __call__(self, inp, out=None):
inp = tuple(map(Number.make, inp))
subsd = dict(zip(self.syms, inp))
def _eval(expr_iter):
return [expr.subs(subsd).evalf() for expr in expr_iter]
exprs = self.exprs
if out is not None:
try:
out.flat = _eval(exprs.flatten())
except AttributeError:
out.flat = _eval(exprs)
elif isinstance(exprs, Matrix):
import numpy as np
nr, nc = exprs.nrows, exprs.ncols
out = np.empty((nr, nc))
for ri in range(nr):
for ci in range(nc):
out[ri, ci] = exprs._get_element(
ri*nc + ci).subs(subsd).evalf()
return out
# return Matrix(nr, nc, _eval(exprs._get_element(i) for
# i in range(nr*nc)))
elif hasattr(exprs, 'reshape'):
# NumPy like container:
container = exprs.__class__(exprs.shape, dtype=float, order='C')
container.flat = _eval(exprs.flatten())
return container
else:
return _eval(exprs)
|
bjodah/pysym
|
pysym/util.py
|
Python
|
bsd-2-clause
| 2,569 | 0 |
from typing import Any, Dict, Mapping, Optional, Tuple
from .exceptions import UnknownUpdateCardAction
SUPPORTED_CARD_ACTIONS = [
u'updateCard',
u'createCard',
u'addLabelToCard',
u'removeLabelFromCard',
u'addMemberToCard',
u'removeMemberFromCard',
u'addAttachmentToCard',
u'addChecklistToCard',
u'commentCard',
u'updateCheckItemStateOnCard',
]
IGNORED_CARD_ACTIONS = [
'createCheckItem',
]
CREATE = u'createCard'
CHANGE_LIST = u'changeList'
CHANGE_NAME = u'changeName'
SET_DESC = u'setDesc'
CHANGE_DESC = u'changeDesc'
REMOVE_DESC = u'removeDesc'
ARCHIVE = u'archiveCard'
REOPEN = u'reopenCard'
SET_DUE_DATE = u'setDueDate'
CHANGE_DUE_DATE = u'changeDueDate'
REMOVE_DUE_DATE = u'removeDueDate'
ADD_LABEL = u'addLabelToCard'
REMOVE_LABEL = u'removeLabelFromCard'
ADD_MEMBER = u'addMemberToCard'
REMOVE_MEMBER = u'removeMemberFromCard'
ADD_ATTACHMENT = u'addAttachmentToCard'
ADD_CHECKLIST = u'addChecklistToCard'
COMMENT = u'commentCard'
UPDATE_CHECK_ITEM_STATE = u'updateCheckItemStateOnCard'
TRELLO_CARD_URL_TEMPLATE = u'[{card_name}]({card_url})'
ACTIONS_TO_MESSAGE_MAPPER = {
CREATE: u'created {card_url_template}.',
CHANGE_LIST: u'moved {card_url_template} from {old_list} to {new_list}.',
CHANGE_NAME: u'renamed the card from "{old_name}" to {card_url_template}.',
SET_DESC: u'set description for {card_url_template} to:\n~~~ quote\n{desc}\n~~~\n',
CHANGE_DESC: (u'changed description for {card_url_template} from\n' +
'~~~ quote\n{old_desc}\n~~~\nto\n~~~ quote\n{desc}\n~~~\n'),
REMOVE_DESC: u'removed description from {card_url_template}.',
ARCHIVE: u'archived {card_url_template}.',
REOPEN: u'reopened {card_url_template}.',
SET_DUE_DATE: u'set due date for {card_url_template} to {due_date}.',
CHANGE_DUE_DATE: u'changed due date for {card_url_template} from {old_due_date} to {due_date}.',
REMOVE_DUE_DATE: u'removed the due date from {card_url_template}.',
ADD_LABEL: u'added a {color} label with \"{text}\" to {card_url_template}.',
REMOVE_LABEL: u'removed a {color} label with \"{text}\" from {card_url_template}.',
ADD_MEMBER: u'added {member_name} to {card_url_template}.',
REMOVE_MEMBER: u'removed {member_name} from {card_url_template}.',
ADD_ATTACHMENT: u'added [{attachment_name}]({attachment_url}) to {card_url_template}.',
ADD_CHECKLIST: u'added the {checklist_name} checklist to {card_url_template}.',
COMMENT: u'commented on {card_url_template}:\n~~~ quote\n{text}\n~~~\n',
UPDATE_CHECK_ITEM_STATE: u'{action} **{item_name}** in **{checklist_name}** ({card_url_template}).'
}
def prettify_date(date_string: str) -> str:
return date_string.replace('T', ' ').replace('.000', '').replace('Z', ' UTC')
def process_card_action(payload: Mapping[str, Any], action_type: str) -> Optional[Tuple[str, str]]:
proper_action = get_proper_action(payload, action_type)
if proper_action is not None:
return get_subject(payload), get_body(payload, proper_action)
return None
def get_proper_action(payload: Mapping[str, Any], action_type: str) -> Optional[str]:
if action_type == 'updateCard':
data = get_action_data(payload)
old_data = data['old']
card_data = data['card']
if data.get('listBefore'):
return CHANGE_LIST
if old_data.get('name'):
return CHANGE_NAME
if old_data.get('desc') == "":
return SET_DESC
if old_data.get('desc'):
if card_data.get('desc') == "":
return REMOVE_DESC
else:
return CHANGE_DESC
if old_data.get('due', False) is None:
return SET_DUE_DATE
if old_data.get('due'):
if card_data.get('due', False) is None:
return REMOVE_DUE_DATE
else:
return CHANGE_DUE_DATE
if old_data.get('closed') is False and card_data.get('closed'):
return ARCHIVE
if old_data.get('closed') and card_data.get('closed') is False:
return REOPEN
# we don't support events for when a card is moved up or down
# within a single list
if old_data.get('pos'):
return None
raise UnknownUpdateCardAction()
return action_type
def get_subject(payload: Mapping[str, Any]) -> str:
return get_action_data(payload)['board'].get('name')
def get_body(payload: Mapping[str, Any], action_type: str) -> str:
message_body = ACTIONS_TO_FILL_BODY_MAPPER[action_type](payload, action_type)
creator = payload['action']['memberCreator'].get('fullName')
return u'{full_name} {rest}'.format(full_name=creator, rest=message_body)
def get_added_checklist_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'checklist_name': get_action_data(payload)['checklist'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_update_check_item_body(payload: Mapping[str, Any], action_type: str) -> str:
action = get_action_data(payload)
state = action['checkItem']['state']
data = {
'action': 'checked' if state == 'complete' else 'unchecked',
'checklist_name': action['checklist'].get('name'),
'item_name': action['checkItem'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_added_attachment_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'attachment_url': get_action_data(payload)['attachment'].get('url'),
'attachment_name': get_action_data(payload)['attachment'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_updated_card_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'card_name': get_card_name(payload),
'old_list': get_action_data(payload)['listBefore'].get('name'),
'new_list': get_action_data(payload)['listAfter'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_renamed_card_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'old_name': get_action_data(payload)['old'].get('name'),
'new_name': get_action_data(payload)['old'].get('name'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_added_label_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'color': get_action_data(payload).get('value'),
'text': get_action_data(payload).get('text'),
}
return fill_appropriate_message_content(payload, action_type, data)
def get_managed_member_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'member_name': payload['action']['member'].get('fullName')
}
return fill_appropriate_message_content(payload, action_type, data)
def get_comment_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'text': get_action_data(payload)['text'],
}
return fill_appropriate_message_content(payload, action_type, data)
def get_managed_due_date_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'due_date': prettify_date(get_action_data(payload)['card'].get('due'))
}
return fill_appropriate_message_content(payload, action_type, data)
def get_changed_due_date_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'due_date': prettify_date(get_action_data(payload)['card'].get('due')),
'old_due_date': prettify_date(get_action_data(payload)['old'].get('due'))
}
return fill_appropriate_message_content(payload, action_type, data)
def get_managed_desc_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'desc': prettify_date(get_action_data(payload)['card']['desc'])
}
return fill_appropriate_message_content(payload, action_type, data)
def get_changed_desc_body(payload: Mapping[str, Any], action_type: str) -> str:
data = {
'desc': prettify_date(get_action_data(payload)['card']['desc']),
'old_desc': prettify_date(get_action_data(payload)['old']['desc'])
}
return fill_appropriate_message_content(payload, action_type, data)
def get_body_by_action_type_without_data(payload: Mapping[str, Any], action_type: str) -> str:
return fill_appropriate_message_content(payload, action_type)
def fill_appropriate_message_content(payload: Mapping[str, Any],
action_type: str,
data: Optional[Dict[str, Any]]=None) -> str:
data = {} if data is None else data
data['card_url_template'] = data.get('card_url_template', get_filled_card_url_template(payload))
message_body = get_message_body(action_type)
return message_body.format(**data)
def get_filled_card_url_template(payload: Mapping[str, Any]) -> str:
return TRELLO_CARD_URL_TEMPLATE.format(card_name=get_card_name(payload), card_url=get_card_url(payload))
def get_card_url(payload: Mapping[str, Any]) -> str:
return u'https://trello.com/c/{}'.format(get_action_data(payload)['card'].get('shortLink'))
def get_message_body(action_type: str) -> str:
return ACTIONS_TO_MESSAGE_MAPPER[action_type]
def get_card_name(payload: Mapping[str, Any]) -> str:
return get_action_data(payload)['card'].get('name')
def get_action_data(payload: Mapping[str, Any]) -> Mapping[str, Any]:
return payload['action'].get('data')
ACTIONS_TO_FILL_BODY_MAPPER = {
CREATE: get_body_by_action_type_without_data,
CHANGE_LIST: get_updated_card_body,
CHANGE_NAME: get_renamed_card_body,
SET_DESC: get_managed_desc_body,
CHANGE_DESC: get_changed_desc_body,
REMOVE_DESC: get_body_by_action_type_without_data,
ARCHIVE: get_body_by_action_type_without_data,
REOPEN: get_body_by_action_type_without_data,
SET_DUE_DATE: get_managed_due_date_body,
CHANGE_DUE_DATE: get_changed_due_date_body,
REMOVE_DUE_DATE: get_body_by_action_type_without_data,
ADD_LABEL: get_added_label_body,
REMOVE_LABEL: get_added_label_body,
ADD_MEMBER: get_managed_member_body,
REMOVE_MEMBER: get_managed_member_body,
ADD_ATTACHMENT: get_added_attachment_body,
ADD_CHECKLIST: get_added_checklist_body,
COMMENT: get_comment_body,
UPDATE_CHECK_ITEM_STATE: get_update_check_item_body,
}
|
tommyip/zulip
|
zerver/webhooks/trello/view/card_actions.py
|
Python
|
apache-2.0
| 10,437 | 0.004791 |
import numpy as np
import plotly.graph_objs as go
def p2c(r, theta, phi):
"""Convert polar unit vector to cartesians"""
return [r * np.sin(theta) * np.cos(phi),
r * np.sin(theta) * np.sin(phi),
r * np.cos(theta)]
# return [-r * np.cos(theta),
# r * np.sin(theta) * np.sin(phi),
# r * np.sin(theta) * np.cos(phi)]
class Arrow:
def __init__(self, theta, out, width=5, color='rgb(0,0,0)'):
"""
Args:
theta (float) - radians [0, π]
out (bool) - True if outgoing, False if incoming (to the origin)
width (int) - line thickness
color (hex/rgb) - line color
"""
self.theta = theta
self.out = out
self.width = width
self.color = color
wing_length, wing_angle = self._find_wing_coord()
shaft_xyz = p2c(1., self.theta, 0)
wings_xyz = [p2c(wing_length, self.theta + wing_angle, 0),
p2c(wing_length, self.theta - wing_angle, 0)]
self.shaft = go.Scatter3d(
x=[0, shaft_xyz[0]],
y=[0, shaft_xyz[1]],
z=[0, shaft_xyz[2]],
showlegend=False, mode='lines', line={'width': self.width, 'color': self.color}
)
self.wings = go.Scatter3d(
x=[wings_xyz[0][0], shaft_xyz[0] / 2., wings_xyz[1][0]],
y=[wings_xyz[0][1], shaft_xyz[1] / 2., wings_xyz[1][1]],
z=[wings_xyz[0][2], shaft_xyz[2] / 2., wings_xyz[1][2]],
showlegend=False, mode='lines', line={'width': self.width, 'color': self.color}
)
self.data = [self.shaft, self.wings]
def _find_wing_coord(self):
"""Finds polar coordinates of arrowhead wing ends"""
frac = 0.1
r = 0.5
sin45 = np.sin(np.pi / 4.)
if self.out == True:
d = r - frac * sin45
elif self.out == False:
d = r + frac * sin45
else:
raise TypeError("arg: out must be True or False")
a = np.sqrt(frac**2 * sin45**2 + d**2)
alpha = np.arccos(d / a)
return [a, alpha]
|
cydcowley/Imperial-Visualizations
|
visuals_EM/Waves and Dielectrics/plotly_arrows.py
|
Python
|
mit
| 2,137 | 0.003745 |
from customers.models import Client
from django.conf import settings
from django.db import utils
from django.views.generic import TemplateView
from tenant_schemas.utils import remove_www
class HomeView(TemplateView):
template_name = "index_public.html"
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
hostname_without_port = remove_www(self.request.get_host().split(':')[0])
try:
Client.objects.get(schema_name='public')
except utils.DatabaseError:
context['need_sync'] = True
context['shared_apps'] = settings.SHARED_APPS
context['tenants_list'] = []
return context
except Client.DoesNotExist:
context['no_public_tenant'] = True
context['hostname'] = hostname_without_port
if Client.objects.count() == 1:
context['only_public_tenant'] = True
context['tenants_list'] = Client.objects.all()
return context
|
mcanaves/django-tenant-schemas
|
examples/tenant_tutorial/tenant_tutorial/views.py
|
Python
|
mit
| 1,030 | 0.000971 |
from oscar_vat_moss import fields
from oscar.apps.address.abstract_models import AbstractShippingAddress
from oscar.apps.address.abstract_models import AbstractBillingAddress
class ShippingAddress(AbstractShippingAddress):
vatin = fields.vatin()
class BillingAddress(AbstractBillingAddress):
vatin = fields.vatin()
from oscar.apps.order.models import * # noqa
|
hastexo/django-oscar-vat_moss
|
oscar_vat_moss/order/models.py
|
Python
|
bsd-3-clause
| 375 | 0 |
#########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
from manager_rest.celery_client import celery_client as client
class WorkflowClient(object):
@staticmethod
def execute_workflow(name,
workflow,
blueprint_id,
deployment_id,
execution_id,
execution_parameters=None):
task_name = workflow['operation']
task_queue = '{}_workflows'.format(deployment_id)
execution_parameters['__cloudify_context'] = {
'workflow_id': name,
'blueprint_id': blueprint_id,
'deployment_id': deployment_id,
'execution_id': execution_id
}
client().execute_task(task_name=task_name,
task_queue=task_queue,
task_id=execution_id,
kwargs=execution_parameters)
def workflow_client():
return WorkflowClient()
|
konradxyz/cloudify-manager
|
rest-service/manager_rest/workflow_client.py
|
Python
|
apache-2.0
| 1,585 | 0 |
#! /usr/bin/env python
import vcsn
from test import *
algos = ['distance', 'inplace', 'separate']
# check INPUT EXP ALGORITHM
# -------------------------
def check_algo(i, o, algo):
i = vcsn.automaton(i)
o = vcsn.automaton(o)
print("using algorithm: ", algo)
print("checking proper")
# We call sort().strip() everywhere to avoid seeing differences caused by the
# different numbering of the states between the algorithms
CHECK_EQ(o.sort().strip(), i.proper(algo=algo).sort().strip())
# Since we remove only states that _become_ inaccessible,
# i.proper(prune = False).accessible() is not the same as
# i.proper(): in the former case we also removed the non-accessible
# states.
print("checking proper(prune = False)")
CHECK_EQ(o.accessible(),
i.proper(prune=False, algo=algo).accessible())
# FIXME: Because proper uses copy, state numbers are changed.
#
# FIXME: cannot use is_isomorphic because some of our test cases
# have unreachable states, which is considered invalid by
# is_isomorphic.
print("checking idempotence")
if i.proper(algo=algo).is_accessible():
CHECK_ISOMORPHIC(i.proper(algo=algo), i.proper(algo=algo).proper(algo=algo))
else:
CHECK_EQ(i.proper(algo=algo).sort().strip(),
i.proper(algo=algo).proper(algo=algo).sort().strip())
def check_fail_algo(aut, algo):
a = vcsn.automaton(aut)
try:
a.proper(algo=algo)
FAIL(r"invalid \\e-cycle not detected")
except RuntimeError:
PASS()
def check(i, o, algs=algos):
for algo in algs:
check_algo(i, o, algo)
def check_fail(i, algs=algos):
for algo in algs:
check_fail_algo(i, algo)
## --------------------------------------- ##
## lao, r: check the computation of star. ##
## --------------------------------------- ##
check(r'''context = "lao, r"
$ -> 0 <3>
0 -> 1 <5>
1 -> 1 <.5>\e
1 -> 2 <7>\e
2 -> $ <11>
''',
'''
digraph
{
vcsn_context = "lao, r"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
}
I0 -> 0 [label = "<3>"]
0 -> 1 [label = "<5>"]
1 -> F1 [label = "<154>"]
}
''')
## -------------------------------------------- ##
## law_char, r: check the computation of star. ##
## -------------------------------------------- ##
check(r'''digraph
{
vcsn_context = "law_char(ab), r"
I -> 0 -> F
0 -> 0 [label = "<.5>\\e"]
}''','''digraph
{
vcsn_context = "wordset<char_letters(ab)>, r"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F0
}
{
node [shape = circle, style = rounded, width = 0.5]
0
}
I0 -> 0
0 -> F0 [label = "<2>"]
}''')
## ------------- ##
## law_char, b. ##
## ------------- ##
check(r'''digraph
{
vcsn_context = "law_char(ab), b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0
0 -> 1 [label = "a"]
0 -> 2 [label = "\\e"]
1 -> F1
1 -> 0 [label = "\\e"]
1 -> 2 [label = "a"]
2 -> 0 [label = "a"]
2 -> 1 [label = "\\e"]
}''', '''digraph
{
vcsn_context = "wordset<char_letters(ab)>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F0
F1
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0
0 -> F0
0 -> 0 [label = "a"]
0 -> 1 [label = "a"]
0 -> 2 [label = "a"]
1 -> F1
1 -> 0 [label = "a"]
1 -> 1 [label = "a"]
1 -> 2 [label = "a"]
2 -> F2
2 -> 0 [label = "a"]
2 -> 1 [label = "a"]
2 -> 2 [label = "a"]
}''')
## ------------------------------------------------- ##
## law_char, z: invalid \e-cycle (weight is not 0). ##
## ------------------------------------------------- ##
check_fail(r'''digraph
{
vcsn_context = "law_char(ab), z"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
3
}
I0 -> 0
0 -> 1 [label = "<2>a"]
0 -> 2 [label = "<-1>\\e"]
1 -> F1
1 -> 0 [label = "<-1>\\e"]
2 -> 1 [label = "<-1>\\e"]
2 -> 3 [label = "<2>a"]
3 -> 0 [label = "<2>a"]
}''')
## ------------- ##
## law_char, z. ##
## ------------- ##
check(r'''digraph
{
vcsn_context = "law_char(ab), z"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
3
}
I0 -> 0
0 -> 1 [label = "<2>a"]
0 -> 2 [label = "<-1>a"]
1 -> F1
1 -> 0 [label = "<-1>\\e"]
2 -> 1 [label = "<-1>\\e"]
2 -> 3 [label = "<2>a"]
3 -> 0 [label = "<2>a"]
}''', '''digraph
{
vcsn_context = "wordset<char_letters(ab)>, z"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
3
}
I0 -> 0
0 -> 1 [label = "<2>a"]
0 -> 2 [label = "<-1>a"]
1 -> F1
1 -> 1 [label = "<-2>a"]
1 -> 2 [label = "a"]
2 -> F2 [label = "<-1>"]
2 -> 1 [label = "<2>a"]
2 -> 2 [label = "<-1>a"]
2 -> 3 [label = "<2>a"]
3 -> 0 [label = "<2>a"]
}''')
## ---------------------------------- ##
## law_char, zmin: invalid \e-cycle. ##
## ---------------------------------- ##
check_fail(r'''digraph
{
vcsn_context = "law_char(ab), zmin"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0 [label = "<0>"]
0 -> 1 [label = "<2>a"]
0 -> 2 [label = "<-1>\\e"]
1 -> F1 [label = "<0>"]
1 -> 0 [label = "<-1>\\e"]
1 -> 2 [label = "<2>a"]
2 -> 0 [label = "<2>a"]
2 -> 1 [label = "<-1>\\e"]
}''')
## ---------------------------- ##
## lan_char, zr: a long cycle. ##
## ---------------------------- ##
# FIXME(ap): with distance, weights are equivalent but not the same
check(r'''digraph
{
vcsn_context = "lan_char(z), expressionset<lal_char(abcd), q>"
rankdir = LR
node [shape = circle]
{
node [shape = point, width = 0]
I
F
}
{ 0 1 2 3 4 }
I -> 0
0 -> 1 [label = "<a>\\e"]
1 -> 2 [label = "<b>\\e"]
2 -> 3 [label = "<c>\\e"]
3 -> 0 [label = "<d>\\e"]
0 -> 4 [label = "z"]
4 -> F
}''', r'''digraph
{
vcsn_context = "letterset<char_letters(z)>, expressionset<letterset<char_letters(abcd)>, q>"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
}
I0 -> 0
0 -> 1 [label = "<(abcd)*>z"]
1 -> F1
}''', [algo for algo in algos if algo != 'distance'])
## ----------------------------------------- ##
## lan_char, zr: remove now-useless states. ##
## ----------------------------------------- ##
# Check that we remove states that _end_ without incoming transitions,
# but leave states that were inaccessible before the elimination of
# the spontaneous transitions.
# FIXME(ap): with distance, inaccessible states get pruned
check(r'''digraph
{
vcsn_context = "lan_char(z), expressionset<lal_char(abcdefgh), q>"
rankdir = LR
node [shape = circle]
{
node [shape = point, width = 0]
I
F
}
{ 0 1 2 3 4 5 6 7 8 9 }
I -> 0
0 -> 3 [label = "<a>\\e"]
0 -> 5 [label = "<b>\\e"]
1 -> 2 [label = "<c>\\e"]
3 -> 4 [label = "<d>\\e"]
5 -> 6 [label = "<e>\\e"]
7 -> 8 [label = "<f>\\e"]
6 -> 9 [label = "<g>\\e"]
8 -> 9 [label = "<h>\\e"]
9 -> F
}''', '''digraph
{
vcsn_context = "letterset<char_letters(z)>, expressionset<letterset<char_letters(abcdefgh)>, q>"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F0
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1 [color = DimGray]
2 [color = DimGray]
}
I0 -> 0
0 -> F0 [label = "<beg>"]
2 -> F2 [label = "<fh>", color = DimGray]
}''', [algo for algo in algos if algo != 'distance'])
## ------------- ##
## lan_char, b. ##
## ------------- ##
check(r'''digraph
{
vcsn_context = "lan_char(ab), b"
I -> 0
0 -> 1 [label = "\\e"]
1 -> 0 [label = "\\e"]
0 -> 4 [label = "a"]
4 -> F
}''', '''digraph
{
vcsn_context = "letterset<char_letters(ab)>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
}
I0 -> 0
0 -> 1 [label = "a"]
1 -> F1
}''')
## ---------------------------- ##
## lat<lan_char, lan_char>, b. ##
## ---------------------------- ##
check(r'''digraph
{
vcsn_context = "lat<lan_char(ab),lan_char(xy)>, b"
I0 -> 0
0 -> 1 [label = "(\\e,\\e)"]
0 -> 1 [label = "(a,x)"]
0 -> 2 [label = "(b,\\e)"]
1 -> F1
1 -> 2 [label = "(\\e,y)"]
2 -> F2
}''', r'''digraph
{
vcsn_context = "lat<nullableset<letterset<char_letters(ab)>>, nullableset<letterset<char_letters(xy)>>>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F0
F1
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0
0 -> F0
0 -> 1 [label = "(a,x)"]
0 -> 2 [label = "(\\e,y), (b,\\e)"]
1 -> F1
1 -> 2 [label = "(\\e,y)"]
2 -> F2
}''')
## ---------------------------- ##
## lat<lan_char, lal_char>, b. ##
## ---------------------------- ##
check(r'''digraph
{
vcsn_context = "lat<lan_char(ab),lal_char(xy)>, b"
I0 -> 0
0 -> 1 [label = "(a,x)"]
0 -> 2 [label = "(b,y)"]
1 -> F1
1 -> 2 [label = "(\\e,y)"]
2 -> F2
}''', r'''digraph
{
vcsn_context = "lat<nullableset<letterset<char_letters(ab)>>, letterset<char_letters(xy)>>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
F1
F2
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
2
}
I0 -> 0
0 -> 1 [label = "(a,x)"]
0 -> 2 [label = "(b,y)"]
1 -> F1
1 -> 2 [label = "(\\e,y)"]
2 -> F2
}''')
## ---------------------- ##
## Forward vs. backward. ##
## ---------------------- ##
for algo in algos:
a = vcsn.context('lan_char(ab), b').expression('a*').thompson()
CHECK_EQ(vcsn.automaton(r'''digraph
{
vcsn_context = "letterset<char_letters(ab)>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I1
F0
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
}
I1 -> 1
0 -> F0
0 -> 0 [label = "a"]
1 -> F1
1 -> 0 [label = "a"]
}''').sort().strip(), a.proper(backward=True, algo=algo).sort().strip())
CHECK_EQ(vcsn.automaton(r'''digraph
{
vcsn_context = "letterset<char_letters(ab)>, b"
rankdir = LR
edge [arrowhead = vee, arrowsize = .6]
{
node [shape = point, width = 0]
I0
I1
F1
}
{
node [shape = circle, style = rounded, width = 0.5]
0
1
}
I0 -> 0
I1 -> 1
0 -> 0 [label = "a"]
0 -> 1 [label = "a"]
1 -> F1
}''').sort().strip(), a.proper(backward=False, algo=algo).sort().strip())
|
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
|
tests/python/proper.py
|
Python
|
gpl-3.0
| 11,408 | 0.006837 |
class Token:
"""
Class representing a token.
kind: the kind of token, e.g. filename, number, other
value: specific instance value, e.g. "/tmp/foo.c", or 5
offset: byte offset from start of parse string
"""
def __init__(self, kind, value=None, offset=None):
self.offset = offset
self.kind = kind
self.value = value
def __eq__(self, o):
""" '==', but it's okay if offset is different"""
if isinstance(o, Token):
# Both are tokens: compare kind and value
# It's okay if offsets are different
return (self.kind == o.kind)
else:
return self.kind == o
def __repr__(self):
return str(self.kind)
def __repr1__(self, indent, sib_num=''):
return self.format(line_prefix=indent, sib_num=sib_num)
def __str__(self):
return self.format(line_prefix='')
def format(self, line_prefix='', sib_num=None):
if sib_num:
sib_num = "%d." % sib_num
else:
sib_num = ''
prefix = ('%s%s' % (line_prefix, sib_num))
offset_opname = '%5s %-10s' % (self.offset, self.kind)
if not self.value:
return "%s%s" % (prefix, offset_opname)
return "%s%s %s" % (prefix, offset_opname, self.value)
def __hash__(self):
return hash(self.kind)
def __getitem__(self, i):
raise IndexError
|
rocky/python3-trepan
|
trepan/processor/parse/tok.py
|
Python
|
gpl-3.0
| 1,426 | 0 |
# Copyright (C) 2015 Ross D Milligan
# GNU GENERAL PUBLIC LICENSE Version 3 (full notice can be found at https://github.com/rdmilligan/SaltwashAR)
class Speaking:
# initialize speaking
def __init__(self, text_to_speech):
self.is_speaking = False
self.text_to_speech = text_to_speech
# text to speech
def _text_to_speech(self, text):
self.is_speaking = True
self.text_to_speech.convert(text)
self.is_speaking = False
|
rdmilligan/SaltwashAR
|
scripts/features/base/speaking.py
|
Python
|
gpl-3.0
| 476 | 0.006303 |
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.
#
# @COPYRIGHT_end
"""@package src.ec2.helpers.query
@copyright Copyright (c) 2012 Institute of Nuclear Physics PAS <http://www.ifj.edu.pl/>
@author Oleksandr Gituliar <gituliar@gmail.com>
"""
from datetime import datetime
import urllib
from ec2.base.auth import _sign_parameters_ver2
def query(parameters, aws_key=None, aws_secret=None, endpoint=None,
method=None, secure=False):
parameters.setdefault('SignatureMethod', 'HmacSHA256')
parameters.setdefault('SignatureVersion', '2')
parameters['AWSAccessKeyId'] = aws_key
parameters['Timestamp'] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
parameters['Version'] = "2012-03-01"
# set Signature
signature = _sign_parameters_ver2(
parameters,
aws_secret,
endpoint=endpoint,
method=method,
)
parameters['Signature'] = signature
# build request
protocol = 'http' if not secure else 'https'
query_parameters = urllib.urlencode(parameters)
if method == 'GET':
request = ("%s://%s/?%s" % (protocol, endpoint, query_parameters),)
elif method == 'POST':
request = ("%s://%s" % (protocol, endpoint), query_parameters)
else:
raise Exception('Unsupported %s method: %s' % (protocol.upper(), method))
response = urllib.urlopen(*request).read()
return request, response
def get_instance_tags(cluster_manager):
instances = cluster_manager.user.vm.get_list()
tags = []
for instance in instances:
tags.append({'resource-id': 'i-' + str(instance['vm_id']),
'key': 'Name',
'resource-type': 'instance',
'value': instance['name']})
return tags
def get_instance_name_tag(cluster_manager, id):
instance = cluster_manager.user.vm.get_by_id({'vm_id': id})
tags = {'resource-id': 'i-' + str(instance['vm_id']),
'key': 'Name',
'resource-type': 'instance',
'value': instance['name']}
return tags
def get_volume_name_tag(cluster_manager, id):
volume = cluster_manager.user.storage_image.get_by_id({'vm_id': id})
tags = {'resource-id': 'i-' + str(volume['storage_image_id']),
'key': 'Name',
'resource-type': 'volume',
'value': volume['name']}
return tags
def get_volume_tags(cluster_manager):
volumes = cluster_manager.user.storage_image.get_list()
tags = []
for volume in volumes:
tags.append({'resource-id': 'vol-' + str(volume['storage_image_id']),
'key': 'Name',
'resource-type': 'volume',
'value': volume['name']})
return tags
|
Dev-Cloud-Platform/Dev-Cloud
|
dev_cloud/cc1/src/ec2/helpers/query.py
|
Python
|
apache-2.0
| 3,363 | 0.000595 |
"""HTTP Client for asyncio."""
import asyncio
import base64
import hashlib
import json
import os
import sys
import traceback
import warnings
from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
from yarl import URL
from . import connector as connector_mod
from . import client_exceptions, client_reqrep, hdrs, http, payload
from .client_exceptions import * # noqa
from .client_exceptions import (ClientError, ClientOSError, ServerTimeoutError,
WSServerHandshakeError)
from .client_reqrep import * # noqa
from .client_reqrep import ClientRequest, ClientResponse
from .client_ws import ClientWebSocketResponse
from .connector import * # noqa
from .connector import TCPConnector
from .cookiejar import CookieJar
from .helpers import (PY_35, CeilTimeout, TimeoutHandle, _BaseCoroMixin,
deprecated_noop, sentinel)
from .http import WS_KEY, WebSocketReader, WebSocketWriter
from .streams import FlowControlDataQueue
__all__ = (client_exceptions.__all__ + # noqa
client_reqrep.__all__ + # noqa
connector_mod.__all__ + # noqa
('ClientSession', 'ClientWebSocketResponse', 'request'))
# 5 Minute default read and connect timeout
DEFAULT_TIMEOUT = 5 * 60
class ClientSession:
"""First-class interface for making HTTP requests."""
_source_traceback = None
_connector = None
requote_redirect_url = True
def __init__(self, *, connector=None, loop=None, cookies=None,
headers=None, skip_auto_headers=None,
auth=None, json_serialize=json.dumps,
request_class=ClientRequest, response_class=ClientResponse,
ws_response_class=ClientWebSocketResponse,
version=http.HttpVersion11,
cookie_jar=None, connector_owner=True, raise_for_status=False,
read_timeout=sentinel, conn_timeout=None,
auto_decompress=True):
implicit_loop = False
if loop is None:
if connector is not None:
loop = connector._loop
else:
implicit_loop = True
loop = asyncio.get_event_loop()
if connector is None:
connector = TCPConnector(loop=loop)
if connector._loop is not loop:
raise RuntimeError(
"Session and connector has to use same event loop")
self._loop = loop
if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))
if implicit_loop and not loop.is_running():
warnings.warn("Creating a client session outside of coroutine is "
"a very dangerous idea", ResourceWarning,
stacklevel=2)
context = {'client_session': self,
'message': 'Creating a client session outside '
'of coroutine'}
if self._source_traceback is not None:
context['source_traceback'] = self._source_traceback
loop.call_exception_handler(context)
if cookie_jar is None:
cookie_jar = CookieJar(loop=loop)
self._cookie_jar = cookie_jar
if cookies is not None:
self._cookie_jar.update_cookies(cookies)
self._connector = connector
self._connector_owner = connector_owner
self._default_auth = auth
self._version = version
self._json_serialize = json_serialize
self._read_timeout = (read_timeout if read_timeout is not sentinel
else DEFAULT_TIMEOUT)
self._conn_timeout = conn_timeout
self._raise_for_status = raise_for_status
self._auto_decompress = auto_decompress
# Convert to list of tuples
if headers:
headers = CIMultiDict(headers)
else:
headers = CIMultiDict()
self._default_headers = headers
if skip_auto_headers is not None:
self._skip_auto_headers = frozenset([istr(i)
for i in skip_auto_headers])
else:
self._skip_auto_headers = frozenset()
self._request_class = request_class
self._response_class = response_class
self._ws_response_class = ws_response_class
def __del__(self, _warnings=warnings):
if not self.closed:
self.close()
_warnings.warn("Unclosed client session {!r}".format(self),
ResourceWarning)
context = {'client_session': self,
'message': 'Unclosed client session'}
if self._source_traceback is not None:
context['source_traceback'] = self._source_traceback
self._loop.call_exception_handler(context)
def request(self, method, url, **kwargs):
"""Perform HTTP request."""
return _RequestContextManager(self._request(method, url, **kwargs))
@asyncio.coroutine
def _request(self, method, url, *,
params=None,
data=None,
json=None,
headers=None,
skip_auto_headers=None,
auth=None,
allow_redirects=True,
max_redirects=10,
encoding=None,
compress=None,
chunked=None,
expect100=False,
read_until_eof=True,
proxy=None,
proxy_auth=None,
timeout=sentinel):
# NOTE: timeout clamps existing connect and read timeouts. We cannot
# set the default to None because we need to detect if the user wants
# to use the existing timeouts by setting timeout to None.
if encoding is not None:
warnings.warn(
"encoding parameter is not supported, "
"please use FormData(charset='utf-8') instead",
DeprecationWarning)
if self.closed:
raise RuntimeError('Session is closed')
if data is not None and json is not None:
raise ValueError(
'data and json parameters can not be used at the same time')
elif json is not None:
data = payload.JsonPayload(json, dumps=self._json_serialize)
if not isinstance(chunked, bool) and chunked is not None:
warnings.warn(
'Chunk size is deprecated #1615', DeprecationWarning)
redirects = 0
history = []
version = self._version
# Merge with default headers and transform to CIMultiDict
headers = self._prepare_headers(headers)
if auth is None:
auth = self._default_auth
# It would be confusing if we support explicit Authorization header
# with `auth` argument
if (headers is not None and
auth is not None and
hdrs.AUTHORIZATION in headers):
raise ValueError("Can't combine `Authorization` header with "
"`auth` argument")
skip_headers = set(self._skip_auto_headers)
if skip_auto_headers is not None:
for i in skip_auto_headers:
skip_headers.add(istr(i))
if proxy is not None:
proxy = URL(proxy)
# timeout is cumulative for all request operations
# (request, redirects, responses, data consuming)
tm = TimeoutHandle(
self._loop,
timeout if timeout is not sentinel else self._read_timeout)
handle = tm.start()
timer = tm.timer()
try:
with timer:
while True:
url = URL(url).with_fragment(None)
cookies = self._cookie_jar.filter_cookies(url)
req = self._request_class(
method, url, params=params, headers=headers,
skip_auto_headers=skip_headers, data=data,
cookies=cookies, auth=auth, version=version,
compress=compress, chunked=chunked,
expect100=expect100, loop=self._loop,
response_class=self._response_class,
proxy=proxy, proxy_auth=proxy_auth, timer=timer,
session=self, auto_decompress=self._auto_decompress)
# connection timeout
try:
with CeilTimeout(self._conn_timeout, loop=self._loop):
conn = yield from self._connector.connect(req)
except asyncio.TimeoutError as exc:
raise ServerTimeoutError(
'Connection timeout '
'to host {0}'.format(url)) from exc
conn.writer.set_tcp_nodelay(True)
try:
resp = req.send(conn)
try:
yield from resp.start(conn, read_until_eof)
except:
resp.close()
conn.close()
raise
except ClientError:
raise
except OSError as exc:
raise ClientOSError(*exc.args) from exc
self._cookie_jar.update_cookies(resp.cookies, resp.url)
# redirects
if resp.status in (
301, 302, 303, 307, 308) and allow_redirects:
redirects += 1
history.append(resp)
if max_redirects and redirects >= max_redirects:
resp.close()
break
else:
resp.release()
# For 301 and 302, mimic IE, now changed in RFC
# https://github.com/kennethreitz/requests/pull/269
if (resp.status == 303 and
resp.method != hdrs.METH_HEAD) \
or (resp.status in (301, 302) and
resp.method == hdrs.METH_POST):
method = hdrs.METH_GET
data = None
if headers.get(hdrs.CONTENT_LENGTH):
headers.pop(hdrs.CONTENT_LENGTH)
r_url = (resp.headers.get(hdrs.LOCATION) or
resp.headers.get(hdrs.URI))
if r_url is None:
# see github.com/aio-libs/aiohttp/issues/2022
break
r_url = URL(
r_url, encoded=not self.requote_redirect_url)
scheme = r_url.scheme
if scheme not in ('http', 'https', ''):
resp.close()
raise ValueError(
'Can redirect only to http or https')
elif not scheme:
r_url = url.join(r_url)
url = r_url
params = None
resp.release()
continue
break
# check response status
if self._raise_for_status:
resp.raise_for_status()
# register connection
if handle is not None:
if resp.connection is not None:
resp.connection.add_callback(handle.cancel)
else:
handle.cancel()
resp._history = tuple(history)
return resp
except:
# cleanup timer
tm.close()
if handle:
handle.cancel()
handle = None
raise
def ws_connect(self, url, *,
protocols=(),
timeout=10.0,
receive_timeout=None,
autoclose=True,
autoping=True,
heartbeat=None,
auth=None,
origin=None,
headers=None,
proxy=None,
proxy_auth=None):
"""Initiate websocket connection."""
return _WSRequestContextManager(
self._ws_connect(url,
protocols=protocols,
timeout=timeout,
receive_timeout=receive_timeout,
autoclose=autoclose,
autoping=autoping,
heartbeat=heartbeat,
auth=auth,
origin=origin,
headers=headers,
proxy=proxy,
proxy_auth=proxy_auth))
@asyncio.coroutine
def _ws_connect(self, url, *,
protocols=(),
timeout=10.0,
receive_timeout=None,
autoclose=True,
autoping=True,
heartbeat=None,
auth=None,
origin=None,
headers=None,
proxy=None,
proxy_auth=None):
if headers is None:
headers = CIMultiDict()
default_headers = {
hdrs.UPGRADE: hdrs.WEBSOCKET,
hdrs.CONNECTION: hdrs.UPGRADE,
hdrs.SEC_WEBSOCKET_VERSION: '13',
}
for key, value in default_headers.items():
if key not in headers:
headers[key] = value
sec_key = base64.b64encode(os.urandom(16))
headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode()
if protocols:
headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ','.join(protocols)
if origin is not None:
headers[hdrs.ORIGIN] = origin
# send request
resp = yield from self.get(url, headers=headers,
read_until_eof=False,
auth=auth,
proxy=proxy,
proxy_auth=proxy_auth)
try:
# check handshake
if resp.status != 101:
raise WSServerHandshakeError(
resp.request_info,
resp.history,
message='Invalid response status',
code=resp.status,
headers=resp.headers)
if resp.headers.get(hdrs.UPGRADE, '').lower() != 'websocket':
raise WSServerHandshakeError(
resp.request_info,
resp.history,
message='Invalid upgrade header',
code=resp.status,
headers=resp.headers)
if resp.headers.get(hdrs.CONNECTION, '').lower() != 'upgrade':
raise WSServerHandshakeError(
resp.request_info,
resp.history,
message='Invalid connection header',
code=resp.status,
headers=resp.headers)
# key calculation
key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, '')
match = base64.b64encode(
hashlib.sha1(sec_key + WS_KEY).digest()).decode()
if key != match:
raise WSServerHandshakeError(
resp.request_info,
resp.history,
message='Invalid challenge response',
code=resp.status,
headers=resp.headers)
# websocket protocol
protocol = None
if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers:
resp_protocols = [
proto.strip() for proto in
resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(',')]
for proto in resp_protocols:
if proto in protocols:
protocol = proto
break
proto = resp.connection.protocol
reader = FlowControlDataQueue(
proto, limit=2 ** 16, loop=self._loop)
proto.set_parser(WebSocketReader(reader), reader)
resp.connection.writer.set_tcp_nodelay(True)
writer = WebSocketWriter(resp.connection.writer, use_mask=True)
except Exception:
resp.close()
raise
else:
return self._ws_response_class(reader,
writer,
protocol,
resp,
timeout,
autoclose,
autoping,
self._loop,
receive_timeout=receive_timeout,
heartbeat=heartbeat)
def _prepare_headers(self, headers):
""" Add default headers and transform it to CIMultiDict
"""
# Convert headers to MultiDict
result = CIMultiDict(self._default_headers)
if headers:
if not isinstance(headers, (MultiDictProxy, MultiDict)):
headers = CIMultiDict(headers)
added_names = set()
for key, value in headers.items():
if key in added_names:
result.add(key, value)
else:
result[key] = value
added_names.add(key)
return result
def get(self, url, *, allow_redirects=True, **kwargs):
"""Perform HTTP GET request."""
return _RequestContextManager(
self._request(hdrs.METH_GET, url,
allow_redirects=allow_redirects,
**kwargs))
def options(self, url, *, allow_redirects=True, **kwargs):
"""Perform HTTP OPTIONS request."""
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, url,
allow_redirects=allow_redirects,
**kwargs))
def head(self, url, *, allow_redirects=False, **kwargs):
"""Perform HTTP HEAD request."""
return _RequestContextManager(
self._request(hdrs.METH_HEAD, url,
allow_redirects=allow_redirects,
**kwargs))
def post(self, url, *, data=None, **kwargs):
"""Perform HTTP POST request."""
return _RequestContextManager(
self._request(hdrs.METH_POST, url,
data=data,
**kwargs))
def put(self, url, *, data=None, **kwargs):
"""Perform HTTP PUT request."""
return _RequestContextManager(
self._request(hdrs.METH_PUT, url,
data=data,
**kwargs))
def patch(self, url, *, data=None, **kwargs):
"""Perform HTTP PATCH request."""
return _RequestContextManager(
self._request(hdrs.METH_PATCH, url,
data=data,
**kwargs))
def delete(self, url, **kwargs):
"""Perform HTTP DELETE request."""
return _RequestContextManager(
self._request(hdrs.METH_DELETE, url,
**kwargs))
def close(self):
"""Close underlying connector.
Release all acquired resources.
"""
if not self.closed:
if self._connector_owner:
self._connector.close()
self._connector = None
return deprecated_noop('ClientSession.close() is a coroutine')
@property
def closed(self):
"""Is client session closed.
A readonly property.
"""
return self._connector is None or self._connector.closed
@property
def connector(self):
"""Connector instance used for the session."""
return self._connector
@property
def cookie_jar(self):
"""The session cookies."""
return self._cookie_jar
@property
def version(self):
"""The session HTTP protocol version."""
return self._version
@property
def loop(self):
"""Session's loop."""
return self._loop
def detach(self):
"""Detach connector from session without closing the former.
Session is switched to closed state anyway.
"""
self._connector = None
def __enter__(self):
warnings.warn("Use async with instead", DeprecationWarning)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
if PY_35:
@asyncio.coroutine
def __aenter__(self):
return self
@asyncio.coroutine
def __aexit__(self, exc_type, exc_val, exc_tb):
yield from self.close()
class _BaseRequestContextManager(_BaseCoroMixin):
__slots__ = ('_resp',)
def __init__(self, coro):
super().__init__(coro)
self._coro = coro
if PY_35:
@asyncio.coroutine
def __aenter__(self):
self._resp = yield from self._coro
return self._resp
class _RequestContextManager(_BaseRequestContextManager):
if PY_35:
@asyncio.coroutine
def __aexit__(self, exc_type, exc, tb):
# We're basing behavior on the exception as it can be caused by
# user code unrelated to the status of the connection. If you
# would like to close a connection you must do that
# explicitly. Otherwise connection error handling should kick in
# and close/recycle the connection as required.
self._resp.release()
class _WSRequestContextManager(_BaseRequestContextManager):
if PY_35:
@asyncio.coroutine
def __aexit__(self, exc_type, exc, tb):
yield from self._resp.close()
class _SessionRequestContextManager(_RequestContextManager):
__slots__ = _RequestContextManager.__slots__ + ('_session', )
def __init__(self, coro, session):
super().__init__(coro)
self._session = session
@asyncio.coroutine
def __iter__(self):
try:
return (yield from self._coro)
except:
self._session.close()
raise
if PY_35:
def __await__(self):
try:
return (yield from self._coro)
except:
self._session.close()
raise
def request(method, url, *,
params=None,
data=None,
json=None,
headers=None,
skip_auto_headers=None,
cookies=None,
auth=None,
allow_redirects=True,
max_redirects=10,
encoding=None,
version=http.HttpVersion11,
compress=None,
chunked=None,
expect100=False,
connector=None,
loop=None,
read_until_eof=True,
proxy=None,
proxy_auth=None):
"""Constructs and sends a request. Returns response object.
method - HTTP method
url - request url
params - (optional) Dictionary or bytes to be sent in the query
string of the new request
data - (optional) Dictionary, bytes, or file-like object to
send in the body of the request
json - (optional) Any json compatibile python object
headers - (optional) Dictionary of HTTP Headers to send with
the request
cookies - (optional) Dict object to send with the request
auth - (optional) BasicAuth named tuple represent HTTP Basic Auth
auth - aiohttp.helpers.BasicAuth
allow_redirects - (optional) If set to False, do not follow
redirects
version - Request HTTP version.
compress - Set to True if request has to be compressed
with deflate encoding.
chunked - Set to chunk size for chunked transfer encoding.
expect100 - Expect 100-continue response from server.
connector - BaseConnector sub-class instance to support
connection pooling.
read_until_eof - Read response until eof if response
does not have Content-Length header.
loop - Optional event loop.
Usage::
>>> import aiohttp
>>> resp = yield from aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()
"""
connector_owner = False
if connector is None:
connector_owner = True
connector = TCPConnector(loop=loop, force_close=True)
session = ClientSession(
loop=loop, cookies=cookies, version=version,
connector=connector, connector_owner=connector_owner)
return _SessionRequestContextManager(
session._request(method, url,
params=params,
data=data,
json=json,
headers=headers,
skip_auto_headers=skip_auto_headers,
auth=auth,
allow_redirects=allow_redirects,
max_redirects=max_redirects,
encoding=encoding,
compress=compress,
chunked=chunked,
expect100=expect100,
read_until_eof=read_until_eof,
proxy=proxy,
proxy_auth=proxy_auth,),
session=session)
|
Eyepea/aiohttp
|
aiohttp/client.py
|
Python
|
apache-2.0
| 26,125 | 0.000153 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ddplot.py can create plots from plot results created using dd_single.py and
dd_time.py
Copyright 2014,2015 Maximilian Weigand
This program 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.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# from memory_profiler import *
from optparse import OptionParser
import os
import numpy as np
from NDimInv.plot_helper import *
import NDimInv.elem as elem
# import dd_single
import NDimInv
# import lib_dd.plot as lDDp
import sip_formats.convert as SC
import matplotlib.pylab as plt
import matplotlib as mpl
def handle_cmd_options():
parser = OptionParser()
parser.add_option("-i", "--dir", type='string', metavar='DIR',
help="dd_single/dd_time result directory default " +
"results",
default="results", dest="result_dir")
parser.add_option("--range", dest="spec_ranges", type="string",
help="Pixel range(s) to plot. Separate by ';' and " +
"start with 1. For example: \"1;2;4;5\". " +
"Also allowed are ranges: \"2-10\", and open ranges: " +
"\"5-\" (default: -1 (all))",
default=None)
# parser.add_option("--nr_cpus", type='int', metavar='NR',
# help="Output directory", default=1,
# dest="nr_cpus")
parser.add_option('-o', "--output", type='str', metavar='DIR',
help="Output directory (default: filtered_results)",
default='filtered_results',
dest="output_dir")
(options, args) = parser.parse_args()
return options, args
def _get_result_type(directory):
"""Use heuristics to determine the type of result dir that we deal with
Possible types are 'ascii' and 'ascii_audit'
"""
if not os.path.isdir(directory):
raise Exception('Directory does not exist: {0}'.format(directory))
if os.path.isdir(directory + os.sep + 'stats_and_rms'):
return 'ascii'
else:
return 'ascii_audit'
def load_ascii_audit_data(directory):
"""We need:
* frequencies
* data (rmag_rpha, cre_cim)
* forward response (rmag_rpha, cre_cim)
* RTD
"""
data = {}
frequencies = np.loadtxt(directory + os.sep + 'frequencies.dat')
data['frequencies'] = frequencies
with open(directory + os.sep + 'data.dat', 'r') as fid:
[fid.readline() for x in range(0, 3)]
header = fid.readline().strip()
index = header.find('format:')
data_format = header[index + 8:].strip()
subdata = np.loadtxt(fid)
temp = SC.convert(data_format, 'rmag_rpha', subdata)
rmag, rpha = SC.split_data(temp)
data['d_rmag'] = rmag
data['d_rpha'] = rpha
temp = SC.convert(data_format, 'cre_cim', subdata)
rmag, rpha = SC.split_data(temp)
data['d_cre'] = rmag
data['d_cim'] = rpha
temp = SC.convert(data_format, 'rre_rim', subdata)
rmag, rpha = SC.split_data(temp)
data['d_rre'] = rmag
data['d_rim'] = rpha
with open(directory + os.sep + 'f.dat', 'r') as fid:
[fid.readline() for x in range(0, 3)]
header = fid.readline().strip()
index = header.find('format:')
data_format = header[index + 8:].strip()
subdata = np.loadtxt(fid)
temp = SC.convert(data_format, 'rmag_rpha', subdata)
rmag, rpha = SC.split_data(temp)
data['f_rmag'] = rmag
data['f_rpha'] = rpha
temp = SC.convert(data_format, 'cre_cim', subdata)
rmag, rpha = SC.split_data(temp)
data['f_cre'] = rmag
data['f_cim'] = rpha
temp = SC.convert(data_format, 'rre_rim', subdata)
rmag, rpha = SC.split_data(temp)
data['f_rre'] = rmag
data['f_rim'] = rpha
data['rtd'] = np.atleast_2d(
np.loadtxt(directory + os.sep + 'm_i.dat', skiprows=4))
data['tau'] = np.loadtxt(directory + os.sep + 'tau.dat', skiprows=4)
return data
def load_ascii_data(directory):
data = {}
frequencies = np.loadtxt(directory + os.sep + 'frequencies.dat')
data['frequencies'] = frequencies
data_format = open(
directory + os.sep + 'data_format.dat', 'r').readline().strip()
subdata = np.loadtxt(directory + os.sep + 'data.dat')
temp = SC.convert(data_format, 'rmag_rpha', subdata)
rmag, rpha = SC.split_data(temp)
data['d_rmag'] = rmag
data['d_rpha'] = rpha
temp = SC.convert(data_format, 'cre_cim', subdata)
rmag, rpha = SC.split_data(temp)
data['d_cre'] = rmag
data['d_cim'] = rpha
temp = SC.convert(data_format, 'rre_rim', subdata)
rmag, rpha = SC.split_data(temp)
data['d_rre'] = rmag
data['d_rim'] = rpha
f_format = open(
directory + os.sep + 'f_format.dat', 'r').readline().strip()
subdata = np.loadtxt(directory + os.sep + 'f.dat')
temp = SC.convert(f_format, 'rmag_rpha', subdata)
rmag, rpha = SC.split_data(temp)
data['f_rmag'] = rmag
data['f_rpha'] = rpha
temp = SC.convert(f_format, 'cre_cim', subdata)
rmag, rpha = SC.split_data(temp)
data['f_cre'] = rmag
data['f_cim'] = rpha
temp = SC.convert(f_format, 'rre_rim', subdata)
rmag, rpha = SC.split_data(temp)
data['f_rre'] = rmag
data['f_rim'] = rpha
data['rtd'] = np.atleast_2d(
np.loadtxt(directory + os.sep + 'stats_and_rms' + os.sep +
'm_i_results.dat'))
data['tau'] = np.loadtxt(directory + os.sep + 'tau.dat')
return data
def extract_indices_from_range_str(filter_string, max_index=None):
"""
Extract indices (e.g. for spectra or pixels) from a range string. The
string must have the following format: Separate different ranges by ';',
first index is 1.
If max_index is provided, open ranges are allowed, as well as "-1" for all.
Examples:
"1;2;4;5"
"2-10"
"5-"
"-1"
Parameters
----------
filter_string : string to be parsed according to the format specifications
¦ ¦ ¦ ¦ above
max_index : (default: None). Provide the maximum index for the ranges to
¦ ¦ ¦ allow open ranges and "-1" for all indices
"""
if(filter_string is None):
return None
sections = filter_string.split(';')
filter_ids = []
# now look for ranges and expand if necessary
for section in sections:
filter_range = section.split('-')
if(len(filter_range) == 2):
start = filter_range[0]
end = filter_range[1]
# check for an open range, e.g. 4-
if(end == ''):
if(max_index is not None):
end = max_index
else:
continue
filter_ids += list(range(int(start) - 1, int(end)))
else:
filter_ids.append(int(section) - 1)
return filter_ids
def plot_data(data, options):
nr_specs = data['d_rmag'].shape[0]
indices = extract_indices_from_range_str(options.spec_ranges,
nr_specs)
if indices is None:
indices = list(range(0, nr_specs))
frequencies = data['frequencies']
for index in indices:
fig, axes = plt.subplots(1, 5, figsize=(14, 3))
# Magnitude and phase values
ax = axes[0]
ax.semilogx(frequencies, data['d_rmag'][index, :], '.', color='k')
ax.semilogx(frequencies, data['f_rmag'][index, :], '-', color='k')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r'$|\rho|~[\Omega m]$')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
ax = axes[1]
ax.semilogx(frequencies, -data['d_rpha'][index, :], '.', color='k')
ax.semilogx(frequencies, -data['f_rpha'][index, :], '-', color='k')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r'$-\phi~[mrad]$')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
# self._mark_tau_parameters_f(nr, ax, it)
# real and imaginary parts
ax = axes[2]
ax.semilogx(frequencies, data['d_rre'][index, :], '.', color='k')
ax.semilogx(frequencies, data['f_rre'][index, :], '-', color='k')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\rho'~[\Omega m]$", color='k')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax = axes[2].twinx()
ax.semilogx(frequencies, data['d_cre'][index, :], '.', color='gray')
ax.semilogx(frequencies, data['f_cre'][index, :], '-', color='gray')
ax.set_ylabel(r"$-\sigma'~[S/m]$", color='gray')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax = axes[3]
ax.semilogx(frequencies, -data['d_rim'][index, :], '.', color='k',
label='data')
ax.semilogx(frequencies, -data['f_rim'][index, :], '-', color='k',
label='fit')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\rho''~[\Omega m]$", color='k')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax = axes[3].twinx()
ax.semilogx(frequencies, data['d_cim'][index, :], '.', color='gray',
label='data')
ax.semilogx(frequencies, data['f_cim'][index, :], '-', color='gray',
label='fit')
# ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\sigma''~[S/m]$", color='gray')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
# self._plot_rtd(nr, axes[nr, 4], M[m], it)
ax = axes[4]
ax.semilogx(data['tau'], data['rtd'][index, :], '.-', color='k')
ax.set_xlabel(r'$\tau~[s]$')
ax.set_ylabel(r'$log_{10}(m)$')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
fig.tight_layout()
fig.savefig('spec_{0:03}.png'.format(index), dpi=300)
def _plot_rtd(self, nr, ax, m, it):
ax.semilogx(it.Data.obj.tau, m[1:], '.-', color='k')
ax.set_xlim(it.Data.obj.tau.min(), it.Data.obj.tau.max())
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=5))
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
self._mark_tau_parameters_tau(nr, ax, it)
ax.invert_xaxis()
# mark limits of data frequencies, converted into the tau space
tau_min = np.min(it.Model.obj.tau)
tau_max = np.max(it.Model.obj.tau)
d_fmin = np.min(it.Data.obj.frequencies)
d_fmax = np.max(it.Data.obj.frequencies)
t_fmin = 1 / (2 * np.pi * d_fmin)
t_fmax = 1 / (2 * np.pi * d_fmax)
ax.axvline(t_fmin, c='y', alpha=0.7)
ax.axvline(t_fmax, c='y', alpha=0.7)
ax.axvspan(tau_min, t_fmax, hatch='/', color='gray', alpha=0.5)
ax.axvspan(t_fmin, tau_max, hatch='/', color='gray', alpha=0.5,
label='area outside data range')
ax.set_xlabel(r'$\tau~[s]$')
ax.set_ylabel(r'$log_{10}(m)$')
# print lambda value in title
title_string = r'$\lambda:$ '
for lam in it.lams:
if(type(lam) == list):
lam = lam[0]
if(isinstance(lam, float) or isinstance(lam, int)):
title_string += '{0} '.format(lam)
else:
# individual lambdas
title_string += '{0} '.format(
lam[m_indices[nr], m_indices[nr]])
ax.set_title(title_string)
def _plot_cre_cim(self, nr, axes, orig_data, fit_data, it):
cre_cim_orig = sip_convert.convert(it.Data.obj.data_format,
'cre_cim',
orig_data)
cre_cim_fit = sip_convert.convert(it.Data.obj.data_format,
'cre_cim',
fit_data)
frequencies = it.Data.obj.frequencies
ax = axes[0]
ax.semilogx(frequencies, cre_cim_orig[:, 0], '.', color='gray')
ax.semilogx(frequencies, cre_cim_fit[:, 0], '-', color='gray')
# ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\sigma'~[S/m]$", color='gray')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax = axes[1]
ax.semilogx(frequencies, cre_cim_orig[:, 1], '.', color='gray',
label='data')
ax.semilogx(frequencies, cre_cim_fit[:, 1], '-', color='gray',
label='fit')
# ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\sigma''~[S/m]$", color='gray')
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
def _plot_rre_rim(self, nr, axes, orig_data, fit_data, it):
rre_rim_orig = sip_convert.convert(it.Data.obj.data_format,
'rre_rim',
orig_data)
rre_rim_fit = sip_convert.convert(it.Data.obj.data_format,
'rre_rim',
fit_data)
frequencies = it.Data.obj.frequencies
ax = axes[0]
ax.semilogx(frequencies, rre_rim_orig[:, 0], '.', color='k')
ax.semilogx(frequencies, rre_rim_fit[:, 0], '-', color='k')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\rho'~[\Omega m]$")
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
ax = axes[1]
ax.semilogx(frequencies, -rre_rim_orig[:, 1], '.', color='k',
label='data')
ax.semilogx(frequencies, -rre_rim_fit[:, 1], '-', color='k',
label='fit')
ax.set_xlabel('frequency [Hz]')
ax.set_ylabel(r"$-\rho''~[\Omega m]$")
ax.xaxis.set_major_locator(mpl.ticker.LogLocator(numticks=4))
self._mark_tau_parameters_f(nr, ax, it)
# legend is created from first plot
if nr == 0:
ax.legend(loc="upper center", ncol=5,
bbox_to_anchor=(0, 0, 1, 1),
bbox_transform=ax.get_figure().transFigure)
leg = ax.get_legend()
ltext = leg.get_texts()
plt.setp(ltext, fontsize='6')
def _mark_tau_parameters_tau(self, nr, ax, it):
# mark relaxation time parameters
# mark tau_peak
for index in range(1, 3):
try:
tpeak = it.stat_pars['tau_peak{0}'.format(index)][nr]
if(not np.isnan(tpeak)):
ax.axvline(x=10**tpeak, color='k', label=r'$\tau_{peak}^' +
'{0}'.format(index) + '$',
linestyle='dashed')
except:
pass
try:
ax.axvline(x=10**it.stat_pars['tau_50'][nr], color='g',
label=r'$\tau_{50}$')
except:
pass
try:
ax.axvline(x=10**it.stat_pars['tau_mean'][nr], color='c',
label=r'$\tau_{mean}$')
except:
pass
def _mark_tau_parameters_f(self, nr, ax, it):
# mark relaxation time parameters
# mark tau_peak
for index in range(1, 3):
try:
fpeak = it.stat_pars['f_peak{0}'.format(index)][nr]
if(not np.isnan(fpeak)):
ax.axvline(x=fpeak, color='k', label=r'$\tau_{peak}^' +
'{0}'.format(index) + '$',
linestyle='dashed')
except:
pass
try:
ax.axvline(x=it.stat_pars['f_50'][nr], color='g',
label=r'$\tau_{50}$')
except:
pass
try:
ax.axvline(x=it.stat_pars['f_mean'][nr], color='c',
label=r'$\tau_{mean}$')
except:
pass
def load_data(options):
result_type = _get_result_type(options.result_dir)
loading_funcs = {'ascii': load_ascii_data,
'ascii_audit': load_ascii_audit_data
}
data = loading_funcs[result_type](options.result_dir)
return data
if __name__ == '__main__':
options, _ = handle_cmd_options()
data = load_data(options)
plot_data(data, options)
|
m-weigand/ccd_tools
|
src/ddplot/ddplot.py
|
Python
|
gpl-3.0
| 16,512 | 0.000666 |
"""Network subnets."""
|
softlayer/softlayer-python
|
SoftLayer/CLI/subnet/__init__.py
|
Python
|
mit
| 23 | 0 |
#!/usr/bin/env python3
# encoding: utf-8
from nose import with_setup
from tests.utils import *
@with_setup(usual_setup_func, usual_teardown_func)
def test_negative():
create_file('xxx', 'b.png')
create_file('xxx', 'a.png')
create_file('xxx', 'a')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 3
assert footer['total_lint_size'] == 0
assert footer['duplicates'] == 0
@with_setup(usual_setup_func, usual_teardown_func)
def test_positive():
create_file('xxx', 'a.png')
create_file('xxx', 'a.jpg')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 2
assert footer['total_lint_size'] == 3
assert footer['duplicates'] == 1
|
SeeSpotRun/rmlint
|
tests/test_options/test_match_without_extension.py
|
Python
|
gpl-3.0
| 718 | 0.001393 |
import GPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# ~~~~WARNING: ONLY SUPPORT FOR 1D RIGHT NOW~~~~ #
# TODO
def batch():
pass
# Calculates GP from input and output vectors X and Y respectively
def calcGP(X, Y, kernel='rbf', variance=1., lengthscale=1.):
# Reshape in 1D Case to proper column vector form
if(len(X.shape) == 1):
X = np.reshape(X, (len(X),1))
if(len(Y.shape) == 1):
Y = np.reshape(Y, (len(Y),1))
if(kernel=='rbf'):
kernel = GPy.kern.RBF(input_dim=1, variance=variance, lengthscale=lengthscale)
m = GPy.models.GPRegression(X,Y,kernel)
return m
else:
print('Kernel is not supported, please use one that is supported or use the default RBF Kernel')
return None
# Updates GP with a set of new function evaluations Y at points X
def updateGP(model, kernel, Xnew, Ynew):
# Reshape in 1D Case
if(len(Xnew.shape) == 1):
Xnew = np.reshape(X, (len(Xnew),1))
if(len(Ynew.shape) == 1):
Ynew = np.reshape(Y, (len(Ynew),1))
X = np.append(model.X, Xnew, 0)
Y = np.append(model.Y, Ynew, 0)
m = GPy.models.GPRegression(X,Y,kernel)
return m
# Using Expected Improvement, send out a number of further evaluations
# -batchsize = number of new evals
# -fidelity = number of points used to estimate EI
# -bounds = determines how new evals points are spaced
def batchNewEvals_EI(model, bounds=1, batchsize=50, fidelity=100):
P, ei = compute_ei(model, fidelity)
idx = np.argmax(ei)
xnew = P[idx]
X = np.linspace(xnew-bounds, xnew+bounds, num=batchsize)
return X
# Calculates EI given means mu and variances sigma2
def compute_ei_inner(ybest, mu, sigma2):
sigma = np.sqrt(sigma2)
u = (ybest - mu) / sigma
ucdf = norm.cdf(u)
updf = norm.pdf(u)
ei = sigma * (updf + u * ucdf)
return ei
# Takes in GP model from GPy and computes EI at points P
# We are assuming minimization, and thus ybest represents the smallest point we have so far
def compute_ei(model, numsamples):
P = np.linspace(model.X[0], model.X[-1], num=numsamples)
ybest = np.amax(model.Y)
P = np.reshape(P, [len(P), 1])
mu, sigma2 = model.predict(P)
return P, compute_ei_inner(ybest, mu, sigma2)
def plotGP(model):
fig = model.plot()
regfig = GPy.plotting.show(fig)
regfig.savefig('GPmodel.png')
|
ericlee0803/surrogate-GCP
|
gp/GPhelpers.py
|
Python
|
bsd-3-clause
| 2,253 | 0.030626 |
"""
=================================
Gaussian Mixture Model Ellipsoids
=================================
Plot the confidence ellipsoids of a mixture of two Gaussians with EM
and variational Dirichlet process.
Both models have access to five components with which to fit the
data. Note that the EM model will necessarily use all five components
while the DP model will effectively only use as many as are needed for
a good fit. This is a property of the Dirichlet Process prior. Here we
can see that the EM model splits some components arbitrarily, because it
is trying to fit too many components, while the Dirichlet Process model
adapts it number of state automatically.
This example doesn't show it, as we're in a low-dimensional space, but
another advantage of the Dirichlet process model is that it can fit
full covariance matrices effectively even when there are less examples
per cluster than there are dimensions in the data, due to
regularization properties of the inference algorithm.
"""
import itertools
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import mixture
# Number of samples per component
n_samples = 500
# Generate random sample, two components
np.random.seed(0)
C = np.array([[0., -0.1], [1.7, .4]])
X = np.r_[np.dot(np.random.randn(n_samples, 2), C),
.7 * np.random.randn(n_samples, 2) + np.array([-6, 3])]
# Fit a mixture of Gaussians with EM using five components
gmm = mixture.GMM(n_components=5, covariance_type='full')
gmm.fit(X)
# Fit a Dirichlet process mixture of Gaussians using five components
dpgmm = mixture.DPGMM(n_components=5, covariance_type='full')
dpgmm.fit(X)
color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm'])
for i, (clf, title) in enumerate([(gmm, 'GMM'),
(dpgmm, 'Dirichlet Process GMM')]):
splot = plt.subplot(2, 1, 1 + i)
Y_ = clf.predict(X)
for i, (mean, covar, color) in enumerate(zip(
clf.means_, clf._get_covars(), color_iter)):
v, w = linalg.eigh(covar)
u = w[0] / linalg.norm(w[0])
# as the DP will not use every component it has access to
# unless it needs it, we shouldn't plot the redundant
# components.
if not np.any(Y_ == i):
continue
plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color)
# Plot an ellipse to show the Gaussian component
angle = np.arctan(u[1] / u[0])
angle = 180 * angle / np.pi # convert to degrees
ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color)
ell.set_clip_box(splot.bbox)
ell.set_alpha(0.5)
splot.add_artist(ell)
plt.xlim(-10, 10)
plt.ylim(-3, 6)
plt.xticks(())
plt.yticks(())
plt.title(title)
plt.show()
|
RPGOne/Skynet
|
scikit-learn-c604ac39ad0e5b066d964df3e8f31ba7ebda1e0e/examples/mixture/plot_gmm.py
|
Python
|
bsd-3-clause
| 2,817 | 0 |
"""
Copyright (c) 2016 Genome Research Ltd.
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.
"""
from __future__ import division
import tempfile
import urllib
import pandas
from mupit.gtf import convert_gtf
from mupit.util import is_url
def get_default_rates(rates_url="http://www.nature.com/ng/journal/v46/n9/extref/ng.3050-S2.xls",
gencode_url="ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_19/gencode.v19.annotation.gtf.gz"):
""" obtain the table of mutation rates from the Samocha et al paper
Rates for all genes can be obtained from the supplementary material of
Samocha et al. Nature Genetics 2014 doi:10.1038/ng.3050
Args:
rates_url: url to supplementary mutation rates table
gencode_url: url to gencode, or local path. This is required to identify
chromosomes for the genes in the rates data, since we need to know
the chromosome in order to corrrect rates on chromosome X.
Returns:
dataframe of mutation rates, with an extra column for summed lof rate
"""
rates = pandas.read_excel(rates_url, sheetname="mutation_probabilities")
# convert rates from log-scaled values, so we can later multiply by the
# number of transmissions
columns = ["syn", "mis", "non", "splice_site", "frameshift"]
rates[columns] = 10 ** rates[columns]
# sort out the required columns and names.
rates["hgnc"] = rates["gene"]
gencode = load_gencode(gencode_url)
recode = dict(zip(gencode["hgnc"], gencode["chrom"]))
rates["chrom"] = rates["hgnc"].map(recode)
rates = rates[["hgnc", "chrom", "syn", "mis", "splice_site", "frameshift", "non"]]
return rates
def load_gencode(path):
""" load gencode table with HGNC symbols and chromosome coordinates
Args:
path: path to gzipped tab-separated table of gencode gene entries. This
can be either a url, or local path.
Returns:
pandas dataframe of HGNC symbols and genome coordiantes
"""
gencode = convert_gtf(path)
# restrict outselves to protein coding genes (or genes which are protein
# coding in at least some individuals)
gencode = gencode[gencode["gene_type"].isin(["protein_coding",
"polymorphic_pseudogene"])]
gencode = gencode[gencode["feature"] == "gene"]
# get the required column names, and strip out all unnecessary columns
gencode["hgnc"] = gencode["gene_name"]
gencode["chrom"] = [ x.strip("chr") for x in gencode["seqname"].astype(str) ]
gencode = gencode[["hgnc", "chrom", "start", "end"]].copy()
return gencode
def get_expected_mutations(rates, male, female):
""" gets numbers of expected mutation per gene
Loads gene-based mutation rates, in order to determine the expected number
of mutations per gene, given the number of studied probands and adjusts for
sex-chromosome transmissions.
This defaults to the gene-based mutation rates from Nature Genetics
46:944-950 (2014) doi:10.1038/ng.3050, but we can pass in other gene-based
mutation rate datasets.
Args:
rates: pandas dataframe containing per-gene mutation
male: number of male probands in the dataset
female: number of female probands in the dataset
Returns:
a dataframe of mutation rates for genes under different mutation
classes.
"""
if rates is None:
rates = get_default_rates()
autosomal = 2 * (male + female)
expected = rates[["hgnc", "chrom"]].copy()
# account for how different pandas versions sum series with only NA
kwargs = {}
if pandas.__version__ >= '0.22.0':
kwargs = {'min_count': 1}
# get the number of expected mutations, given the number of transmissions
expected["lof_indel"] = rates["frameshift"] * autosomal
expected["lof_snv"] = (rates[["non", "splice_site"]].sum(axis=1, skipna=True, **kwargs)) * autosomal
expected["missense_indel"] = (rates["frameshift"] / 9) * autosomal
expected["missense_snv"] = rates["mis"] * autosomal
expected["synonymous_snv"] = rates["syn"] * autosomal
# correct for the known ratio of indels to nonsense, and for transmissions
# on the X-chromosome
expected = adjust_indel_rates(expected)
expected = correct_for_x_chrom(expected, male, female)
# subset to the columns we need to estimate enrichment probabilities
expected = expected[["hgnc", "chrom", "lof_indel", "lof_snv",
"missense_indel", "missense_snv", "synonymous_snv"]]
return expected
def correct_for_x_chrom(expected, male_n, female_n):
""" correct mutations rates for sex-chromosome transmission rates
Args:
expected: gene-based data frame, containing rates for different mutation
classes.
male_n: number of trios with male offspring
female_n: number of trios with female offspring
Returns:
a dataframe of mutation rates for genes under different mutation
classes.
"""
# Calculate the number of transmissions for autosomal, male and female
# transmissions. The number of transmissions from males is equal to the
# number of female probands (since only females receive a chrX from their
# fathers). Likewise, all offspring receive a chrX from their mothers, so
# the number of transmissions from females equals the number of probands.
autosomal = 2 * (male_n + female_n)
female_transmissions = male_n + female_n
male_transmissions = female_n
# get scaling factors using the alpha from the most recent SFHS (Scottish
# Family Health Study) phased de novo data.
alpha = 3.4
male_factor = 2 / (1 + (1 / alpha))
female_factor = 2 / (1 + alpha)
# correct the non-PAR chrX genes for fewer transmissions and lower rate
# (dependent on alpha)
chrX = expected["chrom"].isin(["X", "chrX"])
x_factor = ((male_transmissions * male_factor) + (female_transmissions * female_factor)) / autosomal
x_factor = pandas.Series([x_factor] * len(chrX), index=expected.index)
x_factor[~chrX] = 1
expected["missense_snv"] *= x_factor
expected["missense_indel"] *= x_factor
expected["lof_snv"] *= x_factor
expected["lof_indel"] *= x_factor
expected["synonymous_snv"] *= x_factor
return expected
def adjust_indel_rates(expected):
""" adapt indel rates for lower rate estimate from validated de novos
The indel mutation rates from Samocha et al., Nature Genetics 46:944-950
assume that the overall indel mutation rate is 1.25-fold greater than the
overall nonsense mutation rate, ie there are 1.25 times as many frameshifts
as nonsense mutations. We have our own estimates for the ratio, derived from
our de novo validation efforts, which we shall apply in place of the Samocha
et al ratios.
Args:
rates: data frame of mutation rates.
Returns:
the rates data frame, with adjusted indel rates.
"""
# the following numbers were derived from the DDD 4K dataset.
nonsense_n = 411
frameshift_n = 610
ddd_ratio = frameshift_n / nonsense_n
samocha_ratio = 1.25 # Nature Genetics 46:944-950 frameshift to nonsense ratio
# correct back from using the Samocha et al. ratio
expected["missense_indel"] /= samocha_ratio
expected["lof_indel"] /= samocha_ratio
# adjust the indel rates for the DDD indel ratio
expected["missense_indel"] *= ddd_ratio
expected["lof_indel"] *= ddd_ratio
return expected
|
jeremymcrae/mupit
|
mupit/mutation_rates.py
|
Python
|
mit
| 8,652 | 0.007397 |
# -*- coding: utf-8 -*-
# flake8: noqa
import datetime
import logging
import json
import os.path
import prison
import urllib.parse
from .util import EAException
from .util import lookup_es_key
from .util import ts_add
kibana_default_timedelta = datetime.timedelta(minutes=10)
kibana5_kibana6_versions = frozenset(['5.6', '6.0', '6.1', '6.2', '6.3', '6.4', '6.5', '6.6', '6.7', '6.8'])
kibana7_versions = frozenset(['7.0', '7.1', '7.2', '7.3'])
def generate_kibana_discover_url(rule, match):
''' Creates a link for a kibana discover app. '''
discover_app_url = rule.get('kibana_discover_app_url')
if not discover_app_url:
logging.warning(
'Missing kibana_discover_app_url for rule %s' % (
rule.get('name', '<MISSING NAME>')
)
)
return None
kibana_version = rule.get('kibana_discover_version')
if not kibana_version:
logging.warning(
'Missing kibana_discover_version for rule %s' % (
rule.get('name', '<MISSING NAME>')
)
)
return None
index = rule.get('kibana_discover_index_pattern_id')
if not index:
logging.warning(
'Missing kibana_discover_index_pattern_id for rule %s' % (
rule.get('name', '<MISSING NAME>')
)
)
return None
columns = rule.get('kibana_discover_columns', ['_source'])
filters = rule.get('filter', [])
if 'query_key' in rule:
query_keys = rule.get('compound_query_key', [rule['query_key']])
else:
query_keys = []
timestamp = lookup_es_key(match, rule['timestamp_field'])
timeframe = rule.get('timeframe', kibana_default_timedelta)
from_timedelta = rule.get('kibana_discover_from_timedelta', timeframe)
from_time = ts_add(timestamp, -from_timedelta)
to_timedelta = rule.get('kibana_discover_to_timedelta', timeframe)
to_time = ts_add(timestamp, to_timedelta)
if kibana_version in kibana5_kibana6_versions:
globalState = kibana6_disover_global_state(from_time, to_time)
appState = kibana_discover_app_state(index, columns, filters, query_keys, match)
elif kibana_version in kibana7_versions:
globalState = kibana7_disover_global_state(from_time, to_time)
appState = kibana_discover_app_state(index, columns, filters, query_keys, match)
else:
logging.warning(
'Unknown kibana discover application version %s for rule %s' % (
kibana_version,
rule.get('name', '<MISSING NAME>')
)
)
return None
return "%s?_g=%s&_a=%s" % (
os.path.expandvars(discover_app_url),
urllib.parse.quote(globalState),
urllib.parse.quote(appState)
)
def kibana6_disover_global_state(from_time, to_time):
return prison.dumps( {
'refreshInterval': {
'pause': True,
'value': 0
},
'time': {
'from': from_time,
'mode': 'absolute',
'to': to_time
}
} )
def kibana7_disover_global_state(from_time, to_time):
return prison.dumps( {
'filters': [],
'refreshInterval': {
'pause': True,
'value': 0
},
'time': {
'from': from_time,
'to': to_time
}
} )
def kibana_discover_app_state(index, columns, filters, query_keys, match):
app_filters = []
if filters:
bool_filter = { 'must': filters }
app_filters.append( {
'$state': {
'store': 'appState'
},
'bool': bool_filter,
'meta': {
'alias': 'filter',
'disabled': False,
'index': index,
'key': 'bool',
'negate': False,
'type': 'custom',
'value': json.dumps(bool_filter, separators=(',', ':'))
},
} )
for query_key in query_keys:
query_value = lookup_es_key(match, query_key)
if query_value is None:
app_filters.append( {
'$state': {
'store': 'appState'
},
'exists': {
'field': query_key
},
'meta': {
'alias': None,
'disabled': False,
'index': index,
'key': query_key,
'negate': True,
'type': 'exists',
'value': 'exists'
}
} )
else:
app_filters.append( {
'$state': {
'store': 'appState'
},
'meta': {
'alias': None,
'disabled': False,
'index': index,
'key': query_key,
'negate': False,
'params': {
'query': query_value,
'type': 'phrase'
},
'type': 'phrase',
'value': str(query_value)
},
'query': {
'match': {
query_key: {
'query': query_value,
'type': 'phrase'
}
}
}
} )
return prison.dumps( {
'columns': columns,
'filters': app_filters,
'index': index,
'interval': 'auto'
} )
|
Yelp/elastalert
|
elastalert/kibana_discover.py
|
Python
|
apache-2.0
| 5,644 | 0.003189 |
# -*- coding: utf-8 -*-
# Copyright (c) 2006 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the VCS status monitor thread class for Subversion.
"""
from __future__ import unicode_literals
import os
import pysvn
from VCS.StatusMonitorThread import VcsStatusMonitorThread
import Preferences
class SvnStatusMonitorThread(VcsStatusMonitorThread):
"""
Class implementing the VCS status monitor thread class for Subversion.
"""
def __init__(self, interval, project, vcs, parent=None):
"""
Constructor
@param interval new interval in seconds (integer)
@param project reference to the project object (Project)
@param vcs reference to the version control object
@param parent reference to the parent object (QObject)
"""
VcsStatusMonitorThread.__init__(self, interval, project, vcs, parent)
def _performMonitor(self):
"""
Protected method implementing the monitoring action.
This method populates the statusList member variable
with a list of strings giving the status in the first column and the
path relative to the project directory starting with the third column.
The allowed status flags are:
<ul>
<li>"A" path was added but not yet comitted</li>
<li>"M" path has local changes</li>
<li>"O" path was removed</li>
<li>"R" path was deleted and then re-added</li>
<li>"U" path needs an update</li>
<li>"Z" path contains a conflict</li>
<li>" " path is back at normal</li>
</ul>
@return tuple of flag indicating successful operation (boolean) and
a status message in case of non successful operation (string)
"""
self.shouldUpdate = False
client = pysvn.Client()
client.exception_style = 1
client.callback_get_login = \
self.__clientLoginCallback
client.callback_ssl_server_trust_prompt = \
self.__clientSslServerTrustPromptCallback
cwd = os.getcwd()
os.chdir(self.projectDir)
try:
allFiles = client.status(
'.', recurse=True, get_all=True, ignore=True,
update=not Preferences.getVCS("MonitorLocalStatus"))
states = {}
for file in allFiles:
uptodate = True
if file.repos_text_status != pysvn.wc_status_kind.none:
uptodate = uptodate and \
file.repos_text_status != pysvn.wc_status_kind.modified
if file.repos_prop_status != pysvn.wc_status_kind.none:
uptodate = uptodate and \
file.repos_prop_status != pysvn.wc_status_kind.modified
status = ""
if not uptodate:
status = "U"
self.shouldUpdate = True
elif file.text_status == pysvn.wc_status_kind.conflicted or \
file.prop_status == pysvn.wc_status_kind.conflicted:
status = "Z"
elif file.text_status == pysvn.wc_status_kind.deleted or \
file.prop_status == pysvn.wc_status_kind.deleted:
status = "O"
elif file.text_status == pysvn.wc_status_kind.modified or \
file.prop_status == pysvn.wc_status_kind.modified:
status = "M"
elif file.text_status == pysvn.wc_status_kind.added or \
file.prop_status == pysvn.wc_status_kind.added:
status = "A"
elif file.text_status == pysvn.wc_status_kind.replaced or \
file.prop_status == pysvn.wc_status_kind.replaced:
status = "R"
if status:
states[file.path] = status
try:
if self.reportedStates[file.path] != status:
self.statusList.append(
"{0} {1}".format(status, file.path))
except KeyError:
self.statusList.append(
"{0} {1}".format(status, file.path))
for name in list(self.reportedStates.keys()):
if name not in states:
self.statusList.append(" {0}".format(name))
self.reportedStates = states
res = True
statusStr = self.tr(
"Subversion status checked successfully (using pysvn)")
except pysvn.ClientError as e:
res = False
statusStr = e.args[0]
os.chdir(cwd)
return res, statusStr
def __clientLoginCallback(self, realm, username, may_save):
"""
Private method called by the client to get login information.
@param realm name of the realm of the requested credentials (string)
@param username username as supplied by subversion (string)
@param may_save flag indicating, that subversion is willing to save
the answers returned (boolean)
@return tuple of four values (retcode, username, password, save).
Retcode should be True, if username and password should be used
by subversion, username and password contain the relevant data
as strings and save is a flag indicating, that username and
password should be saved. Always returns (False, "", "", False).
"""
return (False, "", "", False)
def __clientSslServerTrustPromptCallback(self, trust_dict):
"""
Private method called by the client to request acceptance for a
ssl server certificate.
@param trust_dict dictionary containing the trust data
@return tuple of three values (retcode, acceptedFailures, save).
Retcode should be true, if the certificate should be accepted,
acceptedFailures should indicate the accepted certificate failures
and save should be True, if subversion should save the certificate.
Always returns (False, 0, False).
"""
return (False, 0, False)
|
testmana2/test
|
Plugins/VcsPlugins/vcsPySvn/SvnStatusMonitorThread.py
|
Python
|
gpl-3.0
| 6,360 | 0.00173 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2011 Thomas Schreiber
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# by Thomas Schreiber <ubiquill@gmail.com>
#
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from view.changesUi import Ui_changeSummary
import string
class ChangeWin(QDialog):
"""A QDialog that lists changes before they are commited.
:param QDialog: Parent class.
"""
def __init__(self, parent):
"""Initialize ChangeWin.
:param parent: Caller.
"""
QDialog.__init__(self, parent)
self.ui=Ui_changeSummary()
self.ui.setupUi(self)
def setChanges(self, changeDict):
"""Add changes to ChangeWin.
:param changeDict: Dictionary of changes.
"""
installString = ''
upgradeString = ''
removeString = ''
for app in changeDict['repoInstalls']:
installString += app + ' '
for app in changeDict['aurInstalls']:
installString += app + ' '
for app in changeDict['aurBuildDeps']:
installString += app + ' '
for app in changeDict['aurDeps']:
installString += app + ' '
for app in changeDict['repoUpgrades']:
upgradeString += app + ' '
for app in changeDict['aurUpgrades']:
upgradeString += app + ' '
for app in changeDict['removes']:
removeString += app + ' '
self.ui.toInstallEdit.setText(installString)
self.ui.toUpgradeEdit.setText(upgradeString)
self.ui.toRemoveEdit.setText(removeString)
# vim: set ts=4 sw=4 noet:
|
ubiquill/Potluck
|
src/view/Changes.py
|
Python
|
gpl-2.0
| 2,296 | 0.003486 |
info = {
"name": "sw",
"date_order": "DMY",
"january": [
"jan",
"januari"
],
"february": [
"feb",
"februari"
],
"march": [
"mac",
"machi"
],
"april": [
"apr",
"aprili"
],
"may": [
"mei"
],
"june": [
"jun",
"juni"
],
"july": [
"jul",
"julai"
],
"august": [
"ago",
"agosti"
],
"september": [
"sep",
"septemba"
],
"october": [
"okt",
"oktoba"
],
"november": [
"nov",
"novemba"
],
"december": [
"des",
"desemba"
],
"monday": [
"jumatatu"
],
"tuesday": [
"jumanne"
],
"wednesday": [
"jumatano"
],
"thursday": [
"alhamisi"
],
"friday": [
"ijumaa"
],
"saturday": [
"jumamosi"
],
"sunday": [
"jumapili"
],
"am": [
"am",
"asubuhi"
],
"pm": [
"mchana",
"pm"
],
"year": [
"mwaka"
],
"month": [
"mwezi"
],
"week": [
"wiki"
],
"day": [
"siku"
],
"hour": [
"saa"
],
"minute": [
"dak",
"dakika"
],
"second": [
"sek",
"sekunde"
],
"relative-type": {
"0 day ago": [
"leo"
],
"0 hour ago": [
"saa hii"
],
"0 minute ago": [
"dakika hii"
],
"0 month ago": [
"mwezi huu"
],
"0 second ago": [
"sasa hivi"
],
"0 week ago": [
"wiki hii"
],
"0 year ago": [
"mwaka huu"
],
"1 day ago": [
"jana"
],
"1 month ago": [
"mwezi uliopita"
],
"1 week ago": [
"wiki iliyopita"
],
"1 year ago": [
"mwaka uliopita"
],
"in 1 day": [
"kesho"
],
"in 1 month": [
"mwezi ujao"
],
"in 1 week": [
"wiki ijayo"
],
"in 1 year": [
"mwaka ujao"
]
},
"relative-type-regex": {
"\\1 day ago": [
"siku (\\d+) iliyopita",
"siku (\\d+) zilizopita"
],
"\\1 hour ago": [
"saa (\\d+) iliyopita",
"saa (\\d+) zilizopita"
],
"\\1 minute ago": [
"dakika (\\d+) iliyopita",
"dakika (\\d+) zilizopita"
],
"\\1 month ago": [
"miezi (\\d+) iliyopita",
"mwezi (\\d+) uliopita"
],
"\\1 second ago": [
"sekunde (\\d+) iliyopita",
"sekunde (\\d+) zilizopita"
],
"\\1 week ago": [
"wiki (\\d+) iliyopita",
"wiki (\\d+) zilizopita"
],
"\\1 year ago": [
"miaka (\\d+) iliyopita",
"mwaka (\\d+) uliopita"
],
"in \\1 day": [
"baada ya siku (\\d+)"
],
"in \\1 hour": [
"baada ya saa (\\d+)"
],
"in \\1 minute": [
"baada ya dakika (\\d+)"
],
"in \\1 month": [
"baada ya miezi (\\d+)",
"baada ya mwezi (\\d+)"
],
"in \\1 second": [
"baada ya sekunde (\\d+)"
],
"in \\1 week": [
"baada ya wiki (\\d+)"
],
"in \\1 year": [
"baada ya miaka (\\d+)",
"baada ya mwaka (\\d+)"
]
},
"locale_specific": {
"sw-CD": {
"name": "sw-CD",
"week": [
"juma"
]
},
"sw-KE": {
"name": "sw-KE"
},
"sw-UG": {
"name": "sw-UG"
}
},
"skip": [
" ",
"'",
",",
"-",
".",
"/",
";",
"@",
"[",
"]",
"|",
","
]
}
|
scrapinghub/dateparser
|
dateparser/data/date_translation_data/sw.py
|
Python
|
bsd-3-clause
| 4,155 | 0 |
# coding=UTF-8
# URL: https://github.com/SickRage/SickRage
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
###
# As a test case, there are instances in which it is necessary to call protected members of
# classes in order to test those classes. Therefore we will be pylint disable protected-access
###
# pylint: disable=line-too-long
"""
Test notifiers
"""
import os.path
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sickbeard import db
from sickbeard.tv import TVEpisode, TVShow
from sickbeard.webserve import Home
from sickbeard.notifiers.emailnotify import Notifier as EmailNotifier
from sickbeard.notifiers.prowl import Notifier as ProwlNotifier
from sickrage.helper.encoding import ss
import tests.test_lib as test
class NotifierTests(test.SickbeardTestDBCase): # pylint: disable=too-many-public-methods
"""
Test notifiers
"""
@classmethod
def setUpClass(cls):
num_legacy_shows = 3
num_shows = 3
num_episodes_per_show = 5
cls.mydb = db.DBConnection()
cls.legacy_shows = []
cls.shows = []
# Per-show-notifications were originally added for email notifications only. To add
# this feature to other notifiers, it was necessary to alter the way text is stored in
# one of the DB columns. Therefore, to test properly, we must create some shows that
# store emails in the old method (legacy method) and then other shows that will use
# the new method.
for show_counter in range(100, 100 + num_legacy_shows):
show = TVShow(1, show_counter)
show.name = "Show " + str(show_counter)
show.episodes = []
for episode_counter in range(0, num_episodes_per_show):
episode = TVEpisode(show, test.SEASON, episode_counter)
episode.name = "Episode " + str(episode_counter + 1)
episode.quality = "SDTV"
show.episodes.append(episode)
show.saveToDB()
cls.legacy_shows.append(show)
for show_counter in range(200, 200 + num_shows):
show = TVShow(1, show_counter)
show.name = "Show " + str(show_counter)
show.episodes = []
for episode_counter in range(0, num_episodes_per_show):
episode = TVEpisode(show, test.SEASON, episode_counter)
episode.name = "Episode " + str(episode_counter + 1)
episode.quality = "SDTV"
show.episodes.append(episode)
show.saveToDB()
cls.shows.append(show)
def setUp(self):
"""
Set up tests
"""
self._debug_spew("\n\r")
@unittest.skip('Not yet implemented')
def test_boxcar(self):
"""
Test boxcar notifications
"""
pass
def test_email(self):
"""
Test email notifications
"""
email_notifier = EmailNotifier()
# Per-show-email notifications were added early on and utilized a different format than the other notifiers.
# Therefore, to test properly (and ensure backwards compatibility), this routine will test shows that use
# both the old and the new storage methodology
legacy_test_emails = "email-1@address.com,email2@address.org,email_3@address.tv"
test_emails = "email-4@address.com,email5@address.org,email_6@address.tv"
for show in self.legacy_shows:
showid = self._get_showid_by_showname(show.name)
self.mydb.action("UPDATE tv_shows SET notify_list = ? WHERE show_id = ?", [legacy_test_emails, showid])
for show in self.shows:
showid = self._get_showid_by_showname(show.name)
Home.saveShowNotifyList(show=showid, emails=test_emails)
# Now, iterate through all shows using the email list generation routines that are used in the notifier proper
shows = self.legacy_shows + self.shows
for show in shows:
for episode in show.episodes:
ep_name = ss(episode._format_pattern('%SN - %Sx%0E - %EN - ') + episode.quality) # pylint: disable=protected-access
show_name = email_notifier._parseEp(ep_name) # pylint: disable=protected-access
recipients = email_notifier._generate_recipients(show_name) # pylint: disable=protected-access
self._debug_spew("- Email Notifications for " + show.name + " (episode: " + episode.name + ") will be sent to:")
for email in recipients:
self._debug_spew("-- " + email.strip())
self._debug_spew("\n\r")
return True
@unittest.skip('Not yet implemented')
def test_emby(self):
"""
Test emby notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_freemobile(self):
"""
Test freemobile notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_growl(self):
"""
Test growl notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_kodi(self):
"""
Test kodi notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_libnotify(self):
"""
Test libnotify notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_nma(self):
"""
Test nma notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_nmj(self):
"""
Test nmj notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_nmjv2(self):
"""
Test nmjv2 notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_plex(self):
"""
Test plex notifications
"""
pass
def test_prowl(self):
"""
Test prowl notifications
"""
prowl_notifier = ProwlNotifier()
# Prowl per-show-notifications only utilize the new methodology for storage; therefore, the list of legacy_shows
# will not be altered (to preserve backwards compatibility testing)
test_prowl_apis = "11111111111111111111,22222222222222222222"
for show in self.shows:
showid = self._get_showid_by_showname(show.name)
Home.saveShowNotifyList(show=showid, prowlAPIs=test_prowl_apis)
# Now, iterate through all shows using the Prowl API generation routines that are used in the notifier proper
for show in self.shows:
for episode in show.episodes:
ep_name = ss(episode._format_pattern('%SN - %Sx%0E - %EN - ') + episode.quality) # pylint: disable=protected-access
show_name = prowl_notifier._parse_episode(ep_name) # pylint: disable=protected-access
recipients = prowl_notifier._generate_recipients(show_name) # pylint: disable=protected-access
self._debug_spew("- Prowl Notifications for " + show.name + " (episode: " + episode.name + ") will be sent to:")
for api in recipients:
self._debug_spew("-- " + api.strip())
self._debug_spew("\n\r")
return True
@unittest.skip('Not yet implemented')
def test_pushalot(self):
"""
Test pushalot notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_pushbullet(self):
"""
Test pushbullet notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_pushover(self):
"""
Test pushover notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_pytivo(self):
"""
Test pytivo notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_synoindex(self):
"""
Test synoindex notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_synologynotifier(self):
"""
Test synologynotifier notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_trakt(self):
"""
Test trakt notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_tweet(self):
"""
Test tweet notifications
"""
pass
@unittest.skip('Not yet implemented')
def test_twilio(self):
"""
Test twilio notifications
"""
pass
@staticmethod
def _debug_spew(text):
"""
Spew text notifications
:param text: to spew
:return:
"""
if __name__ == '__main__' and text is not None:
print text
def _get_showid_by_showname(self, showname):
"""
Get show ID by show name
:param showname:
:return:
"""
if showname is not None:
rows = self.mydb.select("SELECT show_id FROM tv_shows WHERE show_name = ?", [showname])
if len(rows) == 1:
return rows[0]['show_id']
return -1
if __name__ == '__main__':
print "=================="
print "STARTING - NOTIFIER TESTS"
print "=================="
print "######################################################################"
SUITE = unittest.TestLoader().loadTestsFromTestCase(NotifierTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
|
jackkiej/SickRage
|
tests/notifier_tests.py
|
Python
|
gpl-3.0
| 10,384 | 0.003371 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""
This script computes bounds on the privacy cost of training the
student model from noisy aggregation of labels predicted by teachers.
It should be used only after training the student (and therefore the
teachers as well). We however include the label files required to
reproduce key results from our paper (https://arxiv.org/abs/1610.05755):
the epsilon bounds for MNIST and SVHN students.
The command that computes the epsilon bound associated
with the training of the MNIST student model (100 label queries
with a (1/20)*2=0.1 epsilon bound each) is:
python analysis.py
--counts_file=mnist_250_teachers_labels.npy
--indices_file=mnist_250_teachers_100_indices_used_by_student.npy
The command that computes the epsilon bound associated
with the training of the SVHN student model (1000 label queries
with a (1/20)*2=0.1 epsilon bound each) is:
python analysis.py
--counts_file=svhn_250_teachers_labels.npy
--max_examples=1000
--delta=1e-6
"""
import os
import math
import numpy as np
from six.moves import xrange
import tensorflow as tf
from differential_privacy.multiple_teachers.input import maybe_download
# These parameters can be changed to compute bounds for different failure rates
# or different model predictions.
tf.flags.DEFINE_integer("moments",8, "Number of moments")
tf.flags.DEFINE_float("noise_eps", 0.1, "Eps value for each call to noisymax.")
tf.flags.DEFINE_float("delta", 1e-5, "Target value of delta.")
tf.flags.DEFINE_float("beta", 0.09, "Value of beta for smooth sensitivity")
tf.flags.DEFINE_string("counts_file","","Numpy matrix with raw counts")
tf.flags.DEFINE_string("indices_file","",
"File containting a numpy matrix with indices used."
"Optional. Use the first max_examples indices if this is not provided.")
tf.flags.DEFINE_integer("max_examples",1000,
"Number of examples to use. We will use the first"
" max_examples many examples from the counts_file"
" or indices_file to do the privacy cost estimate")
tf.flags.DEFINE_float("too_small", 1e-10, "Small threshold to avoid log of 0")
tf.flags.DEFINE_bool("input_is_counts", False, "False if labels, True if counts")
FLAGS = tf.flags.FLAGS
def compute_q_noisy_max(counts, noise_eps):
"""returns ~ Pr[outcome != winner].
Args:
counts: a list of scores
noise_eps: privacy parameter for noisy_max
Returns:
q: the probability that outcome is different from true winner.
"""
# For noisy max, we only get an upper bound.
# Pr[ j beats i*] \leq (2+gap(j,i*))/ 4 exp(gap(j,i*)
# proof at http://mathoverflow.net/questions/66763/
# tight-bounds-on-probability-of-sum-of-laplace-random-variables
winner = np.argmax(counts)
counts_normalized = noise_eps * (counts - counts[winner])
counts_rest = np.array(
[counts_normalized[i] for i in xrange(len(counts)) if i != winner])
q = 0.0
for c in counts_rest:
gap = -c
q += (gap + 2.0) / (4.0 * math.exp(gap))
return min(q, 1.0 - (1.0/len(counts)))
def compute_q_noisy_max_approx(counts, noise_eps):
"""returns ~ Pr[outcome != winner].
Args:
counts: a list of scores
noise_eps: privacy parameter for noisy_max
Returns:
q: the probability that outcome is different from true winner.
"""
# For noisy max, we only get an upper bound.
# Pr[ j beats i*] \leq (2+gap(j,i*))/ 4 exp(gap(j,i*)
# proof at http://mathoverflow.net/questions/66763/
# tight-bounds-on-probability-of-sum-of-laplace-random-variables
# This code uses an approximation that is faster and easier
# to get local sensitivity bound on.
winner = np.argmax(counts)
counts_normalized = noise_eps * (counts - counts[winner])
counts_rest = np.array(
[counts_normalized[i] for i in xrange(len(counts)) if i != winner])
gap = -max(counts_rest)
q = (len(counts) - 1) * (gap + 2.0) / (4.0 * math.exp(gap))
return min(q, 1.0 - (1.0/len(counts)))
def logmgf_exact(q, priv_eps, l):
"""Computes the logmgf value given q and privacy eps.
The bound used is the min of three terms. The first term is from
https://arxiv.org/pdf/1605.02065.pdf.
The second term is based on the fact that when event has probability (1-q) for
q close to zero, q can only change by exp(eps), which corresponds to a
much smaller multiplicative change in (1-q)
The third term comes directly from the privacy guarantee.
Args:
q: pr of non-optimal outcome
priv_eps: eps parameter for DP
l: moment to compute.
Returns:
Upper bound on logmgf
"""
if q < 0.5:
t_one = (1-q) * math.pow((1-q) / (1 - math.exp(priv_eps) * q), l)
t_two = q * math.exp(priv_eps * l)
t = t_one + t_two
try:
log_t = math.log(t)
except ValueError:
print("Got ValueError in math.log for values :" + str((q, priv_eps, l, t)))
log_t = priv_eps * l
else:
log_t = priv_eps * l
return min(0.5 * priv_eps * priv_eps * l * (l + 1), log_t, priv_eps * l)
def logmgf_from_counts(counts, noise_eps, l):
"""
ReportNoisyMax mechanism with noise_eps with 2*noise_eps-DP
in our setting where one count can go up by one and another
can go down by 1.
"""
q = compute_q_noisy_max(counts, noise_eps)
return logmgf_exact(q, 2.0 * noise_eps, l)
def sens_at_k(counts, noise_eps, l, k):
"""Return sensitivity at distane k.
Args:
counts: an array of scores
noise_eps: noise parameter used
l: moment whose sensitivity is being computed
k: distance
Returns:
sensitivity: at distance k
"""
counts_sorted = sorted(counts, reverse=True)
if 0.5 * noise_eps * l > 1:
print("l too large to compute sensitivity")
return 0
# Now we can assume that at k, gap remains positive
# or we have reached the point where logmgf_exact is
# determined by the first term and ind of q.
if counts[0] < counts[1] + k:
return 0
counts_sorted[0] -= k
counts_sorted[1] += k
val = logmgf_from_counts(counts_sorted, noise_eps, l)
counts_sorted[0] -= 1
counts_sorted[1] += 1
val_changed = logmgf_from_counts(counts_sorted, noise_eps, l)
return val_changed - val
def smoothed_sens(counts, noise_eps, l, beta):
"""Compute beta-smooth sensitivity.
Args:
counts: array of scors
noise_eps: noise parameter
l: moment of interest
beta: smoothness parameter
Returns:
smooth_sensitivity: a beta smooth upper bound
"""
k = 0
smoothed_sensitivity = sens_at_k(counts, noise_eps, l, k)
while k < max(counts):
k += 1
sensitivity_at_k = sens_at_k(counts, noise_eps, l, k)
smoothed_sensitivity = max(
smoothed_sensitivity,
math.exp(-beta * k) * sensitivity_at_k)
if sensitivity_at_k == 0.0:
break
return smoothed_sensitivity
def main(unused_argv):
##################################################################
# If we are reproducing results from paper https://arxiv.org/abs/1610.05755,
# download the required binaries with label information.
##################################################################
# Binaries for MNIST results
paper_binaries_mnist = \
["https://github.com/npapernot/multiple-teachers-for-privacy/blob/master/mnist_250_teachers_labels.npy?raw=true",
"https://github.com/npapernot/multiple-teachers-for-privacy/blob/master/mnist_250_teachers_100_indices_used_by_student.npy?raw=true"]
if FLAGS.counts_file == "mnist_250_teachers_labels.npy" \
or FLAGS.indices_file == "mnist_250_teachers_100_indices_used_by_student.npy":
maybe_download(paper_binaries_mnist, os.getcwd())
# Binaries for SVHN results
paper_binaries_svhn = ["https://github.com/npapernot/multiple-teachers-for-privacy/blob/master/svhn_250_teachers_labels.npy?raw=true"]
if FLAGS.counts_file == "svhn_250_teachers_labels.npy":
maybe_download(paper_binaries_svhn, os.getcwd())
input_mat = np.load(FLAGS.counts_file)
if FLAGS.input_is_counts:
counts_mat = input_mat
else:
# In this case, the input is the raw predictions. Transform
num_teachers, n = input_mat.shape
counts_mat = np.zeros((n, 10)).astype(np.int32)
for i in range(n):
for j in range(num_teachers):
counts_mat[i, int(input_mat[j, i])] += 1
n = counts_mat.shape[0]
num_examples = min(n, FLAGS.max_examples)
if not FLAGS.indices_file:
indices = np.array(range(num_examples))
else:
index_list = np.load(FLAGS.indices_file)
indices = index_list[:num_examples]
l_list = 1.0 + np.array(xrange(FLAGS.moments))
beta = FLAGS.beta
total_log_mgf_nm = np.array([0.0 for _ in l_list])
total_ss_nm = np.array([0.0 for _ in l_list])
noise_eps = FLAGS.noise_eps
for i in indices:
total_log_mgf_nm += np.array(
[logmgf_from_counts(counts_mat[i], noise_eps, l)
for l in l_list])
total_ss_nm += np.array(
[smoothed_sens(counts_mat[i], noise_eps, l, beta)
for l in l_list])
delta = FLAGS.delta
# We want delta = exp(alpha - eps l).
# Solving gives eps = (alpha - ln (delta))/l
eps_list_nm = (total_log_mgf_nm - math.log(delta)) / l_list
print("Epsilons (Noisy Max): " + str(eps_list_nm))
print("Smoothed sensitivities (Noisy Max): " + str(total_ss_nm / l_list))
# If beta < eps / 2 ln (1/delta), then adding noise Lap(1) * 2 SS/eps
# is eps,delta DP
# Also if beta < eps / 2(gamma +1), then adding noise 2(gamma+1) SS eta / eps
# where eta has density proportional to 1 / (1+|z|^gamma) is eps-DP
# Both from Corolloary 2.4 in
# http://www.cse.psu.edu/~ads22/pubs/NRS07/NRS07-full-draft-v1.pdf
# Print the first one's scale
ss_eps = 2.0 * beta * math.log(1/delta)
ss_scale = 2.0 / ss_eps
print("To get an " + str(ss_eps) + "-DP estimate of epsilon, ")
print("..add noise ~ " + str(ss_scale))
print("... times " + str(total_ss_nm / l_list))
print("Epsilon = " + str(min(eps_list_nm)) + ".")
if min(eps_list_nm) == eps_list_nm[-1]:
print("Warning: May not have used enough values of l")
# Data independent bound, as mechanism is
# 2*noise_eps DP.
data_ind_log_mgf = np.array([0.0 for _ in l_list])
data_ind_log_mgf += num_examples * np.array(
[logmgf_exact(1.0, 2.0 * noise_eps, l) for l in l_list])
data_ind_eps_list = (data_ind_log_mgf - math.log(delta)) / l_list
print("Data independent bound = " + str(min(data_ind_eps_list)) + ".")
return
if __name__ == "__main__":
tf.app.run()
|
cshallue/models
|
research/differential_privacy/multiple_teachers/analysis.py
|
Python
|
apache-2.0
| 10,988 | 0.012013 |
import itertools
import struct
def ip4_to_int32(str_ip, order='>'):
return struct.unpack(order+"I",struct.pack("BBBB",*map(int,str_ip.split("."))))[0]
def int32_to_ip4(big_int, order='>'):
return '.'.join(map(str, struct.unpack("BBBB",struct.pack(order+"I",big_int))))
def gen_get_n_bit(data, bit=1):
mask = 1 << n
for c in data:
yield 1 if ord(c) & mask else 0
def get_n_bit(data, bit=1):
return list(gen_get_n_bit(data, bit))
def byte_to_bin_str(byte):
return "{0:0>b}".format(byte)
def byte_to_bin_arr(byte):
return [int(x) for x in byte_to_bin_str(byte)]
def gen_chunks(data, size):
for i in range(1+len(data)/size):
yield data[i*size:(i+1)*size]
def chunks(data, size):
return list(gen_chunks(data, size))
def compare_collection(col, func_cmp):
for pair in itertools.combinations(col, 2):
if not func_cmp(*pair):
return False
return True
def gen_pairs(col,):
return itertools.combinations(col,2);
|
k3idii/pykpyk
|
datatools.py
|
Python
|
mit
| 955 | 0.034555 |
# Copyright 2014 Diamond Light Source Ltd.
#
# 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.
"""
.. module:: structures
:platform: Unix
:synopsis: Classes which describe the main data types for passing between
plugins
.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>
"""
import numpy as np
import h5py
import logging
from mpi4py import MPI
from savu.core.utils import logmethod
NX_CLASS = 'NX_class'
# Core Direction Keywords
CD_PROJECTION = 'core_dir_projection'
CD_SINOGRAM = 'core_dir_sinogram'
CD_ROTATION_AXIS = 'core_dir_rotation_axis'
CD_PATTERN = 'core_dir_pattern'
class SliceAvailableWrapper(object):
"""
This class takes 2 datasets, one avaialble boolean ndarray, and 1 data
ndarray. Its purpose is to provide slices from the data array only if data
has been put there, and to allow a convinient way to put slices into the
data array, and set the available array to True
"""
def __init__(self, avail, data):
"""
:param avail: The available boolean ndArray
:type avail: boolean ndArray
:param data: The data ndArray
:type data: any ndArray
"""
self.avail = avail
self.data = data
def __getitem__(self, item):
if self.avail[item].all():
return self.data[item]
else:
return None
def __setitem__(self, item, value):
self.data[item] = value
self.avail[item] = True
def __getattr__(self, name):
"""
Delegate everything else to the data class
"""
value = self.data.__getattribute__(name)
return value
class SliceAlwaysAvailableWrapper(SliceAvailableWrapper):
"""
This class takes 1 data ndarray. Its purpose is to provide slices from the
data array in the same way as the SliceAvailableWrapper but assuming the
data is always available (for example in the case of the input file)
"""
def __init__(self, data):
"""
:param data: The data ndArray
:type data: any ndArray
"""
super(SliceAlwaysAvailableWrapper, self).__init__(None, data)
@logmethod
def __getitem__(self, item):
return self.data[item]
@logmethod
def __setitem__(self, item, value):
self.data[item] = value
class PassThrough(object):
"""
Interface Class describing when the input data of a plugin is also the
output
"""
def __init__(self):
super(PassThrough, self).__init__()
class Data(object):
"""
Baseclass for all data
"""
def __init__(self):
super(Data, self).__init__()
self.backing_file = None
self.data = None
self.base_path = None
self.core_directions = {}
@logmethod
def complete(self):
"""
Closes the backing file and completes work
"""
if self.backing_file is not None:
logging.debug("Completing file %s %s", self.base_path,
self.backing_file.filename)
self.backing_file.close()
self.backing_file = None
def external_link(self):
return h5py.ExternalLink(self.backing_file.filename,
self.base_path)
def get_slice_list(self, frame_type):
if frame_type in self.core_directions.keys():
it = np.nditer(self.data, flags=['multi_index'])
dirs_to_remove = list(self.core_directions[frame_type])
dirs_to_remove.sort(reverse=True)
for direction in dirs_to_remove:
it.remove_axis(direction)
mapping_list = range(len(it.multi_index))
dirs_to_remove.sort()
for direction in dirs_to_remove:
mapping_list.insert(direction, -1)
mapping_array = np.array(mapping_list)
slice_list = []
while not it.finished:
tup = it.multi_index + (slice(None),)
slice_list.append(tuple(np.array(tup)[mapping_array]))
it.iternext()
return slice_list
return None
def get_data_shape(self):
"""
Simply returns the shape of the main data array
"""
return self.data.shape
class RawTimeseriesData(Data):
"""
Descriptor for raw timeseries data
"""
def __init__(self):
super(RawTimeseriesData, self).__init__()
self.image_key = None
self.rotation_angle = None
self.control = None
self.center_of_rotation = None
@logmethod
def populate_from_nx_tomo(self, path):
"""
Populate the RawTimeseriesData from an NXTomo defined NeXus file
:param path: The full path of the NeXus file to load.
:type path: str
"""
self.backing_file = h5py.File(path, 'r')
logging.debug("Creating file '%s' '%s'", 'tomo_entry',
self.backing_file.filename)
data = self.backing_file['entry1/tomo_entry/instrument/detector/data']
self.data = SliceAlwaysAvailableWrapper(data)
image_key = self.backing_file[
'entry1/tomo_entry/instrument/detector/image_key']
self.image_key = SliceAlwaysAvailableWrapper(image_key)
rotation_angle = \
self.backing_file['entry1/tomo_entry/sample/rotation_angle']
self.rotation_angle = SliceAlwaysAvailableWrapper(rotation_angle)
control = self.backing_file['entry1/tomo_entry/control/data']
self.control = SliceAlwaysAvailableWrapper(control)
self.core_directions[CD_PROJECTION] = (1, 2)
self.core_directions[CD_SINOGRAM] = (0, 2)
self.core_directions[CD_ROTATION_AXIS] = (0, )
@logmethod
def create_backing_h5(self, path, group_name, data, mpi=False,
new_shape=None):
"""
Create a h5 backend for this RawTimeseriesData
:param path: The full path of the NeXus file to use as a backend
:type path: str
:param data: The structure from which this can be created
:type data: savu.structure.RawTimeseriesData
:param mpi: if an MPI process, provide MPI package here, default None
:type mpi: package
"""
self.backing_file = None
if mpi:
self.backing_file = h5py.File(path, 'w', driver='mpio',
comm=MPI.COMM_WORLD)
else:
self.backing_file = h5py.File(path, 'w')
if self.backing_file is None:
raise IOError("Failed to open the hdf5 file")
logging.debug("Creating file '%s' '%s'", self.base_path,
self.backing_file.filename)
self.base_path = group_name
if not isinstance(data, RawTimeseriesData):
raise ValueError("data is not a RawTimeseriesData")
self.core_directions[CD_PROJECTION] = (1, 2)
self.core_directions[CD_SINOGRAM] = (0, 2)
self.core_directions[CD_ROTATION_AXIS] = 0
data_shape = new_shape
if data_shape is None:
data_shape = data.data.shape
data_type = np.double
image_key_shape = data.image_key.shape
image_key_type = data.image_key.dtype
rotation_angle_shape = data.rotation_angle.shape
rotation_angle_type = data.rotation_angle.dtype
control_shape = data.control.shape
control_type = data.control.dtype
cor_shape = (data.data.shape[self.core_directions[CD_ROTATION_AXIS]],)
cor_type = np.double
group = self.backing_file.create_group(group_name)
group.attrs[NX_CLASS] = 'NXdata'
data_value = group.create_dataset('data', data_shape, data_type)
data_value.attrs['signal'] = 1
data_avail = group.create_dataset('data_avail',
data_shape, np.bool_)
self.data = SliceAvailableWrapper(data_avail, data_value)
# Create and prepopulate the following, as they are likely to be
# Unchanged during the processing
image_key = \
group.create_dataset('image_key',
image_key_shape, image_key_type)
image_key_avail = \
group.create_dataset('image_key_avail',
image_key_shape, np.bool_)
self.image_key = \
SliceAvailableWrapper(image_key_avail, image_key)
self.image_key[:] = data.image_key[:]
rotation_angle = \
group.create_dataset('rotation_angle',
rotation_angle_shape, rotation_angle_type)
rotation_angle_avail = \
group.create_dataset('rotation_angle_avail',
rotation_angle_shape, np.bool_)
self.rotation_angle = \
SliceAvailableWrapper(rotation_angle_avail, rotation_angle)
self.rotation_angle[:] = data.rotation_angle[:]
control = \
group.create_dataset('control',
control_shape, control_type)
control_avail = \
group.create_dataset('control_avail',
control_shape, np.bool_)
self.control = \
SliceAvailableWrapper(control_avail, control)
self.control[:] = data.control[:]
cor = \
group.create_dataset('center_of_rotation',
cor_shape, cor_type)
cor_avail = \
group.create_dataset('center_of_rotation_avail',
cor_shape, np.bool_)
self.center_of_rotation = \
SliceAvailableWrapper(cor_avail, cor)
def get_number_of_projections(self):
"""
Gets the real number of projections excluding calibration data
:returns: integer number of data frames
"""
return (self.image_key.data[:] == 0).sum()
def get_projection_shape(self):
"""
Gets the shape of a projection
:returns: a tuple of the shape of a single projection
"""
return self.data.data.shape[1:3]
def get_clusterd_frame_list(self):
"""
Gets a list of index arrays grouped by sequential image_key
:returns: a list of integer index arrays
"""
diff = np.abs(np.diff(self.image_key))
pos = np.where(diff > 0)[0] + 1
return np.split(np.arange(self.image_key.shape[0]), pos)
class ProjectionData(Data):
"""
Descriptor for corrected projection data
"""
def __init__(self):
super(ProjectionData, self).__init__()
self.rotation_angle = None
self.center_of_rotation = None
@logmethod
def create_backing_h5(self, path, group_name, data, mpi=False,
new_shape=None):
"""
Create a h5 backend for this ProjectionData
:param path: The full path of the NeXus file to use as a backend
:type path: str
:param data: The structure from which this can be created
:type data: savu.structure
:param mpi: if an MPI process, provide MPI package here, default None
:type boolean: package
"""
self.backing_file = None
if mpi:
self.backing_file = h5py.File(path, 'w', driver='mpio',
comm=MPI.COMM_WORLD)
else:
self.backing_file = h5py.File(path, 'w')
if self.backing_file is None:
raise IOError("Failed to open the hdf5 file")
self.base_path = group_name
logging.debug("Creating file '%s' '%s'", self.base_path,
self.backing_file.filename)
data_shape = new_shape
data_type = None
rotation_angle_shape = None
rotation_angle_type = None
cor_shape = None
cor_type = np.double
if data.__class__ == RawTimeseriesData:
if data_shape is None:
data_shape = (data.get_number_of_projections(),) +\
data.get_projection_shape()
data_type = np.double
rotation_angle_shape = (data.get_number_of_projections(),)
rotation_angle_type = data.rotation_angle.dtype
cor_shape = (data.data.shape[1],)
elif data.__class__ == ProjectionData:
if data_shape is None:
data_shape = data.data.shape
data_type = np.double
rotation_angle_shape = data.rotation_angle.shape
rotation_angle_type = data.rotation_angle.dtype
cor_shape = (data.data.shape[1],)
group = self.backing_file.create_group(group_name)
group.attrs[NX_CLASS] = 'NXdata'
data_value = group.create_dataset('data', data_shape, data_type)
data_value.attrs['signal'] = 1
data_avail = group.create_dataset('data_avail',
data_shape, np.bool_)
self.data = SliceAvailableWrapper(data_avail, data_value)
rotation_angle = \
group.create_dataset('rotation_angle',
rotation_angle_shape, rotation_angle_type)
rotation_angle_avail = \
group.create_dataset('rotation_angle_avail',
rotation_angle_shape, np.bool_)
self.rotation_angle = \
SliceAvailableWrapper(rotation_angle_avail, rotation_angle)
cor = \
group.create_dataset('center_of_rotation',
cor_shape, cor_type)
cor_avail = \
group.create_dataset('center_of_rotation_avail',
cor_shape, np.bool_)
self.center_of_rotation = \
SliceAvailableWrapper(cor_avail, cor)
self.core_directions = data.core_directions
@logmethod
def populate_from_h5(self, path):
"""
Populate the contents of this object from a file
:param path: The full path of the h5 file to load.
:type path: str
"""
self.backing_file = h5py.File(path, 'r')
logging.debug("Creating file '%s' '%s'", 'TimeseriesFieldCorrections',
self.backing_file.filename)
data = self.backing_file['TimeseriesFieldCorrections/data']
self.data = SliceAlwaysAvailableWrapper(data)
rotation_angle = \
self.backing_file['TimeseriesFieldCorrections/rotation_angle']
self.rotation_angle = SliceAlwaysAvailableWrapper(rotation_angle)
self.core_directions[CD_PROJECTION] = (1, 2)
self.core_directions[CD_SINOGRAM] = (0, 2)
self.core_directions[CD_ROTATION_AXIS] = (0,)
def get_number_of_sinograms(self):
"""
Gets the real number sinograms
:returns: integer number of sinogram frames
"""
return self.data.shape[1]
def get_number_of_projections(self):
"""
Gets the real number projections
:returns: integer number of projection frames
"""
return self.data.shape[0]
class VolumeData(Data):
"""
Descriptor for volume data
"""
def __init__(self):
super(VolumeData, self).__init__()
@logmethod
def create_backing_h5(self, path, group_name, data_shape,
data_type, mpi=False):
"""
Create a h5 backend for this ProjectionData
:param path: The full path of the NeXus file to use as a backend
:type path: str
:param data_shape: The shape of the data block
:type data: tuple
:param data_type: The type of the data block
:type data: np.dtype
:param mpi: if an MPI process, provide MPI package here, default None
:type mpi: package
"""
self.backing_file = None
if mpi:
self.backing_file = h5py.File(path, 'w', driver='mpio',
comm=MPI.COMM_WORLD)
else:
self.backing_file = h5py.File(path, 'w')
if self.backing_file is None:
raise IOError("Failed to open the hdf5 file")
self.base_path = group_name
logging.debug("Creating file '%s' '%s'", self.base_path,
self.backing_file.filename)
group = self.backing_file.create_group(group_name)
group.attrs[NX_CLASS] = 'NXdata'
data_value = group.create_dataset('data', data_shape, data_type)
data_value.attrs['signal'] = 1
data_avail = group.create_dataset('data_avail',
data_shape, np.bool_)
self.data = SliceAvailableWrapper(data_avail, data_value)
def get_volume_shape(self):
"""
Gets the real number sinograms
:returns: integer number of sinogram frames
"""
return self.data.shape
|
swtp1v07/Savu
|
savu/data/structures.py
|
Python
|
apache-2.0
| 17,375 | 0 |
from distutils.core import Extension
from collections import defaultdict
def get_extensions():
import numpy as np
exts = []
# malloc
mac_incl_path = "/usr/include/malloc"
cfg = defaultdict(list)
cfg['include_dirs'].append(np.get_include())
cfg['include_dirs'].append(mac_incl_path)
cfg['include_dirs'].append('gala/potential')
cfg['extra_compile_args'].append('--std=gnu99')
cfg['sources'].append('gala/integrate/cyintegrators/leapfrog.pyx')
cfg['sources'].append('gala/potential/potential/src/cpotential.c')
exts.append(Extension('gala.integrate.cyintegrators.leapfrog', **cfg))
cfg = defaultdict(list)
cfg['include_dirs'].append(np.get_include())
cfg['include_dirs'].append(mac_incl_path)
cfg['include_dirs'].append('gala/potential')
cfg['extra_compile_args'].append('--std=gnu99')
cfg['sources'].append('gala/potential/hamiltonian/src/chamiltonian.c')
cfg['sources'].append('gala/potential/potential/src/cpotential.c')
cfg['sources'].append('gala/integrate/cyintegrators/dop853.pyx')
cfg['sources'].append('gala/integrate/cyintegrators/dopri/dop853.c')
exts.append(Extension('gala.integrate.cyintegrators.dop853', **cfg))
cfg = defaultdict(list)
cfg['include_dirs'].append(np.get_include())
cfg['include_dirs'].append(mac_incl_path)
cfg['include_dirs'].append('gala/potential')
cfg['extra_compile_args'].append('--std=gnu99')
cfg['sources'].append('gala/integrate/cyintegrators/ruth4.pyx')
cfg['sources'].append('gala/potential/potential/src/cpotential.c')
exts.append(Extension('gala.integrate.cyintegrators.ruth4', **cfg))
return exts
|
adrn/gala
|
gala/integrate/setup_package.py
|
Python
|
mit
| 1,672 | 0 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""Utility functions for coverage data calculation."""
import collections
import itertools
import json
import posixpath
from typing import Dict, List, Tuple
import tempfile
import pandas as pd
from analysis import data_utils
from common import filestore_utils
from common import logs
logger = logs.Logger('coverage_data_utils')
def fuzzer_and_benchmark_to_key(fuzzer: str, benchmark: str) -> str:
"""Returns the key representing |fuzzer| and |benchmark|."""
return fuzzer + ' ' + benchmark
def key_to_fuzzer_and_benchmark(key: str) -> Tuple[str, str]:
"""Returns a tuple containing the fuzzer and the benchmark represented by
|key|."""
return tuple(key.split(' '))
def get_experiment_filestore_path_for_fuzzer_benchmark(
fuzzer: str,
benchmark: str,
df: pd.DataFrame,
) -> str:
"""Returns the experiment filestore path for |fuzzer| and |benchmark| in
|df|. Returns an arbitrary filestore path if there are multiple."""
df = df[df['fuzzer'] == fuzzer]
df = df[df['benchmark'] == benchmark]
experiment_filestore_paths = get_experiment_filestore_paths(df)
fuzzer_benchmark_filestore_path = experiment_filestore_paths[0]
if len(experiment_filestore_paths) != 1:
logger.warning(
'Multiple cov filestores (%s) for this fuzzer (%s) benchmark (%s) '
'pair. Using first: %s.', experiment_filestore_paths, fuzzer,
benchmark, fuzzer_benchmark_filestore_path)
return fuzzer_benchmark_filestore_path
def get_experiment_filestore_paths(df: pd.DataFrame) -> List[str]:
"""Returns a list of experiment filestore paths from |df|."""
return list((df['experiment_filestore'] + '/' + df['experiment']).unique())
def get_coverage_report_filestore_path(fuzzer: str, benchmark: str,
df: pd.DataFrame) -> str:
"""Returns the filestore path of the coverage report for |fuzzer| on
|benchmark| for |df|."""
exp_filestore_path = get_experiment_filestore_path_for_fuzzer_benchmark(
fuzzer, benchmark, df)
return posixpath.join(exp_filestore_path, 'coverage', 'reports', benchmark,
fuzzer, 'index.html')
def get_covered_regions_dict(experiment_df: pd.DataFrame) -> Dict:
"""Combines json files for different fuzzer-benchmark pair in
|experiment_df| and returns a dictionary of the covered regions."""
fuzzers_and_benchmarks = set(
zip(experiment_df.fuzzer, experiment_df.benchmark))
arguments = [(fuzzer, benchmark,
get_experiment_filestore_path_for_fuzzer_benchmark(
fuzzer, benchmark, experiment_df))
for fuzzer, benchmark in fuzzers_and_benchmarks]
result = itertools.starmap(get_fuzzer_benchmark_covered_regions_and_key,
arguments)
return dict(result)
def get_fuzzer_benchmark_covered_regions_filestore_path(
fuzzer: str, benchmark: str, exp_filestore_path: str) -> str:
"""Returns the path to the covered regions json file in the |filestore| for
|fuzzer| and |benchmark|."""
return posixpath.join(exp_filestore_path, 'coverage', 'data', benchmark,
fuzzer, 'covered_regions.json')
def get_fuzzer_covered_regions(fuzzer: str, benchmark: str, filestore: str):
"""Returns the covered regions dict for |fuzzer| from the json file in the
filestore."""
src_file = get_fuzzer_benchmark_covered_regions_filestore_path(
fuzzer, benchmark, filestore)
with tempfile.NamedTemporaryFile() as dst_file:
if filestore_utils.cp(src_file, dst_file.name,
expect_zero=False).retcode:
logger.warning('covered_regions.json file: %s could not be copied.',
src_file)
return {}
with open(dst_file.name) as json_file:
return json.load(json_file)
def get_fuzzer_benchmark_covered_regions_and_key(
fuzzer: str, benchmark: str, filestore: str) -> Tuple[str, Dict]:
"""Accepts |fuzzer|, |benchmark|, |filestore|.
Returns a tuple containing the fuzzer benchmark key and the regions covered
by the fuzzer on the benchmark."""
fuzzer_benchmark_covered_regions = get_fuzzer_covered_regions(
fuzzer, benchmark, filestore)
key = fuzzer_and_benchmark_to_key(fuzzer, benchmark)
return key, fuzzer_benchmark_covered_regions
def get_unique_region_dict(benchmark_coverage_dict: Dict) -> Dict:
"""Returns a dictionary containing the covering fuzzers for each unique
region, where the |threshold| defines which regions are unique."""
region_dict = collections.defaultdict(list)
unique_region_dict = {}
threshold_count = 1
for fuzzer in benchmark_coverage_dict:
for region in benchmark_coverage_dict[fuzzer]:
region_dict[region].append(fuzzer)
for region, fuzzers in region_dict.items():
if len(fuzzers) <= threshold_count:
unique_region_dict[region] = fuzzers
return unique_region_dict
def get_unique_region_cov_df(unique_region_dict: Dict,
fuzzer_names: List[str]) -> pd.DataFrame:
"""Returns a DataFrame where the two columns are fuzzers and the number of
unique regions covered."""
fuzzers = collections.defaultdict(int)
for region in unique_region_dict:
for fuzzer in unique_region_dict[region]:
fuzzers[fuzzer] += 1
dict_to_transform = {'fuzzer': [], 'unique_regions_covered': []}
for fuzzer in fuzzer_names:
covered_num = fuzzers[fuzzer]
dict_to_transform['fuzzer'].append(fuzzer)
dict_to_transform['unique_regions_covered'].append(covered_num)
return pd.DataFrame(dict_to_transform)
def get_benchmark_cov_dict(coverage_dict, benchmark):
"""Returns a dictionary to store the covered regions of each fuzzer. Uses a
set of tuples to store the covered regions."""
benchmark_cov_dict = {}
for key, covered_regions in coverage_dict.items():
current_fuzzer, current_benchmark = key_to_fuzzer_and_benchmark(key)
if current_benchmark == benchmark:
covered_regions_in_set = set()
for region in covered_regions:
covered_regions_in_set.add(tuple(region))
benchmark_cov_dict[current_fuzzer] = covered_regions_in_set
return benchmark_cov_dict
def get_benchmark_aggregated_cov_df(coverage_dict, benchmark):
"""Returns a dataframe where each row represents a fuzzer and its aggregated
coverage number."""
dict_to_transform = {'fuzzer': [], 'aggregated_edges_covered': []}
for key, covered_regions in coverage_dict.items():
current_fuzzer, current_benchmark = key_to_fuzzer_and_benchmark(key)
if current_benchmark == benchmark:
dict_to_transform['fuzzer'].append(current_fuzzer)
dict_to_transform['aggregated_edges_covered'].append(
len(covered_regions))
return pd.DataFrame(dict_to_transform)
def get_pairwise_unique_coverage_table(benchmark_coverage_dict, fuzzers):
"""Returns a table that shows the unique coverage between each pair of
fuzzers.
The pairwise unique coverage table is a square matrix where each
row and column represents a fuzzer, and each cell contains a number
showing the regions covered by the fuzzer of the column but not by
the fuzzer of the row."""
pairwise_unique_coverage_values = []
for fuzzer_in_row in fuzzers:
row = []
for fuzzer_in_col in fuzzers:
pairwise_unique_coverage_value = get_unique_covered_percentage(
benchmark_coverage_dict[fuzzer_in_row],
benchmark_coverage_dict[fuzzer_in_col])
row.append(pairwise_unique_coverage_value)
pairwise_unique_coverage_values.append(row)
return pd.DataFrame(pairwise_unique_coverage_values,
index=fuzzers,
columns=fuzzers)
def get_unique_covered_percentage(fuzzer_row_covered_regions,
fuzzer_col_covered_regions):
"""Returns the number of regions covered by the fuzzer of the column but not
by the fuzzer of the row."""
unique_region_count = 0
for region in fuzzer_col_covered_regions:
if region not in fuzzer_row_covered_regions:
unique_region_count += 1
return unique_region_count
def rank_by_average_normalized_score(benchmarks_unique_coverage_list):
"""Returns the rank based on average normalized score on unique coverage."""
df_list = [df.set_index('fuzzer') for df in benchmarks_unique_coverage_list]
combined_df = pd.concat(df_list, axis=1).astype(float).T
scores = data_utils.experiment_rank_by_average_normalized_score(combined_df)
return scores
|
google/fuzzbench
|
analysis/coverage_data_utils.py
|
Python
|
apache-2.0
| 9,404 | 0.000638 |
"""Utilities for running individual tests"""
import itertools
import os
import re
import time
from cram._diff import esc, glob, regex, unified_diff
from cram._process import PIPE, STDOUT, execute
__all__ = ['test', 'testfile']
_needescape = re.compile(br'[\x00-\x09\x0b-\x1f\x7f-\xff]').search
_escapesub = re.compile(br'[\x00-\x09\x0b-\x1f\\\x7f-\xff]').sub
_escapemap = dict((bytes([i]), br'\x%02x' % i) for i in range(256))
_escapemap.update({b'\\': b'\\\\', b'\r': br'\r', b'\t': br'\t'})
def _escape(s):
"""Like the string-escape codec, but doesn't escape quotes"""
return (_escapesub(lambda m: _escapemap[m.group(0)], s[:-1]) +
b' (esc)\n')
def test(lines, shell='/bin/sh', indent=2, testname=None, env=None,
cleanenv=True, debug=False):
r"""Run test lines and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator that yields the diff between the two lists.
If a test exits with return code 80, the actual output is set to
None and diff is set to [].
Note that the TESTSHELL environment variable is available in the
test (set to the specified shell). However, the TESTDIR and
TESTFILE environment variables are not available. To run actual
test files, see testfile().
Example usage:
>>> refout, postout, diff = test([b' $ echo hi\n',
... b' [a-z]{2} (re)\n'])
>>> refout == [b' $ echo hi\n', b' [a-z]{2} (re)\n']
True
>>> postout == [b' $ echo hi\n', b' hi\n']
True
>>> bool(diff)
False
lines may also be a single bytes string:
>>> refout, postout, diff = test(b' $ echo hi\n bye\n')
>>> refout == [b' $ echo hi\n', b' bye\n']
True
>>> postout == [b' $ echo hi\n', b' hi\n']
True
>>> bool(diff)
True
>>> (b''.join(diff) ==
... b'--- \n+++ \n@@ -1,2 +1,2 @@\n $ echo hi\n- bye\n+ hi\n')
True
:param lines: Test input
:type lines: bytes or collections.Iterable[bytes]
:param shell: Shell to run test in
:type shell: bytes or str or list[bytes] or list[str]
:param indent: Amount of indentation to use for shell commands
:type indent: int
:param testname: Optional test file name (used in diff output)
:type testname: bytes or None
:param env: Optional environment variables for the test shell
:type env: dict or None
:param cleanenv: Whether or not to sanitize the environment
:type cleanenv: bool
:param debug: Whether or not to run in debug mode (don't capture stdout)
:type debug: bool
return: Input, output, and diff iterables
:rtype: (list[bytes], list[bytes], collections.Iterable[bytes])
"""
indent = b' ' * indent
cmdline = indent + b'$ '
conline = indent + b'> '
salt = b'CRAM%.5f' % time.time()
if env is None:
env = os.environ.copy()
if cleanenv:
for s in ('LANG', 'LC_ALL', 'LANGUAGE'):
env[s] = 'C'
env['TZ'] = 'GMT'
env['CDPATH'] = ''
env['COLUMNS'] = '80'
env['GREP_OPTIONS'] = ''
if isinstance(lines, bytes):
lines = lines.splitlines(True)
if isinstance(shell, (bytes, str)):
shell = [shell]
env['TESTSHELL'] = shell[0]
if debug:
stdin = []
for line in lines:
if not line.endswith(b'\n'):
line += b'\n'
if line.startswith(cmdline):
stdin.append(line[len(cmdline):])
elif line.startswith(conline):
stdin.append(line[len(conline):])
execute(shell + ['-'], stdin=b''.join(stdin), env=env)
return ([], [], [])
after = {}
refout, postout = [], []
i = pos = prepos = -1
stdin = []
for i, line in enumerate(lines):
if not line.endswith(b'\n'):
line += b'\n'
refout.append(line)
if line.startswith(cmdline):
after.setdefault(pos, []).append(line)
prepos = pos
pos = i
stdin.append(b'echo %s %d $?\n' % (salt, i))
stdin.append(line[len(cmdline):])
elif line.startswith(conline):
after.setdefault(prepos, []).append(line)
stdin.append(line[len(conline):])
elif not line.startswith(indent):
after.setdefault(pos, []).append(line)
stdin.append(b'echo %s %d $?\n' % (salt, i + 1))
output, retcode = execute(shell + ['-'], stdin=b''.join(stdin),
stdout=PIPE, stderr=STDOUT, env=env)
if retcode == 80:
return (refout, None, [])
pos = -1
ret = 0
for i, line in enumerate(output[:-1].splitlines(True)):
out, cmd = line, None
if salt in line:
out, cmd = line.split(salt, 1)
if out:
if not out.endswith(b'\n'):
out += b' (no-eol)\n'
if _needescape(out):
out = _escape(out)
postout.append(indent + out)
if cmd:
ret = int(cmd.split()[1])
if ret != 0:
postout.append(indent + b'[%d]\n' % ret)
postout += after.pop(pos, [])
pos = int(cmd.split()[0])
postout += after.pop(pos, [])
if testname:
diffpath = testname
errpath = diffpath + b'.err'
else:
diffpath = errpath = b''
diff = unified_diff(refout, postout, diffpath, errpath,
matchers=[esc, glob, regex])
for firstline in diff:
return refout, postout, itertools.chain([firstline], diff)
return refout, postout, []
def testfile(path, shell='/bin/sh', indent=2, env=None, cleanenv=True,
debug=False, testname=None):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator that yields the diff between the two lists.
If a test exits with return code 80, the actual output is set to
None and diff is set to [].
Note that the TESTDIR, TESTFILE, and TESTSHELL environment
variables are available to use in the test.
:param path: Path to test file
:type path: bytes or str
:param shell: Shell to run test in
:type shell: bytes or str or list[bytes] or list[str]
:param indent: Amount of indentation to use for shell commands
:type indent: int
:param env: Optional environment variables for the test shell
:type env: dict or None
:param cleanenv: Whether or not to sanitize the environment
:type cleanenv: bool
:param debug: Whether or not to run in debug mode (don't capture stdout)
:type debug: bool
:param testname: Optional test file name (used in diff output)
:type testname: bytes or None
:return: Input, output, and diff iterables
:rtype: (list[bytes], list[bytes], collections.Iterable[bytes])
"""
f = open(path, 'rb')
try:
abspath = os.path.abspath(path)
env = env or os.environ.copy()
env['TESTDIR'] = os.fsdecode(os.path.dirname(abspath))
env['TESTFILE'] = os.fsdecode(os.path.basename(abspath))
if testname is None: # pragma: nocover
testname = os.path.basename(abspath)
return test(f, shell, indent=indent, testname=testname, env=env,
cleanenv=cleanenv, debug=debug)
finally:
f.close()
|
brodie/cram
|
cram/_test.py
|
Python
|
gpl-2.0
| 7,518 | 0.000532 |
#!/usr/bin/env python
import os, sys
from Bio import SeqIO
from Bio.Blast import NCBIWWW
from time import sleep
from helpers import parse_fasta, get_opts
def usage():
print """Usage: blast_fasta.py [OPTIONS] seqs.fasta
Options:
-t blast_type blastn, blastp, blastx, tblastn, tblastx, default: blastn
-o out_dir output directory, default: current directory
-p out_prefix prefix for output file names, default: blast_
"""
def run_blast(seq, blast_type='blastn'):
delay = 2
while True:
try:
result = NCBIWWW.qblast(blast_type, 'nr', seq.format('fasta')).getvalue()
sleep(delay)
return result
except urllib2.HTTPError: # something went wrong, increase delay and try again
delay *= 2
if __name__=='__main__':
try:
opts = get_opts(sys.argv[1:], 't:o:p:')
fasta_path = opts[1][0]
opts = dict(opts[0])
except:
usage()
exit(1)
blast_type = opts.get('-t', 'blastn')
out_dir = opts.get('-o', os.getcwd())
out_prefix = opts.get('-p', 'blast_')
seqs = parse_fasta(fasta_path)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
for seq in seqs:
print 'Running BLAST for ' + seq.id + '... ',
blast_xml_str = run_blast(seq, blast_type)
with open(os.path.join(out_dir, out_prefix + seq.id + '.xml'), 'w') as f:
f.write(blast_xml_str)
print 'completed'
|
Serpens/small_bioinfo
|
blast_fasta.py
|
Python
|
gpl-3.0
| 1,496 | 0.007353 |
from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb = DiaryDB(self.TEMP_DB_PATH)
self.logdb_default = DiaryDB()
@classmethod
def tearDownClass(cls):
import os
os.remove(cls.TEMP_DB_PATH)
def constructs_correctly(self):
self.assertIsInstance(self.logdb.conn, sqlite3.Connection)
self.assertIsInstance(self.logdb.cursor, sqlite3.Cursor)
def test_creates_table(self):
table = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND name="logs"
''').fetchone()[0]
self.assertEquals(table, 'logs')
def test_creates_table_already_exists(self):
self.logdb.create_tables()
tables = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND name="logs"
''').fetchall()
self.assertEquals(len(tables), 1)
def test_log(self):
self.logdb.log(self.SIMPLE_EVENT)
entry = self.logdb.cursor.execute('''SELECT * FROM logs ORDER BY
inputDT ASC LIMIT 1''').fetchone()
self.assertEquals(entry[0], self.SIMPLE_EVENT.dt)
self.assertEquals(entry[1], self.SIMPLE_EVENT.level)
self.assertEquals(entry[2], self.SIMPLE_EVENT.info)
def test_close(self):
self.logdb.close()
with self.assertRaises(sqlite3.ProgrammingError,
msg="Cannot operate on a closed database."):
self.logdb.conn.execute("SELECT 1 FROM logs LIMIT 1")
def test_default_path(self):
self.logdb_default.log(self.SIMPLE_EVENT)
entry = self.logdb_default.cursor.execute('''SELECT * FROM logs ORDER BY
inputDT DESC LIMIT 1''').fetchone()
self.assertEquals(entry[0], self.SIMPLE_EVENT.dt)
self.assertEquals(entry[1], self.SIMPLE_EVENT.level)
self.assertEquals(entry[2], self.SIMPLE_EVENT.info)
self.logdb_default.close()
if __name__ == '__main__':
unittest.main()
|
GreenVars/diary
|
tests/logdb_test.py
|
Python
|
mit
| 2,455 | 0.002037 |
import time
import datetime
import oauth2 as oauth
from provider import scope as oauth2_provider_scope
from rest_framework.test import APIClient
from rest_framework_oauth.authentication import (
oauth2_provider,
OAuthAuthentication,
OAuth2Authentication
)
from rest_framework import status, permissions
from rest_framework.views import APIView
from django.conf.urls import patterns, include, url
from django.http import HttpResponse
from django.utils.http import urlencode
from django.test import TestCase
from django.contrib.auth.models import User
class OAuth2AuthenticationDebug(OAuth2Authentication):
allow_query_params_token = True
class MockView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
def post(self, request):
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
def put(self, request):
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
urlpatterns = patterns(
'',
(r'^oauth/$', MockView.as_view(authentication_classes=[OAuthAuthentication])),
(
r'^oauth-with-scope/$',
MockView.as_view(
authentication_classes=[OAuthAuthentication],
permission_classes=[permissions.TokenHasReadWriteScope]
)
),
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
url(r'^oauth2-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication])),
url(r'^oauth2-test-debug/$', MockView.as_view(authentication_classes=[OAuth2AuthenticationDebug])),
url(
r'^oauth2-with-scope-test/$',
MockView.as_view(
authentication_classes=[OAuth2Authentication],
permission_classes=[permissions.TokenHasReadWriteScope]
)
)
)
class OAuthTests(TestCase):
"""OAuth 1.0a authentication"""
urls = 'tests.test_oauth'
def setUp(self):
# these imports are here because oauth is optional and hiding them in try..except block or compat
# could obscure problems if something breaks
from oauth_provider.models import Consumer, Scope
from oauth_provider.models import Token as OAuthToken
from oauth_provider import consts
self.consts = consts
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
self.email = 'lennon@thebeatles.com'
self.password = 'password'
self.user = User.objects.create_user(self.username, self.email, self.password)
self.CONSUMER_KEY = 'consumer_key'
self.CONSUMER_SECRET = 'consumer_secret'
self.TOKEN_KEY = "token_key"
self.TOKEN_SECRET = "token_secret"
self.consumer = Consumer.objects.create(
key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
name='example', user=self.user, status=self.consts.ACCEPTED
)
self.scope = Scope.objects.create(name="resource name", url="api/")
self.token = OAuthToken.objects.create(
user=self.user, consumer=self.consumer, scope=self.scope,
token_type=OAuthToken.ACCESS, key=self.TOKEN_KEY, secret=self.TOKEN_SECRET,
is_approved=True
)
def _create_authorization_header(self):
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
'oauth_token': self.token.key,
'oauth_consumer_key': self.consumer.key
}
req = oauth.Request(method="GET", url="http://example.com", parameters=params)
signature_method = oauth.SignatureMethod_PLAINTEXT()
req.sign_request(signature_method, self.consumer, self.token)
return req.to_header()["Authorization"]
def _create_authorization_url_parameters(self):
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
'oauth_token': self.token.key,
'oauth_consumer_key': self.consumer.key
}
req = oauth.Request(method="GET", url="http://example.com", parameters=params)
signature_method = oauth.SignatureMethod_PLAINTEXT()
req.sign_request(signature_method, self.consumer, self.token)
return dict(req)
def test_post_form_passing_oauth(self):
"""Ensure POSTing form over OAuth with correct credentials passes and does not require CSRF"""
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_form_repeated_nonce_failing_oauth(self):
"""Ensure POSTing form over OAuth with repeated auth (same nonces and timestamp) credentials fails"""
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
# simulate reply attack auth header containes already used (nonce, timestamp) pair
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_token_removed_failing_oauth(self):
"""Ensure POSTing when there is no OAuth access token in db fails"""
self.token.delete()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_consumer_status_not_accepted_failing_oauth(self):
"""Ensure POSTing when consumer status is anything other than ACCEPTED fails"""
for consumer_status in (self.consts.CANCELED, self.consts.PENDING, self.consts.REJECTED):
self.consumer.status = consumer_status
self.consumer.save()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_with_request_token_failing_oauth(self):
"""Ensure POSTing with unauthorized request token instead of access token fails"""
self.token.token_type = self.token.REQUEST
self.token.save()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_with_urlencoded_parameters(self):
"""Ensure POSTing with x-www-form-urlencoded auth parameters passes"""
params = self._create_authorization_url_parameters()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', params, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_get_form_with_url_parameters(self):
"""Ensure GETing with auth in url parameters passes"""
params = self._create_authorization_url_parameters()
response = self.csrf_client.get('/oauth/', params)
self.assertEqual(response.status_code, 200)
def test_post_hmac_sha1_signature_passes(self):
"""Ensure POSTing using HMAC_SHA1 signature method passes"""
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
'oauth_token': self.token.key,
'oauth_consumer_key': self.consumer.key
}
req = oauth.Request(method="POST", url="http://testserver/oauth/", parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, self.consumer, self.token)
auth = req.to_header()["Authorization"]
response = self.csrf_client.post('/oauth/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_get_form_with_readonly_resource_passing_auth(self):
"""Ensure POSTing with a readonly scope instead of a write scope fails"""
read_only_access_token = self.token
read_only_access_token.scope.is_readonly = True
read_only_access_token.scope.save()
params = self._create_authorization_url_parameters()
response = self.csrf_client.get('/oauth-with-scope/', params)
self.assertEqual(response.status_code, 200)
def test_post_form_with_readonly_resource_failing_auth(self):
"""Ensure POSTing with a readonly resource instead of a write scope fails"""
read_only_access_token = self.token
read_only_access_token.scope.is_readonly = True
read_only_access_token.scope.save()
params = self._create_authorization_url_parameters()
response = self.csrf_client.post('/oauth-with-scope/', params)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_with_write_resource_passing_auth(self):
"""Ensure POSTing with a write resource succeed"""
read_write_access_token = self.token
read_write_access_token.scope.is_readonly = False
read_write_access_token.scope.save()
params = self._create_authorization_url_parameters()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth-with-scope/', params, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_bad_consumer_key(self):
"""Ensure POSTing using HMAC_SHA1 signature method passes"""
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
'oauth_token': self.token.key,
'oauth_consumer_key': 'badconsumerkey'
}
req = oauth.Request(method="POST", url="http://testserver/oauth/", parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, self.consumer, self.token)
auth = req.to_header()["Authorization"]
response = self.csrf_client.post('/oauth/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
def test_bad_token_key(self):
"""Ensure POSTing using HMAC_SHA1 signature method passes"""
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
'oauth_token': 'badtokenkey',
'oauth_consumer_key': self.consumer.key
}
req = oauth.Request(method="POST", url="http://testserver/oauth/", parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, self.consumer, self.token)
auth = req.to_header()["Authorization"]
response = self.csrf_client.post('/oauth/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
class OAuth2Tests(TestCase):
"""OAuth 2.0 authentication"""
urls = 'tests.test_oauth'
def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
self.email = 'lennon@thebeatles.com'
self.password = 'password'
self.user = User.objects.create_user(self.username, self.email, self.password)
self.CLIENT_ID = 'client_key'
self.CLIENT_SECRET = 'client_secret'
self.ACCESS_TOKEN = "access_token"
self.REFRESH_TOKEN = "refresh_token"
self.oauth2_client = oauth2_provider.oauth2.models.Client.objects.create(
client_id=self.CLIENT_ID,
client_secret=self.CLIENT_SECRET,
redirect_uri='',
client_type=0,
name='example',
user=None,
)
self.access_token = oauth2_provider.oauth2.models.AccessToken.objects.create(
token=self.ACCESS_TOKEN,
client=self.oauth2_client,
user=self.user,
)
self.refresh_token = oauth2_provider.oauth2.models.RefreshToken.objects.create(
user=self.user,
access_token=self.access_token,
client=self.oauth2_client
)
def _create_authorization_header(self, token=None):
return "Bearer {0}".format(token or self.access_token.token)
def test_get_form_with_wrong_authorization_header_token_type_failing(self):
"""Ensure that a wrong token type lead to the correct HTTP error status code"""
auth = "Wrong token-type-obsviously"
response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
response = self.csrf_client.get('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
def test_get_form_with_wrong_authorization_header_token_format_failing(self):
"""Ensure that a wrong token format lead to the correct HTTP error status code"""
auth = "Bearer wrong token format"
response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
response = self.csrf_client.get('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
def test_get_form_with_wrong_authorization_header_token_failing(self):
"""Ensure that a wrong token lead to the correct HTTP error status code"""
auth = "Bearer wrong-token"
response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
response = self.csrf_client.get('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
def test_get_form_with_wrong_authorization_header_token_missing(self):
"""Ensure that a missing token lead to the correct HTTP error status code"""
auth = "Bearer"
response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
response = self.csrf_client.get('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 401)
def test_get_form_passing_auth(self):
"""Ensure GETing form over OAuth with correct client credentials succeed"""
auth = self._create_authorization_header()
response = self.csrf_client.get('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_form_passing_auth_url_transport(self):
"""Ensure GETing form over OAuth with correct client credentials in form data succeed"""
response = self.csrf_client.post(
'/oauth2-test/',
data={'access_token': self.access_token.token}
)
self.assertEqual(response.status_code, 200)
def test_get_form_passing_auth_url_transport(self):
"""Ensure GETing form over OAuth with correct client credentials in query succeed when DEBUG is True"""
query = urlencode({'access_token': self.access_token.token})
response = self.csrf_client.get('/oauth2-test-debug/?%s' % query)
self.assertEqual(response.status_code, 200)
def test_get_form_failing_auth_url_transport(self):
"""Ensure GETing form over OAuth with correct client credentials in query fails when DEBUG is False"""
query = urlencode({'access_token': self.access_token.token})
response = self.csrf_client.get('/oauth2-test/?%s' % query)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_passing_auth(self):
"""Ensure POSTing form over OAuth with correct credentials passes and does not require CSRF"""
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
def test_post_form_token_removed_failing_auth(self):
"""Ensure POSTing when there is no OAuth access token in db fails"""
self.access_token.delete()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_with_refresh_token_failing_auth(self):
"""Ensure POSTing with refresh token instead of access token fails"""
auth = self._create_authorization_header(token=self.refresh_token.token)
response = self.csrf_client.post('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
def test_post_form_with_expired_access_token_failing_auth(self):
"""Ensure POSTing with expired access token fails with an 'Invalid token' error"""
self.access_token.expires = datetime.datetime.now() - datetime.timedelta(seconds=10) # 10 seconds late
self.access_token.save()
auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth2-test/', HTTP_AUTHORIZATION=auth)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
self.assertIn('Invalid token', response.content)
def test_post_form_with_invalid_scope_failing_auth(self):
"""Ensure POSTing with a readonly scope instead of a write scope fails"""
read_only_access_token = self.access_token
read_only_access_token.scope = oauth2_provider_scope.SCOPE_NAME_DICT['read']
read_only_access_token.save()
auth = self._create_authorization_header(token=read_only_access_token.token)
response = self.csrf_client.get('/oauth2-with-scope-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
response = self.csrf_client.post('/oauth2-with-scope-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_post_form_with_valid_scope_passing_auth(self):
"""Ensure POSTing with a write scope succeed"""
read_write_access_token = self.access_token
read_write_access_token.scope = oauth2_provider_scope.SCOPE_NAME_DICT['write']
read_write_access_token.save()
auth = self._create_authorization_header(token=read_write_access_token.token)
response = self.csrf_client.post('/oauth2-with-scope-test/', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200)
|
jlafon/django-rest-framework-oauth
|
tests/test_oauth.py
|
Python
|
mit
| 19,202 | 0.003854 |
# -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2015 Thomas Perl and the gPodder Team
#
# gPodder 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.
#
# gPodder 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
|
daneoshiga/gpodder
|
src/gpodder/gtkui/interface/__init__.py
|
Python
|
gpl-3.0
| 764 | 0.001309 |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
doc2md.py generates Python documentation in the Markdown (md) format. It was
written to automatically generate documentation that can be put on Github
or Bitbucket wiki pages. It is initially based on Ferry Boender's pydocmd.
It is as of yet not very complete and is more of a Proof-of-concept than a
fully-fledged tool. Markdown is also a very restricted format and every
implementation works subtly, or completely, different. This means output
may be different on different converters.
## Usage
$ python doc2md.py module [...]
doc2md.py scans every python file (.py) given and generates the documentation
in a subfolder `doc`.
## Example output
- http://github.com/blasterbug/doc2md.py/wiki/doc2md
- http://github.com/blasterbug/SmileANN/wiki/neuron
- http://github.com/blasterbug/SmileANN/wiki/faces
"""
import sys
import os
import imp
import inspect
__author__ = "Benjamin Sientzoff"
__version__ = "0.1.2b"
__maintainer__ = "Benjamin Sientzoff (blasterbug)"
__license__ = "GNU GPL V2"
def remove_extension( fl ):
"""
Remove extention from the program file name
"""
# does not handle mutiple dots
return str(fl).split('.')[0]
def fmt_doc(doc, indent=''):
"""
Format a doc-string.
"""
s = ''
for line in doc.lstrip().splitlines():
s += '%s%s \n' % (indent, line.strip())
return s.rstrip()
def insp_file(file_name):
"""
Inspect a file and return module information
"""
mod_inst = imp.load_source(remove_extension( file_name ), file_name)
if not mod_inst:
sys.stderr.write("Failed to import '%s'\n" % (file_name))
sys.exit(2)
mod_name = inspect.getmodulename(file_name)
if not mod_name:
mod_name = os.path.splitext(os.path.basename(file_name))[0]
return insp_mod(mod_name, mod_inst)
def insp_mod(mod_name, mod_inst):
"""
Inspect a module return doc, vars, functions and classes.
"""
info = {
'name': mod_name,
'inst': mod_inst,
'author': {},
'doc': '',
'vars': [],
'functions': [],
'classes': [],
}
# Get module documentation
mod_doc = inspect.getdoc(mod_inst)
if mod_doc:
info['doc'] = mod_doc
for attr_name in ['author', 'copyright', 'license', 'version', 'maintainer', 'email']:
if hasattr(mod_inst, '__%s__' % (attr_name)):
info['author'][attr_name] = getattr(mod_inst, '__%s__' % (attr_name))
# Get module global vars
for member_name, member_inst in inspect.getmembers(mod_inst):
if not member_name.startswith('_') and \
not inspect.isfunction(member_inst) and \
not inspect.isclass(member_inst) and \
not inspect.ismodule(member_inst) and \
member_inst.__module__ == mod_name and \
member_name not in mod_inst.__builtins__:
info['vars'].append( (member_name, member_inst) )
# Get module functions
functions = inspect.getmembers(mod_inst, inspect.isfunction)
if functions:
for func_name, func_inst in functions:
if func_inst.__module__ == mod_name :
info['functions'].append(insp_method(func_name, func_inst))
# Get module classes
classes = inspect.getmembers(mod_inst, inspect.isclass)
if classes:
for class_name, class_inst in classes:
if class_inst.__module__ == mod_name :
info['classes'].append(insp_class(class_name, class_inst))
return info
def insp_class(class_name, class_inst):
"""
Inspect class and return doc, methods.
"""
info = {
'name': class_name,
'inst': class_inst,
'doc': '',
'methods': [],
}
# Get class documentation
class_doc = inspect.getdoc(class_inst)
# if class_doc:
#info['doc'] = fmt_doc(class_doc)
# Get class methods
methods = inspect.getmembers(class_inst, inspect.ismethod)
for method_name, method_inst in methods:
info['methods'].append(insp_method(method_name, method_inst))
return info
def insp_method(method_name, method_inst):
"""
Inspect a method and return arguments, doc.
"""
info = {
'name': method_name,
'inst': method_inst,
'args': [],
'doc': ''
}
# Get method arguments
method_args = inspect.getargspec(method_inst)
for arg in method_args.args:
if arg != 'self':
info['args'].append(arg)
# Apply default argumument values to arguments
if method_args.defaults:
a_pos = len(info['args']) - len(method_args.defaults)
for pos, default in enumerate(method_args.defaults):
info['args'][a_pos + pos] = '%s=%s' % (info['args'][a_pos + pos], default)
# Print method documentation
method_doc = inspect.getdoc(method_inst)
if method_doc:
info['doc'] = fmt_doc(method_doc)
return info
def to_markdown( text_block ) :
"""
Markdownify an inspect file
:param text_block: inspect file to turn to Markdown
:return: Markdown doc into a string
"""
doc_output = ("# %s \n" % file_i['name'] )
doc_output += file_i['doc'] + ' \n'
author = ''
if 'author' in file_i['author']:
author += file_i['author']['author'] + ' '
if 'email' in file_i['author']:
author += '<%s>' % (file_i['author']['email'])
if author:
doc_output += str("\n __Author__: %s \n" % author )
author_attrs = [
('Version', 'version'),
('Copyright', 'copyright'),
('License', 'license'),
]
for attr_friendly, attr_name in author_attrs:
if attr_name in file_i['author']:
doc_output += " __%s__: %s \n" % (attr_friendly, file_i['author'][attr_name])
if file_i['vars']:
doc_output += "\n## Variables\n"
for var_name, var_inst in file_i['vars']:
doc_output += " - `%s`: %s\n" % (var_name, var_inst)
if file_i['functions']:
doc_output += "\n\n## Functions\n"
for function_i in file_i['functions']:
if function_i['name'].startswith('_'):
continue
doc_output += "\n\n### `%s(%s)`\n" % (function_i['name'], ', '.join(function_i['args']))
if function_i['doc']:
doc_output += "%s" % (function_i['doc'])
else:
doc_output += "No documentation for this function "
if file_i['classes']:
doc_output += "\n\n## Classes\n"
for class_i in file_i['classes']:
doc_output += "\n\n### class `%s()`\n" % (class_i['name'])
if class_i['doc']:
doc_output += "%s " % (class_i['doc'])
else:
doc_output += "No documentation for this class "
doc_output += "\n\n### Methods:\n"
for method_i in class_i['methods']:
if method_i['name'] != '__init__' and method_i['name'].startswith('_'):
continue
doc_output += "\n\n#### def `%s(%s)`\n" % (method_i['name'], ', '.join(method_i['args']))
doc_output += "%s " % (method_i['doc'])
return doc_output
if __name__ == '__main__':
if 1 < len(sys.argv) :
doc_dir = "doc"
for arg in sys.argv[1:] :
file_i = insp_file(arg)
doc_content = to_markdown(file_i)
if not os.path.exists( doc_dir ) :
os.makedirs( doc_dir )
doc_file = open( doc_dir + "/" + remove_extension(arg) + ".md", 'w')
sys.stdout.write( "Writing documentation for %s in doc/\n" % arg )
doc_file.write( doc_content )
doc_file.close()
else:
sys.stderr.write('Usage: %s <file.py>\n' % (sys.argv[0]))
sys.exit(1)
|
blasterbug/doc2md.py
|
doc2md.py
|
Python
|
gpl-2.0
| 7,823 | 0.005497 |
#!/usr/bin/env python
import sys
import textwrap
names = sorted(sys.modules.keys())
name_text = ', '.join(names)
print textwrap.fill(name_text)
|
talapus/Ophidian
|
Academia/Modules/list_all_installed_modules.py
|
Python
|
bsd-3-clause
| 147 | 0 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Created Time: Fri Jul 17 00:58:20 2015
# Purpose: generate a bidirected graph
# Mail: hewr2010@gmail.com
__author__ = "Wayne Ho"
import sys
import random
if __name__ == "__main__":
if len(sys.argv) < 3:
print("./%s [#vertices] [#edges]" % sys.argv[0])
exit()
n, m = int(sys.argv[1]), int(sys.argv[2])
print n, m
pool = {}
for i in xrange(m):
while True:
x, y = int(n * random.random()), int(n * random.random())
if x > y:
x, y = y, x
if x == y:
continue
if (x, y) not in pool:
break
pool[(x, y)] = True
print x, y
|
manene/SAE_Sampling
|
spark/genGraph.py
|
Python
|
mit
| 715 | 0 |
import site
import sys, os
from peewee import *
import datetime
import time
import calendar
import sqlite3
import gzip
import shutil
#-----------------------------------------------------------------------
if os.path.exists('/storage/extSdCard'):
database = SqliteDatabase('/storage/extSdCard/mydb/lessonplan2010.db', **{})
backupdir = '/storage/extSdCard/dbbackup/'
db = '/storage/extSdCard/mydb/lessonplan2010.db'
else:
database = SqliteDatabase('lessonplan2010.db', **{})
class BaseModel(Model):
class Meta:
database = database
class Lessonplanbank(BaseModel):
activity1 = CharField(null=True)
activity2 = CharField(null=True)
assimilation = CharField(null=True)
bank = PrimaryKeyField(db_column='bank_id', null=True)
content = CharField(null=True)
duration = CharField(null=True)
exercise = TextField(null=True)
handout = TextField(null=True)
impact = CharField(null=True)
level = CharField(null=True)
lo1 = CharField(null=True)
lo2 = CharField(null=True)
lo3 = CharField(null=True)
note = CharField(null=True)
theme = CharField(null=True)
tingkatan = CharField(null=True)
topic = CharField(null=True)
week = IntegerField(null=True)
class Meta:
db_table = 'lessonplanbank'
class Lessonplan2016(BaseModel):
activity1 = CharField(null=True)
activity2 = CharField(null=True)
assimilation = CharField(null=True)
content = CharField(null=True)
date = IntegerField(null=True)
duration = CharField(null=True)
exercise = TextField(null=True)
handout = TextField(null=True)
impact = CharField(null=True)
lo1 = CharField(null=True)
lo2 = CharField(null=True)
lo3 = CharField(null=True)
note = CharField(null=True)
theme = CharField(null=True)
timeend = CharField(null=True)
timestart = CharField(null=True)
tingkatan = CharField(null=True)
topic = CharField(null=True)
week = CharField(null=True)
class Meta:
db_table = 'lessonplan2016'
database.connect()
def create_tables():
database.connect()
database.create_tables([Lessonplan2016,])
create_tables()
|
mwbetrg/skripbatak
|
createlp2016table.py
|
Python
|
bsd-3-clause
| 2,171 | 0.004606 |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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.
#
# Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
import socket
import sickbeard
from sickbeard import logger, common
from sickbeard.exceptions import ex
from lib.growl import gntp
class GrowlNotifier:
def test_notify(self, host, password):
self._sendRegistration(host, password, 'Test')
return self._sendGrowl("Test Growl", "Testing Growl settings from Sick Beard", "Test", host, password, force=True)
def notify_snatch(self, ep_name):
if sickbeard.GROWL_NOTIFY_ONSNATCH:
self._sendGrowl(common.notifyStrings[common.NOTIFY_SNATCH], ep_name)
def notify_download(self, ep_name):
if sickbeard.GROWL_NOTIFY_ONDOWNLOAD:
self._sendGrowl(common.notifyStrings[common.NOTIFY_DOWNLOAD], ep_name)
def notify_subtitle_download(self, ep_name, lang):
if sickbeard.GROWL_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendGrowl(common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], ep_name + ": " + lang)
def _send_growl(self, options,message=None):
#Send Notification
notice = gntp.GNTPNotice()
#Required
notice.add_header('Application-Name',options['app'])
notice.add_header('Notification-Name',options['name'])
notice.add_header('Notification-Title',options['title'])
if options['password']:
notice.set_password(options['password'])
#Optional
if options['sticky']:
notice.add_header('Notification-Sticky',options['sticky'])
if options['priority']:
notice.add_header('Notification-Priority',options['priority'])
if options['icon']:
notice.add_header('Notification-Icon', 'https://raw.github.com/midgetspy/Sick-Beard/master/data/images/sickbeard.png')
if message:
notice.add_header('Notification-Text',message)
response = self._send(options['host'],options['port'],notice.encode(),options['debug'])
if isinstance(response,gntp.GNTPOK): return True
return False
def _send(self, host,port,data,debug=False):
if debug: print '<Sending>\n',data,'\n</Sending>'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send(data)
response = gntp.parse_gntp(s.recv(1024))
s.close()
if debug: print '<Recieved>\n',response,'\n</Recieved>'
return response
def _sendGrowl(self, title="Sick Beard Notification", message=None, name=None, host=None, password=None, force=False):
if not sickbeard.USE_GROWL and not force:
return False
if name == None:
name = title
if host == None:
hostParts = sickbeard.GROWL_HOST.split(':')
else:
hostParts = host.split(':')
if len(hostParts) != 2 or hostParts[1] == '':
port = 23053
else:
port = int(hostParts[1])
growlHosts = [(hostParts[0],port)]
opts = {}
opts['name'] = name
opts['title'] = title
opts['app'] = 'SickBeard'
opts['sticky'] = None
opts['priority'] = None
opts['debug'] = False
if password == None:
opts['password'] = sickbeard.GROWL_PASSWORD
else:
opts['password'] = password
opts['icon'] = True
for pc in growlHosts:
opts['host'] = pc[0]
opts['port'] = pc[1]
logger.log(u"Sending growl to "+opts['host']+":"+str(opts['port'])+": "+message)
try:
return self._send_growl(opts, message)
except socket.error, e:
logger.log(u"Unable to send growl to "+opts['host']+":"+str(opts['port'])+": "+ex(e))
return False
def _sendRegistration(self, host=None, password=None, name='Sick Beard Notification'):
opts = {}
if host == None:
hostParts = sickbeard.GROWL_HOST.split(':')
else:
hostParts = host.split(':')
if len(hostParts) != 2 or hostParts[1] == '':
port = 23053
else:
port = int(hostParts[1])
opts['host'] = hostParts[0]
opts['port'] = port
if password == None:
opts['password'] = sickbeard.GROWL_PASSWORD
else:
opts['password'] = password
opts['app'] = 'SickBeard'
opts['debug'] = False
#Send Registration
register = gntp.GNTPRegister()
register.add_header('Application-Name', opts['app'])
register.add_header('Application-Icon', 'https://raw.github.com/midgetspy/Sick-Beard/master/data/images/sickbeard.png')
register.add_notification('Test', True)
for i in common.notifyStrings:
register.add_notification(common.notifyStrings[i], True)
if opts['password']:
register.set_password(opts['password'])
try:
return self._send(opts['host'],opts['port'],register.encode(),opts['debug'])
except socket.error, e:
logger.log(u"Unable to send growl to "+opts['host']+":"+str(opts['port'])+": "+str(e).decode('utf-8'))
return False
notifier = GrowlNotifier
|
Pistachitos/Sick-Beard
|
sickbeard/notifiers/growl.py
|
Python
|
gpl-3.0
| 6,111 | 0.014237 |
#
# Copyright 2019 Red Hat, Inc.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import json
import ssl
import urllib3
from urllib3.util.timeout import Timeout
from virtwho.virt.kubevirt import config
_TIMEOUT = 60
class KubeClient:
def __init__(self, path, version, insecure):
cfg = config.Configuration()
cl = config._get_kube_config_loader_for_yaml_file(path)
cl.load_and_set(cfg)
if insecure:
self._pool_manager = urllib3.PoolManager(
num_pools=4,
maxsize=4,
cert_reqs=ssl.CERT_NONE,
assert_hostname=False
)
else:
cert_reqs = ssl.CERT_REQUIRED
ca_certs = cfg.ssl_ca_cert
cert_file = cfg.cert_file
key_file = cfg.key_file
self._pool_manager = urllib3.PoolManager(
num_pools=4,
maxsize=4,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
cert_file=cert_file,
key_file=key_file
)
self.host = cfg.host
self.token = cfg.token
if not version:
self._version = self._kubevirt_version()
else:
self._version = version
def get_nodes(self):
return self._request('/api/v1/nodes')
def get_vms(self):
return self._request('/apis/kubevirt.io/' + self._version + '/virtualmachineinstances')
def _kubevirt_version(self):
versions = self._request('/apis/kubevirt.io')
return versions['preferredVersion']['version']
def _request(self, path):
header_params = {}
header_params['Accept'] = 'application/json'
header_params['Content-Type'] = 'application/json'
header_params['Authorization'] = self.token
url = self.host + path
try:
timeout = Timeout(connect=_TIMEOUT, read=_TIMEOUT)
r = self._pool_manager.request(
"GET",
url,
fields=None,
preload_content=True,
headers=header_params,
timeout=timeout
)
except urllib3.exceptions.SSLError as e:
msg = "{0}\n{1}".format(type(e).__name__, str(e))
raise ApiException(status=0, reason=msg)
data = r.data.decode('utf8')
if not 200 <= r.status <= 299:
raise ApiException(http_resp=r)
# fetch data from response object
try:
data = json.loads(data)
except ValueError:
data = r.data
return data
class ApiException(Exception):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None
def __str__(self):
"""
Custom error messages for exception
"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(self.headers)
if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
return error_message
|
candlepin/virt-who
|
virtwho/virt/kubevirt/client.py
|
Python
|
gpl-2.0
| 4,273 | 0.000468 |
import sys
sys.path.insert(1, "../../../")
import h2o
import random
def test_get_future_model(ip,port):
covtype=h2o.upload_file(h2o.locate("smalldata/covtype/covtype.altered.gz"))
myY=54
myX=list(set(range(54)) - set([20,28])) # Cols 21 and 29 are constant, so must be explicitly ignored
# Set response to be indicator of a particular class
res_class=random.sample(range(1,5), 1)[0]
covtype[myY] = covtype[myY] == res_class
covtype[myY] = covtype[myY].asfactor()
# L2: alpha=0, lambda=0
covtype_h2o1 = h2o.start_glm_job(y=covtype[myY], x=covtype[myX], family="binomial", alpha=[0], Lambda=[0])
# Elastic: alpha=0.5, lambda=1e-4
covtype_h2o2 = h2o.start_glm_job(y=covtype[myY], x=covtype[myX], family="binomial", alpha=[0.5], Lambda=[1e-4])
# L1: alpha=1, lambda=1e-4
covtype_h2o3 = h2o.start_glm_job(y=covtype[myY], x=covtype[myX], family="binomial", alpha=[1], Lambda=[1e-4])
covtype_h2o1 = h2o.get_future_model(covtype_h2o1)
print(covtype_h2o1)
covtype_h2o2 = h2o.get_future_model(covtype_h2o2)
print(covtype_h2o2)
covtype_h2o3 = h2o.get_future_model(covtype_h2o3)
print(covtype_h2o3)
if __name__ == "__main__":
h2o.run_test(sys.argv, test_get_future_model)
|
weaver-viii/h2o-3
|
h2o-py/tests/testdir_algos/glm/pyunit_covtype_get_future_model.py
|
Python
|
apache-2.0
| 1,261 | 0.014274 |
#@result Submitted a few seconds ago • Score: 10.00 Status: Accepted Test Case #0: 0s Test Case #1: 0.01s Test Case #2: 0s Test Case #3: 0s Test Case #4: 0.01s Test Case #5: 0s
for i in range(int(raw_input())): #More than 4 lines will result in 0 score. Blank lines won't be counted.
a = int(raw_input()); A = set(raw_input().split())
b = int(raw_input()); B = set(raw_input().split())
print B == B.union(A)
|
FeiZhan/Algo-Collection
|
answers/hackerrank/Check Subset.py
|
Python
|
mit
| 423 | 0.016627 |
###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distributed under the GPL v3 license
#along with commercial support options.
#
#cyn.in is a Cynapse Invention.
#
#Copyright (C) 2008 Cynapse India Pvt. Ltd.
#
#This program 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 any later version and observe
#the Additional Terms applicable to this program and must display appropriate
#legal notices. In accordance with Section 7(b) of the GNU General Public
#License version 3, these Appropriate Legal Notices must retain the display of
#the "Powered by cyn.in" AND "A Cynapse Invention" logos. You should have
#received a copy of the detailed Additional Terms License with this program.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#Public License for more details.
#
#You should have received a copy of the GNU General Public License along with
#this program. If not, see <http://www.gnu.org/licenses/>.
#
#You can contact Cynapse at support@cynapse.com with any problems with cyn.in.
#For any queries regarding the licensing, please send your mails to
# legal@cynapse.com
#
#You can also contact Cynapse at:
#802, Building No. 1,
#Dheeraj Sagar, Malad(W)
#Mumbai-400064, India
###############################################################################
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ubify.policy.config import spacesdefaultaddablenonfolderishtypes
from zope.component import getUtility
from zope.app.publisher.interfaces.browser import IBrowserMenu
class AddContentSelector(BrowserView):
"""Contains backend code for the addcontentselector
"""
template = ViewPageTemplateFile('addcontentselector.pt')
allowed_types = spacesdefaultaddablenonfolderishtypes + ('ContentSpace',)
def __call__(self):
return self.template()
def isAllowedtoAdd(self,typename):
menu = getUtility(IBrowserMenu, name='plone_contentmenu_factory')
self.currentcontextmenu = []
object_typename = self.context.portal_type
if object_typename in ('RecycleBin','Plone Site'):
self.currentcontextmenu = []
else:
self.currentcontextmenu = menu.getMenuItems(self.context, self.request)
self.allowedhere = False
if len(self.currentcontextmenu) > 0:
temp_list = [action for action in self.currentcontextmenu if action.has_key('extra') and action['extra'].has_key('id') and action['extra']['id'].lower() == typename.lower()]
self.allowedhere = len(temp_list) > 0
self.displaycurrentcontexttitle = ""
if self.allowedhere:
self.displaycurrentcontexttitle = self.context.Title()
if object_typename == 'ContentRoot':
self.displaycurrentcontexttitle = "Home"
|
cynapse/cynin
|
src/ubify.cyninv2theme/ubify/cyninv2theme/browser/addcontentselector.py
|
Python
|
gpl-3.0
| 3,531 | 0.016709 |
from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
setattr(m, '__loader__', getattr(sys.modules[module_name], '__loader__'))
m.__file__ = file
return m
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l-1]
#print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def compare_object_attrs(x, y):
try:
if x == y:
return 0
x_num = to_number(x)
y_num = to_number(y)
if x_num is not None and y_num is not None:
if x_num - y_num<0:
return -1
else:
return 1
if '__len__' == x:
return -1
if '__len__' == y:
return 1
return x.__cmp__(y)
except:
if IS_PY3K:
return (to_string(x) > to_string(y)) - (to_string(x) < to_string(y))
else:
return cmp(to_string(x), to_string(y))
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
if IS_PY3K:
def is_string(x):
return isinstance(x, str)
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def quote_smart(s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
first_arg_class = first_arg_obj.__class__
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname
def _get_project_roots(project_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not project_roots_cache:
roots = os.getenv('IDE_PROJECT_ROOTS', '').split(os.pathsep)
pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
project_roots_cache.append(new_roots)
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(new_roots)
return library_roots_cache[-1] # returns the project roots with case normalized
def not_in_project_roots(filename, filename_to_not_in_scope_cache={}):
# Note: the filename_to_not_in_scope_cache is the same instance among the many calls to the method
try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filename)
for root in project_roots:
if filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = False
break
else: # for else (only called if the break wasn't reached).
filename_to_not_in_scope_cache[original_filename] = True
if not filename_to_not_in_scope_cache[original_filename]:
# additional check if interpreter is situated in a project directory
library_roots = _get_library_roots()
for root in library_roots:
if root != '' and filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename]
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv('PYDEVD_FILTER_LIBRARIES') is not None
pydev_log.debug("PYDEVD_FILTER_LIBRARIES %s\n" % is_filter)
return is_filter
def _get_stepping_filters(filters_cache=[]):
if not filters_cache:
filters = os.getenv('PYDEVD_FILTERS', '').split(';')
pydev_log.debug("PYDEVD_FILTERS %s\n" % filters)
new_filters = []
for new_filter in filters:
new_filters.append(new_filter)
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
if fnmatch.fnmatch(filename, stepping_filter):
pydev_log.debug("File %s ignored by filter %s" % (filename, stepping_filter))
filename_to_ignored_by_filters_cache[filename] = True
break
else:
filename_to_ignored_by_filters_cache[filename] = False
return filename_to_ignored_by_filters_cache[filename]
|
asedunov/intellij-community
|
python/helpers/pydev/_pydevd_bundle/pydevd_utils.py
|
Python
|
apache-2.0
| 7,871 | 0.004447 |
# -*- coding: utf-8 -*-
"""
A window with a unicode textfield where the user can edit.
Useful for editing the contents of an article.
"""
from __future__ import absolute_import, unicode_literals
#
# (C) Rob W.W. Hooft, 2003
# (C) Daniel Herding, 2004
# Wikiwichtel
# (C) Pywikibot team, 2008-2014
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
#
import sys
if sys.version_info[0] > 2:
import tkinter as Tkinter
from tkinter.scrolledtext import ScrolledText
from tkinter import simpledialog as tkSimpleDialog
else:
import Tkinter
from ScrolledText import ScrolledText
import tkSimpleDialog
from idlelib import SearchDialog, ReplaceDialog, configDialog
from idlelib.configHandler import idleConf
from idlelib.MultiCall import MultiCallCreator
import pywikibot
from pywikibot import __url__
class TextEditor(ScrolledText):
"""A text widget with some editing enhancements.
A lot of code here is copied or adapted from the idlelib/EditorWindow.py
file in the standard Python distribution.
"""
def __init__(self, master=None, **kwargs):
# get default settings from user's IDLE configuration
currentTheme = idleConf.CurrentTheme()
textcf = dict(padx=5, wrap='word', undo='True',
foreground=idleConf.GetHighlight(currentTheme,
'normal', fgBg='fg'),
background=idleConf.GetHighlight(currentTheme,
'normal', fgBg='bg'),
highlightcolor=idleConf.GetHighlight(currentTheme,
'hilite', fgBg='fg'),
highlightbackground=idleConf.GetHighlight(currentTheme,
'hilite',
fgBg='bg'),
insertbackground=idleConf.GetHighlight(currentTheme,
'cursor',
fgBg='fg'),
width=idleConf.GetOption('main', 'EditorWindow', 'width'),
height=idleConf.GetOption('main', 'EditorWindow',
'height')
)
fontWeight = 'normal'
if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'):
fontWeight = 'bold'
textcf['font'] = (idleConf.GetOption('main', 'EditorWindow', 'font'),
idleConf.GetOption('main', 'EditorWindow',
'font-size'),
fontWeight)
# override defaults with any user-specified settings
textcf.update(kwargs)
ScrolledText.__init__(self, master, **textcf)
def add_bindings(self):
# due to IDLE dependencies, this can't be called from __init__
# add key and event bindings
self.bind("<<cut>>", self.cut)
self.bind("<<copy>>", self.copy)
self.bind("<<paste>>", self.paste)
self.bind("<<select-all>>", self.select_all)
self.bind("<<remove-selection>>", self.remove_selection)
self.bind("<<find>>", self.find_event)
self.bind("<<find-again>>", self.find_again_event)
self.bind("<<find-selection>>", self.find_selection_event)
self.bind("<<replace>>", self.replace_event)
self.bind("<<goto-line>>", self.goto_line_event)
self.bind("<<del-word-left>>", self.del_word_left)
self.bind("<<del-word-right>>", self.del_word_right)
keydefs = {'<<copy>>': ['<Control-Key-c>', '<Control-Key-C>'],
'<<cut>>': ['<Control-Key-x>', '<Control-Key-X>'],
'<<del-word-left>>': ['<Control-Key-BackSpace>'],
'<<del-word-right>>': ['<Control-Key-Delete>'],
'<<end-of-file>>': ['<Control-Key-d>', '<Control-Key-D>'],
'<<find-again>>': ['<Control-Key-g>', '<Key-F3>'],
'<<find-selection>>': ['<Control-Key-F3>'],
'<<find>>': ['<Control-Key-f>', '<Control-Key-F>'],
'<<goto-line>>': ['<Alt-Key-g>', '<Meta-Key-g>'],
'<<paste>>': ['<Control-Key-v>', '<Control-Key-V>'],
'<<redo>>': ['<Control-Shift-Key-Z>'],
'<<remove-selection>>': ['<Key-Escape>'],
'<<replace>>': ['<Control-Key-h>', '<Control-Key-H>'],
'<<select-all>>': ['<Control-Key-a>'],
'<<undo>>': ['<Control-Key-z>', '<Control-Key-Z>'],
}
for event, keylist in keydefs.items():
if keylist:
self.event_add(event, *keylist)
def cut(self, event):
if self.tag_ranges("sel"):
self.event_generate("<<Cut>>")
return "break"
def copy(self, event):
if self.tag_ranges("sel"):
self.event_generate("<<Copy>>")
return "break"
def paste(self, event):
self.event_generate("<<Paste>>")
return "break"
def select_all(self, event=None):
self.tag_add("sel", "1.0", "end-1c")
self.mark_set("insert", "1.0")
self.see("insert")
return "break"
def remove_selection(self, event=None):
self.tag_remove("sel", "1.0", "end")
self.see("insert")
def del_word_left(self, event):
self.event_generate('<Meta-Delete>')
return "break"
def del_word_right(self, event=None):
self.event_generate('<Meta-d>')
return "break"
def find_event(self, event=None):
if not self.tag_ranges("sel"):
found = self.tag_ranges("found")
if found:
self.tag_add("sel", found[0], found[1])
else:
self.tag_add("sel", "1.0", "1.0+1c")
SearchDialog.find(self)
return "break"
def find_again_event(self, event=None):
SearchDialog.find_again(self)
return "break"
def find_selection_event(self, event=None):
SearchDialog.find_selection(self)
return "break"
def replace_event(self, event=None):
ReplaceDialog.replace(self)
return "break"
def find_all(self, s):
"""
Highlight all occurrences of string s, and select the first one.
If the string has already been highlighted, jump to the next occurrence
after the current selection. (You cannot go backwards using the
button, but you can manually place the cursor anywhere in the
document to start searching from that point.)
"""
if hasattr(self, "_highlight") and self._highlight == s:
try:
if self.get(Tkinter.SEL_FIRST, Tkinter.SEL_LAST) == s:
return self.find_selection_event(None)
else:
# user must have changed the selection
found = self.tag_nextrange('found', Tkinter.SEL_LAST)
except Tkinter.TclError:
# user must have unset the selection
found = self.tag_nextrange('found', Tkinter.INSERT)
if not found:
# at last occurrence, scroll back to the top
found = self.tag_nextrange('found', 1.0)
if found:
self.do_highlight(found[0], found[1])
else:
# find all occurrences of string s;
# adapted from O'Reilly's Python in a Nutshell
# remove previous uses of tag 'found', if any
self.tag_remove('found', '1.0', Tkinter.END)
if s:
self._highlight = s
# start from the beginning (and when we come to the end, stop)
idx = '1.0'
while True:
# find next occurrence, exit loop if no more
idx = self.search(s, idx, nocase=1, stopindex=Tkinter.END)
if not idx:
break
# index right after the end of the occurrence
lastidx = '%s+%dc' % (idx, len(s))
# tag the whole occurrence (start included, stop excluded)
self.tag_add('found', idx, lastidx)
# prepare to search for next occurrence
idx = lastidx
# use a red foreground for all the tagged occurrences
self.tag_config('found', foreground='red')
found = self.tag_nextrange('found', 1.0)
if found:
self.do_highlight(found[0], found[1])
def do_highlight(self, start, end):
"""Select and show the text from index start to index end."""
self.see(start)
self.tag_remove(Tkinter.SEL, '1.0', Tkinter.END)
self.tag_add(Tkinter.SEL, start, end)
self.focus_set()
def goto_line_event(self, event):
lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:",
parent=self)
if lineno is None:
return "break"
if lineno <= 0:
self.bell()
return "break"
self.mark_set("insert", "%d.0" % lineno)
self.see("insert")
class EditBoxWindow(Tkinter.Frame):
"""Edit box window."""
def __init__(self, parent=None, **kwargs):
if parent is None:
# create a new window
parent = Tkinter.Tk()
self.parent = parent
Tkinter.Frame.__init__(self, parent)
self.editbox = MultiCallCreator(TextEditor)(self, **kwargs)
self.editbox.pack(side=Tkinter.TOP)
self.editbox.add_bindings()
self.bind("<<open-config-dialog>>", self.config_dialog)
bottom = Tkinter.Frame(parent)
# lower left subframe which will contain a textfield and a Search button
bottom_left_frame = Tkinter.Frame(bottom)
self.textfield = Tkinter.Entry(bottom_left_frame)
self.textfield.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=1)
buttonSearch = Tkinter.Button(bottom_left_frame, text='Find next',
command=self.find)
buttonSearch.pack(side=Tkinter.RIGHT)
bottom_left_frame.pack(side=Tkinter.LEFT, expand=1)
# lower right subframe which will contain OK and Cancel buttons
bottom_right_frame = Tkinter.Frame(bottom)
buttonOK = Tkinter.Button(bottom_right_frame, text='OK',
command=self.pressedOK)
buttonCancel = Tkinter.Button(bottom_right_frame, text='Cancel',
command=parent.destroy)
buttonOK.pack(side=Tkinter.LEFT, fill=Tkinter.X)
buttonCancel.pack(side=Tkinter.RIGHT, fill=Tkinter.X)
bottom_right_frame.pack(side=Tkinter.RIGHT, expand=1)
bottom.pack(side=Tkinter.TOP)
# create a toplevel menu
menubar = Tkinter.Menu(self.parent)
findmenu = Tkinter.Menu(menubar)
findmenu.add_command(label="Find",
command=self.editbox.find_event,
accelerator="Ctrl+F",
underline=0)
findmenu.add_command(label="Find again",
command=self.editbox.find_again_event,
accelerator="Ctrl+G",
underline=6)
findmenu.add_command(label="Find all",
command=self.find_all,
underline=5)
findmenu.add_command(label="Find selection",
command=self.editbox.find_selection_event,
accelerator="Ctrl+F3",
underline=5)
findmenu.add_command(label="Replace",
command=self.editbox.replace_event,
accelerator="Ctrl+H",
underline=0)
menubar.add_cascade(label="Find", menu=findmenu, underline=0)
editmenu = Tkinter.Menu(menubar)
editmenu.add_command(label="Cut",
command=self.editbox.cut,
accelerator="Ctrl+X",
underline=2)
editmenu.add_command(label="Copy",
command=self.editbox.copy,
accelerator="Ctrl+C",
underline=0)
editmenu.add_command(label="Paste",
command=self.editbox.paste,
accelerator="Ctrl+V",
underline=0)
editmenu.add_separator()
editmenu.add_command(label="Select all",
command=self.editbox.select_all,
accelerator="Ctrl+A",
underline=7)
editmenu.add_command(label="Clear selection",
command=self.editbox.remove_selection,
accelerator="Esc")
menubar.add_cascade(label="Edit", menu=editmenu, underline=0)
optmenu = Tkinter.Menu(menubar)
optmenu.add_command(label="Settings...",
command=self.config_dialog,
underline=0)
menubar.add_cascade(label="Options", menu=optmenu, underline=0)
# display the menu
self.parent.config(menu=menubar)
self.pack()
def edit(self, text, jumpIndex=None, highlight=None):
"""
Provide user with editor to modify text.
@param text: the text to be edited
@type text: unicode
@param jumpIndex: position at which to put the caret
@type jumpIndex: int
@param highlight: each occurrence of this substring will be highlighted
@type highlight: unicode
@return: the modified text, or None if the user didn't save the text
file in his text editor
@rtype: unicode or None
"""
self.text = None
# put given text into our textarea
self.editbox.insert(Tkinter.END, text)
# wait for user to push a button which will destroy (close) the window
# enable word wrap
self.editbox.tag_add('all', '1.0', Tkinter.END)
self.editbox.tag_config('all', wrap=Tkinter.WORD)
# start search if required
if highlight:
self.find_all(highlight)
if jumpIndex:
print(jumpIndex)
# lines are indexed starting at 1
line = text[:jumpIndex].count('\n') + 1
column = jumpIndex - (text[:jumpIndex].rfind('\n') + 1)
# don't know how to place the caret, but scrolling to the right line
# should already be helpful.
self.editbox.see('%d.%d' % (line, column))
# wait for user to push a button which will destroy (close) the window
self.parent.mainloop()
return self.text
def find_all(self, target):
self.textfield.insert(Tkinter.END, target)
self.editbox.find_all(target)
def find(self):
# get text to search for
s = self.textfield.get()
if s:
self.editbox.find_all(s)
def config_dialog(self, event=None):
configDialog.ConfigDialog(self, 'Settings')
def pressedOK(self):
# called when user pushes the OK button.
# saves the buffer into a variable, and closes the window.
self.text = self.editbox.get('1.0', Tkinter.END)
# if the editbox contains ASCII characters only, get() will
# return string, otherwise unicode (very annoying). We only want
# it to return unicode, so we work around this.
if sys.version[0] == 2 and isinstance(self.text, str):
self.text = unicode(self.text) # noqa
self.parent.destroy()
def debug(self, event=None):
self.quit()
return "break"
# the following class isn't used anywhere in the framework: ####
class ListBoxWindow:
"""List box window."""
# called when user pushes the OK button.
# closes the window.
def pressedOK(self):
# ok closes listbox
self.parent.destroy()
def __init__(self, parent=None):
if parent is None:
# create a new window
parent = Tkinter.Tk()
self.parent = parent
# selectable: only one item
self.listbox = Tkinter.Listbox(parent, selectmode=Tkinter.SINGLE)
# put list into main frame, using all available space
self.listbox.pack(anchor=Tkinter.CENTER, fill=Tkinter.BOTH)
# lower subframe which will contain one button
self.bottom_frame = Tkinter.Frame(parent)
self.bottom_frame.pack(side=Tkinter.BOTTOM)
buttonOK = Tkinter.Button(self.bottom_frame, text='OK', command=self.pressedOK)
buttonOK.pack(side=Tkinter.LEFT, fill=Tkinter.X)
# idea: set title to cur_disambiguation
def list(self, list):
# put list of alternatives into listbox
self.list = list
# find required area
laenge = len(list)
maxbreite = 0
for i in range(laenge):
# cycle through all listitems to find maxlength
if len(list[i]) + len(str(i)) > maxbreite:
maxbreite = len(list[i]) + len(str(i))
# show list as formerly in DOS-window
self.listbox.insert(Tkinter.END, str(i) + ' - ' + list[i])
# set optimized height & width
self.listbox.config(height=laenge, width=maxbreite + 2)
# wait for user to push a button which will destroy (close) the window
return self.list
class Tkdialog:
"""The dialog window for image info."""
def __init__(self, photo_description, photo, filename):
"""Constructor."""
self.root = Tkinter.Tk()
# "%dx%d%+d%+d" % (width, height, xoffset, yoffset)
self.root.geometry("%ix%i+10-10" % (pywikibot.config.tkhorsize,
pywikibot.config.tkvertsize))
self.root.title(filename)
self.photo_description = photo_description
self.filename = filename
self.photo = photo
self.skip = False
self.exit = False
# --Init of the widgets
# The image
self.image = self.get_image(self.photo, 800, 600)
self.image_panel = Tkinter.Label(self.root, image=self.image)
self.image_panel.image = self.image
# The filename
self.filename_label = Tkinter.Label(self.root, text=u"Suggested filename")
self.filename_field = Tkinter.Entry(self.root, width=100)
self.filename_field.insert(Tkinter.END, filename)
# The description
self.description_label = Tkinter.Label(self.root,
text=u"Suggested description")
self.description_scrollbar = Tkinter.Scrollbar(self.root,
orient=Tkinter.VERTICAL)
self.description_field = Tkinter.Text(self.root)
self.description_field.insert(Tkinter.END, photo_description)
self.description_field.config(state=Tkinter.NORMAL, height=12, width=100,
padx=0, pady=0, wrap=Tkinter.WORD,
yscrollcommand=self.description_scrollbar.set)
self.description_scrollbar.config(command=self.description_field.yview)
# The buttons
self.ok_button = Tkinter.Button(self.root, text="OK",
command=self.ok_file)
self.skip_button = Tkinter.Button(self.root, text="Skip",
command=self.skip_file)
# --Start grid
# The image
self.image_panel.grid(row=0, column=0, rowspan=11, columnspan=4)
# The buttons
self.ok_button.grid(row=11, column=1, rowspan=2)
self.skip_button.grid(row=11, column=2, rowspan=2)
# The filename
self.filename_label.grid(row=13, column=0)
self.filename_field.grid(row=13, column=1, columnspan=3)
# The description
self.description_label.grid(row=14, column=0)
self.description_field.grid(row=14, column=1, columnspan=3)
self.description_scrollbar.grid(row=14, column=5)
def get_image(self, photo, width, height):
"""Take the BytesIO object and build an imageTK thumbnail."""
try:
from PIL import Image, ImageTk
except ImportError:
pywikibot.warning('This script requires ImageTk from the'
'Python Imaging Library (PIL).\n'
'See: {0}/flickrripper.py'.format(__url__))
raise
image = Image.open(photo)
image.thumbnail((width, height))
imageTk = ImageTk.PhotoImage(image)
return imageTk
def ok_file(self):
"""The user pressed the OK button."""
self.filename = self.filename_field.get()
self.photo_description = self.description_field.get(0.0, Tkinter.END)
self.root.destroy()
def skip_file(self):
"""The user pressed the Skip button."""
self.skip = True
self.root.destroy()
def show_dialog(self):
"""Activate the dialog.
@return: new description, name, and if the image is skipped
@rtype: tuple of (unicode, unicode, bool)
"""
self.root.mainloop()
return self.photo_description, self.filename, self.skip
|
icyflame/batman
|
pywikibot/userinterfaces/gui.py
|
Python
|
mit
| 21,774 | 0.000413 |
"""Helper functions for Flask-Statics."""
from flask_statics import resource_base
from flask_statics import resource_definitions
def priority(var):
"""Prioritizes resource position in the final HTML. To be fed into sorted(key=).
Javascript consoles throw errors if Bootstrap's js file is mentioned before jQuery. Using this function such errors
can be avoided. Used internally.
Positional arguments:
var -- value sent by list.sorted(), which is a value in Statics().all_variables.
Returns:
Either a number if sorting is enforced for the value in `var`, or returns `var` itself.
"""
order = dict(JQUERY='0', BOOTSTRAP='1')
return order.get(var, var)
def get_resources(minify=False):
"""Find all resources which subclass ResourceBase.
Keyword arguments:
minify -- select minified resources if available.
Returns:
Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts
with css and js keys, and tuples of resources as values.
"""
all_resources = dict()
subclasses = resource_base.ResourceBase.__subclasses__() + resource_definitions.ResourceAngular.__subclasses__()
for resource in subclasses:
obj = resource(minify)
all_resources[resource.RESOURCE_NAME] = dict(css=tuple(obj.resources_css), js=tuple(obj.resources_js))
return all_resources
|
Robpol86/Flask-Statics-Helper
|
flask_statics/helpers.py
|
Python
|
mit
| 1,406 | 0.004979 |
from django.test import TestCase as DjangoTestCase
from django.conf import settings
from seeder.models import *
from seeder.posters import TwitterPoster
from random import randint as random
from datetime import datetime
import time
import mox
import re
def generate_random_authorized_account():
u = User(username = "foo" + str(random(10000, 99999)))
u.save()
return AuthorizedAccount.objects.create(user = u)
def generate_random_seeder(account = None):
if account is None:
account = generate_random_authorized_account()
return Seeder.objects.create(
twitter_id = random(1000, 9999),
authorized_for = account
)
def generate_random_token(seeder = None):
if seeder is None:
seeder = generate_random_seeder()
return Token.objects.create(
seeder = seeder,
oauth_token = "some token" + str(random(10, 100)),
oauth_token_secret = "some token secret" + str(random(10, 100))
)
def generate_random_update(account = None):
if account is None:
account = generate_random_authorized_account()
return Update.objects.create(
posted_by = account,
original_text = "Hello from Seeder!"
)
def generate_mock_poster(update):
poster = mox.MockObject(TwitterPoster)
poster.post(update)
mox.Replay(poster)
return poster
class TestCase(DjangoTestCase):
def assertPubDateBetween(self, obj, begin, end):
self.assertTrue(obj.pub_date > begin and obj.pub_date < end)
def tearDown(self):
models = (AuthorizedAccount, Token, Seeder, Update, SeededUpdate,)
for model in models:
[obj.delete() for obj in model.objects.all()]
class TestOfSeededUpate(TestCase):
def test_has_a_future_timestamp(self):
foo = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update()
)
self.assertTrue(datetime.now() < foo.pub_date)
def test_retrieves_updates_based_on_availability(self):
first = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update(),
pub_date = datetime.now()
)
second = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update(),
pub_date = datetime.fromtimestamp(time.time() + 1)
)
self.assertEqual(1, len(SeededUpdate.objects.currently_available()))
time.sleep(1.1)
self.assertEqual(2, len(SeededUpdate.objects.currently_available()))
def test_retrieves_updates_that_havenot_been_sent(self):
first = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update(),
pub_date = datetime.now()
)
second = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update(),
pub_date = datetime.now()
)
self.assertEqual(2, len(SeededUpdate.objects.currently_available()))
first.has_sent = 1;
first.save()
self.assertEqual(1, len(SeededUpdate.objects.currently_available()))
def test_send_calls_on_poster(self):
update = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update()
)
poster = generate_mock_poster(update)
update.send(poster)
mox.Verify(poster)
def test_send_marks_updates_as_sent(self):
update = SeededUpdate.objects.create(
seeder = generate_random_seeder(),
update = generate_random_update(),
pub_date = datetime.now()
)
self.assertEqual(len(SeededUpdate.objects.currently_available()), 1,
"sanity check to ensure value seeded update is present")
update.send(generate_mock_poster(update))
self.assertEqual(len(SeededUpdate.objects.currently_available()), 0,
"SeededUpdate should not be available after being sent")
class TestOfUpdate(TestCase):
def test_creates_seeded_updates_on_save(self):
# sanity check
self.assertEqual(0, len(SeededUpdate.objects.all()))
a = generate_random_authorized_account()
[generate_random_seeder(a) for i in range(10)]
update = Update.objects.create(
posted_by = a,
original_text = "Hello from Seeder!"
)
self.assertEqual(10, len(SeededUpdate.objects.all()))
def test_all_seeded_updates_have_pub_dates_between_1_and_30_minutes(self):
a = generate_random_authorized_account()
generate_random_seeder(a)
update = Update.objects.create(
posted_by = a,
original_text = "Hello from Seeder!"
)
seeded_update = SeededUpdate.objects.get(update = update)
# only uses 59 seconds to avoid possible race condition where
# more than a second elapses between creation and the time this
# test runs
begin_datetime = datetime.fromtimestamp(time.time() + 59)
end_datetime = datetime.fromtimestamp(time.time() + (60 * 30) + 1)
self.assertPubDateBetween(seeded_update, begin_datetime, end_datetime)
def test_only_creates_new_seeded_updates_on_new(self):
a = generate_random_authorized_account()
generate_random_seeder(a)
update = generate_random_update(a)
self.assertEqual(len(SeededUpdate.objects.all()), 1,
"Sanity check")
update.save()
self.assertEqual(len(SeededUpdate.objects.all()), 1,
"Should only create SeededUpdates on save when new")
def test_only_creates_for_non_expired_seeders(self):
a = generate_random_authorized_account()
s1 = generate_random_seeder(a)
s2 = generate_random_seeder(a)
s2.set_expires_on_in_days(-1)
s2.save()
update = generate_random_update(a)
self.assertEquals(len(SeededUpdate.objects.all()), 1,
"should only create one SeededUpdate since on has expired")
class TestOfAuthorizedAccount(TestCase):
def test_default_account_returns_default_account(self):
a = generate_random_authorized_account()
a.twitter_id = settings.SEEDER['default_twitter_id']
a.save()
default_account = AuthorizedAccount.objects.default_account()
self.assertEqual(settings.SEEDER['default_twitter_id'], default_account.twitter_id)
def test_only_pulls_seeders_that_have_not_expired(self):
a = generate_random_authorized_account()
s = generate_random_seeder(a)
self.assertEquals(len(a.seeder_set.currently_available()), 1,
"sanity check: seeder_set.currently_available() should be one")
s.expires_on = datetime.fromtimestamp(time.time() - 60)
s.save()
self.assertEquals(len(a.seeder_set.currently_available()), 0,
"seeder_set.currently_available() should have no seeders")
class TestOfSeeder(TestCase):
def test_automatically_expires_in_30_days(self):
seeder = generate_random_seeder()
expected_expires_on = datetime.fromtimestamp(time.time() + 60*60*24*30).date()
self.assertEquals(seeder.expires_on.date(), expected_expires_on,
"seeder.expires_on should default to 30 days")
def test_can_set_by_expires_by_day(self):
seeder = generate_random_seeder()
seeder.set_expires_on_in_days(7)
self.assertEquals(seeder.expires_on.date(), datetime.fromtimestamp(time.time() + 60*60*24*7).date(),
"seeder.expires_on should be 7 days in the future")
def test_can_take_a_string_as_parameter(self):
seeder = generate_random_seeder()
try:
seeder.set_expires_on_in_days("7")
except TypeError:
self.fail("seeder.set_expires_on_in_days() unable to handle a string")
def generate_mock_settings():
return mox.MockObject(settings)
class StubTwitterApi(object):
number_of_calls = 0
calls = []
def __init__(self, *args, **kwargs):
StubTwitterApi.number_of_calls += 1
def __getattribute__(self, method):
StubTwitterApi.calls.append(method)
return self
def __call__(self, *args, **kwargs):
last_call = StubTwitterApi.calls.pop()
StubTwitterApi.calls.append({
"name": last_call,
"args": args,
"kwargs": kwargs,
})
class SanityTestOfStubTwitterApi(TestCase):
def setUp(self):
super(SanityTestOfStubTwitterApi, self).setUp()
StubTwitterApi.number_of_calls = 0
def test_sanity_check(self):
obj1 = StubTwitterApi()
self.assertEqual(StubTwitterApi.number_of_calls, 1)
obj2 = StubTwitterApi()
self.assertEqual(StubTwitterApi.number_of_calls, 2)
obj3 = StubTwitterApi()
self.assertEqual(StubTwitterApi.number_of_calls, 3)
def test_keeps_track_of_calls(self):
obj = StubTwitterApi()
obj.foobar()
self.assertEqual(len(StubTwitterApi.calls), 1)
def test_keeps_track_of_parameters_passed_in_to_methods(self):
obj = StubTwitterApi()
number = random(10, 100)
obj.foobar(number)
data = StubTwitterApi.calls.pop()
self.assertEquals(data['args'], (number,))
def generate_full_update(number_of_seeders):
account = generate_random_authorized_account()
[generate_random_token(generate_random_seeder(account)) for i in range(number_of_seeders)]
update = generate_random_update(account)
return update
class StubSettingsForTwitterApi(object):
TWITTER = {
"CONSUMER_KEY": "foobar",
"CONSUMER_SECRET": "barfoo",
}
class TestOfTwitterPoster(TestCase):
def setUp(self):
super(TestOfTwitterPoster, self).setUp()
StubTwitterApi.number_of_calls = 0
StubTwitterApi.calls = []
def test_encapsulates_post_in_template_string(self):
settings = StubSettingsForTwitterApi()
random_prefix = "random %d" % random(10, 100)
settings.TWITTER["POST_TEMPLATE"] = "%s: %%s" % random_prefix
u = generate_full_update(1)
poster = TwitterPoster(api_class = StubTwitterApi, settings = settings)
poster.post(u.seededupdate_set.all()[0])
for data in StubTwitterApi.calls:
if data['name'] == 'PostUpdate':
break
(posted_status,) = data['args']
expected_status = "%s: .*" % random_prefix
self.assertTrue(
re.compile(expected_status).match(posted_status) is not None
)
def test_instantiates_new_api_class_for_each_token(self):
number_of_seeders = random(2, 10)
u = generate_full_update(number_of_seeders)
poster = TwitterPoster(api_class = StubTwitterApi)
[seeded_update.send(poster) for seeded_update in u.seededupdate_set.all()]
self.assertEquals(StubTwitterApi.number_of_calls, number_of_seeders)
def assertSetSourceCalledWith(self, value):
for data in StubTwitterApi.calls:
if data["name"] == "SetSource":
break
self.assertEquals((value,), data["args"])
def test_sets_source_to_seeder_if_not_configured(self):
u = generate_full_update(1)
poster = TwitterPoster(api_class = StubTwitterApi)
poster.post(u.seededupdate_set.all()[0])
self.assertSetSourceCalledWith("seeder")
def test_sets_source_to_configured_value(self):
settings = StubSettingsForTwitterApi()
random_source = "random value: " + str(random(10, 100))
settings.TWITTER["SOURCE"] = random_source
u = generate_full_update(1)
poster = TwitterPoster(api_class = StubTwitterApi, settings = settings)
poster.post(u.seededupdate_set.all()[0])
self.assertSetSourceCalledWith(random_source)
|
tswicegood/seeder
|
seeder/tests.py
|
Python
|
gpl-3.0
| 11,995 | 0.009587 |
from transifex.projects.models import Project
from transifex.teams.models import Team
from transifex.txcommon.tests import base
class TestTeamModels(base.BaseTestCase):
def test_available_teams(self):
"""
Test whether monkey-patch of Project class with a 'available_teams'
instance method returns the desired result.
"""
# There must be only 1 'pt_BR' team
self.assertEquals(self.project.available_teams.count(), 1)
# Create a new 'ar' team for self.project
team = Team.objects.get_or_create(language=self.language_ar,
project=self.project, creator=self.user['maintainer'])[0]
# Create a secondary project and set it to outsource access to self.project
project = Project.objects.get_or_create(slug="foo",
defaults={'name':"Foo Project"},
source_language=self.language_en)[0]
project.outsource = self.project
# There must be 2 teams. One 'pt_BR' and a 'ar' one.
self.assertEquals(project.available_teams.count(), 2)
|
rvanlaar/easy-transifex
|
src/transifex/transifex/teams/tests/models.py
|
Python
|
bsd-2-clause
| 1,066 | 0.005629 |
#-*- coding: utf-8 -*-
# Implements Colobot model formats
# Copyright (c) 2014 Tomasz Kapuściński
import modelformat
import geometry
import struct
class ColobotNewTextFormat(modelformat.ModelFormat):
def __init__(self):
self.description = 'Colobot New Text format'
def get_extension(self):
return 'txt'
def read(self, filename, model, params):
input_file = open(filename, 'r')
triangle = geometry.Triangle()
materials = []
while True:
line = input_file.readline()
# eof
if len(line) == 0:
break
# comments are ignored
if line[0] == '#':
continue
# remove eol
if line[len(line)-1] == '\n':
line = line[:len(line)-1]
values = line.split(' ');
cmd = values[0]
if cmd == 'version':
model.version = int(values[1])
elif cmd == 'triangles':
continue
elif cmd == 'p1':
triangle.vertices[0] = parse_vertex(values)
elif cmd == 'p2':
triangle.vertices[1] = parse_vertex(values)
elif cmd == 'p3':
triangle.vertices[2] = parse_vertex(values)
elif cmd == 'mat':
triangle.material = parse_material(values)
elif cmd == 'tex1':
triangle.material.texture = values[1]
elif cmd == 'tex2':
triangle.material.texture2 = values[1]
elif cmd == 'var_tex2':
continue
elif cmd == 'lod_level':
triangle.material.lod = int(values[1])
elif cmd == 'state':
triangle.material.state = int(values[1])
mat_final = None
for mat in materials:
if triangle.material == mat:
mat_final = mat
if mat_final is None:
mat_final = triangle.material
materials.append(mat_final)
triangle.material = mat_final
model.triangles.append(triangle)
triangle = geometry.Triangle()
input_file.close()
return True
def write(self, filename, model, params):
output_file = open(filename, 'w')
version = 2
if 'version' in params:
version = int(params['version'])
# write header
output_file.write('# Colobot text model\n')
output_file.write('\n')
output_file.write('### HEAD\n')
output_file.write('version ' + str(version) + '\n')
output_file.write('total_triangles ' + str(len(model.triangles)) + '\n')
output_file.write('\n')
output_file.write('### TRIANGLES\n')
# write triangles
for triangle in model.triangles:
# write vertices
for i in range(3):
vertex = triangle.vertices[i]
output_file.write('p{} c {} {} {}'.format(i+1, vertex.x, vertex.y, vertex.z))
output_file.write(' n {} {} {}'.format(vertex.nx, vertex.ny, vertex.nz))
output_file.write(' t1 {} {}'.format(vertex.u1, vertex.v1))
output_file.write(' t2 {} {}\n'.format(vertex.u2, vertex.v2))
mat = triangle.material
dirt = 'N'
dirt_texture = ''
if 'dirt' in params:
dirt = 'Y'
dirt_texture = params['dirt']
output_file.write('mat dif {} {} {} {}'.format(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2], mat.diffuse[3]))
output_file.write(' amb {} {} {} {}'.format(mat.ambient[0], mat.ambient[1], mat.ambient[2], mat.ambient[3]))
output_file.write(' spc {} {} {} {}\n'.format(mat.specular[0], mat.specular[1], mat.specular[2], mat.specular[3]))
output_file.write('tex1 {}\n'.format(mat.texture))
output_file.write('tex2 {}\n'.format(dirt_texture))
output_file.write('var_tex2 {}\n'.format(dirt))
if version == 1:
output_file.write('lod_level 0\n')
output_file.write('state ' + str(mat.state) + '\n')
output_file.write('\n')
output_file.close()
return True
class ColobotOldFormat(modelformat.ModelFormat):
def __init__(self):
self.description = 'Colobot Old Binary format'
def get_extension(self):
return 'mod'
def read(self, filename, model, params):
input_file = open(filename, 'rb')
# read header
version_major = struct.unpack('=i', input_file.read(4))[0]
version_minor = struct.unpack('=i', input_file.read(4))[0]
triangle_count = struct.unpack('=i', input_file.read(4))[0]
if version_major != 1 or version_minor != 2:
print('Unsupported format version: {}.{}'.format(version_major, version_minor))
return False
# read and ignore padding
input_file.read(40)
materials = []
for index in range(triangle_count):
triangle = geometry.Triangle()
# used, selected, 2 byte padding
input_file.read(4)
for vertex in triangle.vertices:
# position, normal, uvs
floats = struct.unpack('=ffffffffff', input_file.read(40))
vertex.x = floats[0]
vertex.y = floats[1]
vertex.z = floats[2]
vertex.nx = floats[3]
vertex.ny = floats[4]
vertex.nz = floats[5]
vertex.u1 = floats[6]
vertex.v1 = floats[7]
vertex.u2 = floats[8]
vertex.v2 = floats[9]
# material colors
floats = struct.unpack('=fffffffffffffffff', input_file.read(17 * 4))
mat = triangle.material
for i in range(4):
mat.diffuse[i] = floats[0 + i]
mat.ambient[i] = floats[4 + i]
mat.specular[i] = floats[8 + i]
# texture name
chars = input_file.read(20)
for i in range(20):
if chars[i] == '\0':
mat.texture = struct.unpack('={}s'.format(i), chars[:i])[0]
break
values = struct.unpack('=ffiHHHH', input_file.read(20))
mat.state = values[2]
dirt = values[3]
if dirt != 0:
mat.texture2 = 'dirty{:02d}.png'.format(dirt)
# optimizing materials
replaced = False
for material in materials:
if mat == material:
triangle.material = material
replaced = True
break
if not replaced:
materials.append(mat)
model.triangles.append(triangle)
# end of triangle
input_file.close()
return True
def write(self, filename, model, params):
output_file = open(filename, 'wb')
# write header
output_file.write(struct.pack('i', 1)) # version major
output_file.write(struct.pack('i', 2)) # version minor
output_file.write(struct.pack('i', len(model.triangles))) # total triangles
# padding
for x in range(10):
output_file.write(struct.pack('i', 0))
# triangles
for triangle in model.triangles:
output_file.write(struct.pack('=B', True)) # used
output_file.write(struct.pack('=B', False)) # selected ?
output_file.write(struct.pack('=H', 0)) # padding (2 bytes)
# write vertices
for vertex in triangle.vertices:
output_file.write(struct.pack('=fff', vertex.x, vertex.y, vertex.z)) # vertex coord
output_file.write(struct.pack('=fff', vertex.nx, vertex.ny, vertex.nz)) # normal
output_file.write(struct.pack('=ff', vertex.u1, vertex.v1)) # tex coord 1
output_file.write(struct.pack('=ff', vertex.u2, vertex.v2)) # tex coord 2
# material info
mat = triangle.material
output_file.write(struct.pack('=ffff', mat.diffuse[0], mat.diffuse[1], mat.diffuse[2], mat.diffuse[3])) # diffuse color
output_file.write(struct.pack('=ffff', mat.ambient[0], mat.ambient[1], mat.ambient[2], mat.ambient[3])) # ambient color
output_file.write(struct.pack('=ffff', mat.specular[0], mat.specular[1], mat.specular[2], mat.specular[3])) # specular color
output_file.write(struct.pack('=ffff', 0.0, 0.0, 0.0, 0.0)) # emissive color
output_file.write(struct.pack('=f', 0.0)) # power
# texture name
output_file.write(mat.texture.encode('utf-8'))
# texture name padding
for i in range(20 - len(mat.texture)):
output_file.write(struct.pack('=x'))
dirt = 0
if 'dirt' in params:
dirt = int(params['dirt'])
output_file.write(struct.pack('=ff', 0.0, 10000.0)) # rendering range
output_file.write(struct.pack('i', mat.state)) # state
output_file.write(struct.pack('=H', dirt)) # dirt texture
output_file.write(struct.pack('=HHH', 0, 0, 0)) # reserved
output_file.close()
return True
def parse_vertex(values):
vertex_coord = geometry.VertexCoord(float(values[2]), float(values[3]), float(values[4]))
normal = geometry.Normal(float(values[6]), float(values[7]), float(values[8]))
tex_coord_1 = geometry.TexCoord(float(values[10]), float(values[11]))
tex_coord_2 = geometry.TexCoord(float(values[13]), float(values[14]))
return geometry.Vertex(vertex_coord, normal, tex_coord_1, tex_coord_2)
def parse_material(values):
material = geometry.Material()
for i in range(4):
material.diffuse[i] = float(values[2+i])
material.ambient[i] = float(values[7+i])
material.specular[i] = float(values[12+i])
return material
modelformat.register_format('colobot', ColobotOldFormat())
modelformat.register_format('old', ColobotOldFormat())
modelformat.register_format('new_txt', ColobotNewTextFormat())
modelformat.register_extension('mod', 'old')
modelformat.register_extension('txt', 'new_txt')
|
tomaszkax86/Colobot-Model-Converter
|
colobotformat.py
|
Python
|
bsd-2-clause
| 11,044 | 0.006249 |
# Copyright 2015, Province of British Columbia
# License: https://github.com/bcgov/ckanext-bcgov/blob/master/license
import json
import urllib2
import urllib
import pprint
from base import (site_url, api_key)
org_filename = './data/orgs_list.json'
data_string = json.dumps({'all_fields' : True})
org_list = []
try :
request = urllib2.Request(site_url + '/api/3/action/organization_list')
request.add_header('Authorization', api_key)
response = urllib2.urlopen(request, data_string)
assert response.code == 200
response_dict = json.loads(response.read())
assert response_dict['success'] is True
org_list = response_dict['result']
# pprint.pprint(user_list)
except Exception, e:
pass
#Create a dictionary of org_name : org_id
#We need this dictionary to get the id of each org when creating organizations
orgs_dict = {}
for org in org_list :
members = []
data_dict = {'id' : org['id'], 'object_type' : 'user'}
data_string = urllib.quote(json.dumps(data_dict))
try :
request = urllib2.Request(site_url + '/api/3/action/member_list')
request.add_header('Authorization', api_key)
response = urllib2.urlopen(request, data_string)
assert response.code == 200
response_dict = json.loads(response.read())
assert response_dict['success'] is True
members = response_dict['result']
# pprint.pprint(user_list)
except Exception, e:
pass
org_dict = {'id' : org['id'], 'members' : members}
orgs_dict[org['name']] = org_dict
with open(org_filename, 'w') as org_file :
org_file.write(json.dumps(orgs_dict))
|
gjlawran/ckanext-bcgov
|
ckanext/bcgov/scripts/save_orgs.py
|
Python
|
agpl-3.0
| 1,656 | 0.010266 |
# Add ability to pass TF_Input_Dialog a data structure
# instead of an XML filename. XML file is only for
# initial creation, but for updates or showing user-
# modified settings, need this other option.
#---------------------------------------------------------
#!/usr/bin/env python
# August 8 & 11, 2008
# February 10, 2009
# April 21-28, 2009
# S.D. Peckham
import wx
import xml.dom.minidom
import time
import webbrowser ## standard Python module
## import wx.html
import glob
from TF_Input_Var_Box import * ################
# Check these out later.
# import urllib
# import xmllib (deprecated: use xml.sax instead)
# import htmllib
#-------------------------------------------------------------
# class TF_In_Variable_Info
# class TF_In_Variable_List
# class TF_Process_Info
# class TF_Input_Dialog
# In_Variable_Notebook
# In_Variable_Wizard #### (not ready yet)
# Timestep_Box
# Button_Box
# On_Type_Choice
# On_OK
# On_Help
# On_Cancel
# Read_XML_Info
#----------------------------------------------------------------
class TF_In_Variable_Info():
def __init__(self, name='', label='', vtype='Scalar',
value='', units='', type_choices=None):
self.name = name
self.label = label
self.type = vtype
self.value = value
self.units = units
if (type_choices == None):
self.type_choices = ['Scalar', 'Time series', \
'Grid', 'Grid sequence']
# __init__()
#----------------------------------------------------------------
class TF_In_Variable_List():
def __init__(self, n_variables=1):
#-----------------
# First approach
#-----------------
## self.variables = []
## for each in range(n_variables):
## self.variables.append( TF_Variable_Info() )
#------------------------------------------
# Alternate approach with some advantages
#------------------------------------------
self.var_names = []
self.var_labels = []
self.var_types = []
self.var_values = []
self.var_units = []
self.var_type_choices = []
# __init__()
#----------------------------------------------------------------
class TF_Process_Info():
def __init__(self, name='Infiltration',
n_layers=1, n_variables=1):
#----------------------------------------
# Each layer has a list of TF variables
#----------------------------------------
self.n_layers = n_layers
self.n_variables = n_variables # (per layer)
self.layers = []
for each in range(n_layers):
self.layers.append( TF_In_Variable_List(n_variables=n_variables) )
self.timestep = TF_In_Variable_Info()
self.help_file = ''
# __init__()
#-------------------------------------------------------------
class TF_Input_Dialog(wx.Frame):
#-----------------------------------------------------
# Notes: This class is for creating TopoFlow input
# dialogs, which all use a similar template.
# Initial settings, labels, etc. are read
# from the XML file provided
# Default is wx.ALIGN_LEFT for labels & text
#-----------------------------------------------------
def __init__(self, parent=None, id=-1,
main_frame=None,
xml_file="infil_richards_1D.xml"):
#-----------------------
# Try to find XML file
#-----------------------
files = glob.glob(xml_file)
if (len(files) == 0):
msg = "Can't find the XML file:\n\n"
msg += (xml_file + "\n")
dialog = wx.MessageBox(msg, caption='SORRY,')
return
#--------------------------------------------
# Set XML file to read info from, including
# the name of the HTML help file
#--------------------------------------------
self.xml_file = xml_file
self.Read_XML_Info()
#----------------------------------
# Get title for this input dialog
#----------------------------------
title = self.proc_info.proc_name + " : " + \
self.proc_info.method_name + \
" Input Dialog"
#-------------------------------------------
# Initialize a wxPython frame, add a panel
#-------------------------------------------
wx.Frame.__init__(self, parent, id, title)
panel = wx.Panel(self, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
panel.SetBackgroundColour('Light Blue')
self.panel = panel
self.main_sizer = sizer
#--------------------------------------------------
# Saving main_frame allows collected values to be
# stored in its state before this one closes.
#--------------------------------------------------
self.main_frame = main_frame
self.parent = parent
self.title = title
self.vgap = 10
self.hgap = 6
#-------------------------------------------------
# Later move these into Variable_Box() or remove
#-------------------------------------------------
self.type_code = {'Scalar':0, 'Time series':1, \
'Grid':2, 'Grid sequence':3}
self.type_name = {0:'Scalar', 1:'Time series', \
2:'Grid', 3:'Grid sequence'}
#-----------------------------------------
# Create objects to appear in the dialog
#-----------------------------------------
if (self.proc_info.n_layers == 1):
data = self.proc_info.layers[0]
var_box = TF_Input_Var_Box(parent=self.panel,
main_frame=self.main_frame,
data=data)
else:
var_box = self.In_Variable_Notebook()
## var_box = self.In_Variable_Wizard()
ADD_TIME_BOX = (self.proc_info.timestep.value != '')
if (ADD_TIME_BOX):
time_box = self.Timestep_Box()
button_bar = self.Button_Box()
#--------------------------------
# Add objects to the main sizer
#--------------------------------
border1 = self.vgap
border2 = 2 * self.vgap
sizer.Add(var_box, 0, wx.ALL, border1)
if (ADD_TIME_BOX):
sizer.Add(time_box, 0, wx.ALL, border1)
sizer.Add(button_bar, 0, wx.ALL, border2)
panel.SetSizer(sizer)
sizer.Fit(self)
self.Show() # (need here if called)
self.Centre()
## sizer.SetSizeHints(self) # (not needed)
#--------------------------------------------
# Doesn't work for some reason (see p. 328)
#--------------------------------------------
# self.SetSizer(sizer)
# self.Fit()
# __init__()
#----------------------------------------------------------------
def In_Variable_Notebook(self):
notebook = wx.Notebook(self.panel, style=wx.BK_TOP)
k = 0
n_layers = self.proc_info.n_layers
for k in range(n_layers):
data = self.proc_info.layers[k]
kstr = str(k+1)
label = "Layer " + kstr + " variables"
page = TF_Input_Var_Box(parent=notebook, \
data=data, \
box_label=label)
notebook.AddPage(page, "Layer " + kstr)
return notebook
# In_Variable_Notebook()
#----------------------------------------------------------------
def In_Variable_Wizard(self):
pass
# In_Variable_Wizard()
#----------------------------------------------------------------
def Timestep_Box(self):
#---------------------------------------------
# Create sizer box for the process timestep
#---------------------------------------------
time_info = self.proc_info.timestep
unit_str = "[" + time_info.units + "]"
## unit_str = "[" + time_info.units + " / timestep]"
L1 = wx.StaticText(self.panel, -1, time_info.label + ":")
text = wx.TextCtrl(self.panel, -1, time_info.value)
L2 = wx.StaticText(self.panel, -1, unit_str)
#-------------------------------------------------------
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add((3*self.hgap, 3*self.hgap), 1)
box.Add(L1)
box.Add((self.hgap, self.hgap), 1)
box.Add(text)
box.Add((self.hgap, self.hgap), 1)
box.Add(L2)
# self.SetSizer(box) ## (Bad to do this here.)
return box
# Timestep_Box()
#----------------------------------------------------------------
def Button_Box(self):
#----------------------------
# Create bottom button bar
#----------------------------
okay_btn = wx.Button(self.panel, -1, "OK")
help_btn = wx.Button(self.panel, -1, "Help")
cancel_btn = wx.Button(self.panel, -1, "Cancel")
#-------------------------------------------------
box = wx.BoxSizer(wx.HORIZONTAL)
proportion = 0
border = 5
box.Add((20,20), proportion, border)
box.Add(okay_btn, proportion, border)
box.Add((10,10), proportion, border)
box.Add(help_btn, proportion, border)
box.Add((10,10), proportion, border)
box.Add(cancel_btn, proportion, border)
box.Add((10,10), proportion, border)
# box.AddMany([okay_btn, help_btn, cancel_btn])
#-----------------------------------------------------
self.Bind(wx.EVT_BUTTON, self.On_OK, okay_btn)
self.Bind(wx.EVT_BUTTON, self.On_Help, help_btn)
self.Bind(wx.EVT_BUTTON, self.On_Cancel, cancel_btn)
return box
# Button_Box()
#----------------------------------------------------------------
# Note: On_Type_Choice() is located in TF_Input_Var_Box.py
#----------------------------------------------------------------
#----------------------------------------------------------------
def On_OK(self, event):
################################################
# Need to now include "layer" as well when
# saving values from text boxes to parent.
#
# Make sure that timestep gets saved also.
################################################
if (self.parent == None):
print 'Sorry: This dialog has no parent dialog,'
print 'so collected values cannot be saved.'
print ' '
return
#---------------------------------------------
# Read values from text boxes and save them
# in parent's state with droplist settings
#---------------------------------------------
# Can use validator with TextCtrl to check
# that values entered are valid (p. 282)
#---------------------------------------------
k = 0
for box in self.text_boxes:
val_string = box.GetValue()
if (len(val_string) == 0):
wx.MessageBox("Each text box must contain a number or a filename.", "Sorry,")
box.SetBackgroundColour("pink")
time.sleep(0.5)
box.SetFocus()
box.Refresh()
return
else:
#-----------------------------------------------
# Save values from GUI (numerical or string)
# into the state of the dialog's parent frame.
# (use var_types, var_units, var_values)
#-----------------------------------------------
self.var_values[k] = val_string # (update self)
print ' '
print 'Saving values into parent...'
value = val_string
label = self.var_labels[k]
tcode = self.type_code[ self.var_types[k] ]
field_str = 'self.parent.' + name
print "value =", value
exec(field_str + "_type = " + str(tcode))
if (tcode == 0):
exec(field_str + '= ' + value) # (scalar)
exec(field_str + "_file = ''")
else:
exec(field_str + '= None')
exec(field_str + '_file = "' + value + '"')
k += 1
#-----------------------------------------
# At this point, values in self are lost
# but values in parent TLB are retained.
#-----------------------------------------
self.Destroy()
# On_OK()
#----------------------------------------------------------------
def On_Help(self, event):
#---------------------------
# Open the default browser
#---------------------------
help_file = self.proc_info.help_file
result = webbrowser.open('file://' + help_file)
# On_Help()
#----------------------------------------------------------------
def On_Cancel(self, event):
self.Destroy()
# On_Cancel()
#----------------------------------------------------------------
def Read_XML_Info(self):
#---------------------------------------------------------
# Notes: It is helpful to have a look at the DOM specs,
# which can be found online at:
# http://www.w3.org/TR/1998/REC-DOM-Level-1-
# 19981001/introduction.html
# (see the tree diagram)
# http://www.w3.org/TR/1998/REC-DOM-Level-1-
# 19981001/level-one-core.html
# (search for "firstChild")
#---------------------------------------------------------
#--------------------------------------------
# Read input variable info from an XML file
#--------------------------------------------
file_obj = open(self.xml_file, 'r')
# Read entire file into a string
doc_string = file_obj.read()
dom = xml.dom.minidom.parseString( doc_string )
#----------------------------------------------
# Count all tags in XML file of various types
#----------------------------------------------
P_elements = dom.firstChild.getElementsByTagName("process")
L_elements = dom.firstChild.getElementsByTagName("layer")
V_elements = dom.firstChild.getElementsByTagName("variable")
T_elements = dom.firstChild.getElementsByTagName("timestep")
D_elements = dom.firstChild.getElementsByTagName("droplist")
H_elements = dom.firstChild.getElementsByTagName("help_file")
#-------------------------------------------------------------
nP = len(P_elements)
nL = len(L_elements)
nV = len(V_elements)
nT = len(T_elements)
nD = len(D_elements)
nH = len(H_elements)
## print 'n_layers =', nL
## print 'n_variables per layer =', (nV / nL)
#-------------------
# Issue warnings ?
#-------------------
msg = 'TopoFlow Input Dialog XML files \n'
if (nP > 1):
msg += 'may only contain 1 "process" tag. \n'
wx.MessageBox(msg, caption='ERROR ')
return
if (nL == 0):
msg += 'must contain 1 or more "layer" tags. \n'
wx.MessageBox(msg, caption='ERROR ')
return
## if (nT > 1) or (nT == 0):
## msg += 'must contain 1 "timestep" tag. \n'
## wx.MessageBox(msg, caption='ERROR ')
## return
#-----------------------------------------
# There should be 1 top-level child node
# that has the tag name "process"
#-----------------------------------------
# process_node = dom.childNodes[0]
process_node = dom.firstChild
#-------------------------------------------------
# Extract process name and store it in proc_info
#-------------------------------------------------
#---------------------------------------------
# Prepare to save process info from XML file
#---------------------------------------------
proc_info = TF_Process_Info(n_layers=nL, n_variables=nV/nL)
#---------------------------------
# Read proc_name and method_name
#---------------------------------
PN_nodes = process_node.getElementsByTagName("proc_name")
if (len(PN_nodes) > 0):
proc_info.proc_name = PN_nodes[0].firstChild.data.strip()
else:
proc_info.proc_name = "None"
MN_nodes = process_node.getElementsByTagName("method_name")
if (len(MN_nodes) > 0):
proc_info.method_name = MN_nodes[0].firstChild.data.strip()
else:
proc_info.method_name = "None"
#-------------------------------------------------------
# For each variable in each layer, save the associated
# information. The process node should have at least
# one layer tag.
#------------------------------------------------------
layer_nodes = process_node.getElementsByTagName("layer")
k = 0
for L_node in layer_nodes:
var_nodes = L_node.getElementsByTagName("variable")
j = 0
for V_node in var_nodes:
N_nodes = V_node.getElementsByTagName("name")
name = N_nodes[0].firstChild.data.strip()
#---------------------------------------------------
S_nodes = V_node.getElementsByTagName("label")
label = S_nodes[0].firstChild.data.strip()
#---------------------------------------------------
vtypes = V_node.getElementsByTagName("type")
vtype = vtypes[0].firstChild.data.strip()
#---------------------------------------------------
values = V_node.getElementsByTagName("value")
value = values[0].firstChild.data.strip()
#---------------------------------------------------
units = V_node.getElementsByTagName("units")
unit = units[0].firstChild.data.strip()
#---------------------------------------------------
tlists = V_node.getElementsByTagName("type_choices")
tlist = tlists[0].firstChild.data.strip().split(",")
#---------------------------------------------------
## proc_info.layers[k].variables[j].name = name
## proc_info.layers[k].variables[j].label = label
## proc_info.layers[k].variables[j].type = vtype
## proc_info.layers[k].variables[j].value = value
## proc_info.layers[k].variables[j].units = unit
## proc_info.layers[k].variables[j].type_choices = tlist
#-----------------------------------------------------
proc_info.layers[k].var_names.append( name )
proc_info.layers[k].var_labels.append( label )
proc_info.layers[k].var_types.append( vtype )
proc_info.layers[k].var_values.append( value )
proc_info.layers[k].var_units.append( unit )
proc_info.layers[k].var_type_choices.append( tlist )
#-----------------------------------------------------
j += 1
k += 1
#----------------------------
# Read timestep information
#----------------------------
if (nT > 0):
T_nodes = process_node.getElementsByTagName("timestep")
L_nodes = T_nodes[0].getElementsByTagName("label")
V_nodes = T_nodes[0].getElementsByTagName("value")
U_nodes = T_nodes[0].getElementsByTagName("units")
#-------------------------------------------------------
proc_info.timestep.label = L_nodes[0].firstChild.data
proc_info.timestep.value = V_nodes[0].firstChild.data
proc_info.timestep.units = U_nodes[0].firstChild.data
#------------------------------
# Read name of HTML help file
#------------------------------
H_nodes = process_node.getElementsByTagName("help_file")
if (len(H_nodes) > 0):
proc_info.help_file = H_nodes[0].firstChild.data.strip()
self.proc_info = proc_info
# Read_XML_Info()
#----------------------------------------------------------------
#---------------------------------------
# Support two different usage options
#---------------------------------------
if (__name__ == '__main__'):
app = wx.PySimpleApp()
#-------------------------------------
# Example with one layer and no tabs
#-------------------------------------
## frame = TF_Input_Dialog(parent=None, id=-1, \
## xml_file="xml/snowmelt_degree_day.xml")
#---------------------------------
# Example with 3 layers and tabs
#---------------------------------
frame = TF_Input_Dialog(parent=None, id=-1, \
xml_file="xml/infil_richards_1D.xml")
app.MainLoop()
|
peckhams/topoflow
|
topoflow/gui/Input_Dialog.py
|
Python
|
mit
| 21,814 | 0.011094 |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SuroLeveling
A QGIS plugin
todo
-------------------
begin : 2016-02-12
git sha : $Format:%H$
copyright : (C) 2016 by Ondřej Pešek
email : ondra.lobo@seznam.cz
***************************************************************************/
/***************************************************************************
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt
from PyQt4.QtGui import QAction, QIcon
# Initialize Qt resources from file resources.py
import resources
# Import the code for the DockWidget
#from suro_leveling_dockwidget import PositionCorrectionDockWidget#SuroLevelingDockWidget
from position_correction_dockwidget import PositionCorrectionDockWidget
import os.path
class PositionCorrection:#SuroLeveling:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'SuroLeveling_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&GPS position lag correction')
#print "** INITIALIZING SuroLeveling"
self.pluginIsActive = False
self.dockwidget = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('GPS position lag correction', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
self.iface.addToolBarIcon(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/SuroLeveling/icon.png'
self.add_action(
icon_path,
text=self.tr(u'GPS position lag correction'),
callback=self.run,
parent=self.iface.mainWindow())
#--------------------------------------------------------------------------
#def onClosePlugin(self): CAUSE OF ENABLE SECOND OPENING
# """Cleanup necessary items here when plugin dockwidget is closed"""
# print "** CLOSING SuroLeveling"
# disconnects
# self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
# self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
#print "** UNLOAD SuroLeveling"
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&GPS position lag correction'),
action)
self.iface.removeToolBarIcon(action)
#--------------------------------------------------------------------------
def run(self):
"""Run method that loads and starts the plugin"""
if not self.pluginIsActive:
self.pluginIsActive = True
#print "** STARTING SuroLeveling"
# dockwidget may not exist if:
# first run of plugin
# removed on close (see self.onClosePlugin method)
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = PositionCorrectionDockWidget()#SuroLevelingDockWidget()
# connect to provide cleanup on closing of dockwidget
# self.dockwidget.closingPlugin.connect(self.onClosePlugin) CAUSE OF ENABLE SECOND OPENING
# show the dockwidget
self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
self.dockwidget.show()
self.pluginIsActive = False
|
ctu-osgeorel-proj/bp-pesek-2016
|
src/position_correction.py
|
Python
|
gpl-2.0
| 7,629 | 0.003016 |
#! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Sat Apr 24 00:25:31 CEST 2010
import errno
import logging
import socket
import sys
import unittest
from syncless import coio
from syncless import wsgi
def TestApplication(env, start_response):
if env['PATH_INFO'] == '/answer':
start_response('200 OK', [('Content-Type', 'text/plain')])
return ('Forty-two.',)
if env['PATH_INFO'] == '/':
start_response('200 OK', [('Content-Type', 'text/html')])
return ['Hello, World!']
if env['PATH_INFO'] == '/save':
start_response('200 OK', [('Content-Type', 'text/plain')])
return [env['wsgi.input'].readline().upper()]
if env['PATH_INFO'] == 'policy-file':
start_response('200 OK', [('Content-Type', 'text/plain')])
return 'I hope you like our policy.'
# A run-time error caught by the wsgi moduel if this is reached.
TEST_DATE = wsgi.GetHttpDate(1234567890) # 2009-02-13
def CallWsgiWorker(accepted_socket, do_multirequest=True):
env = {}
wsgi.PopulateDefaultWsgiEnv(env, ('127.0.0.1', 80))
peer_name = ('127.0.0.1', 2)
wsgi.WsgiWorker(accepted_socket, peer_name, TestApplication, env, TEST_DATE,
do_multirequest, None)
def ParseHttpResponse(data):
head = 'Status: '
i = data.find('\n\n')
j = data.find('\n\r\n')
if i >= 0 and i < j:
head += data[:i]
body = data[i + 2:]
elif j >= 0:
head += data[:j]
body = data[j + 3:]
else:
raise ValueError('missing HTTP response headers: %r' % data)
# TODO(pts): Don't parse line continuations.
head = dict(line.split(': ', 1) for line in
head.rstrip('\r').replace('\r\n', '\n').split('\n'))
return head, body
def SplitHttpResponses(data):
"""Split a string containing multiple HTTP responses.
Returns:
List of strings (individual HTTP responses).
"""
return ['HTTP/1.' + item for item in data.split('HTTP/1.')[1:]]
class WsgiTest(unittest.TestCase):
# TODO(pts): Write more tests, especially for error responses.
# TODO(pts): Test HEAD requests.
def testDate(self):
self.assertEqual('Fri, 13 Feb 2009 23:31:30 GMT', TEST_DATE)
def AssertHelloResponse(self, head, body, http_version='1.0'):
self.assertEqual('Hello, World!', body)
self.assertEqual('HTTP/%s 200 OK' % http_version, head['Status'])
self.assertEqual('13', head['Content-Length'])
self.assertTrue('syncless' in head['Server'].lower(), head['Server'])
self.assertEqual(TEST_DATE, head['Date'])
self.assertEqual('text/html', head['Content-Type'])
def AssertAnswerResponse(self, head, body, http_version='1.0',
is_new_date=False):
self.assertEqual('Forty-two.', body)
self.assertEqual('HTTP/%s 200 OK' % http_version, head['Status'])
self.assertEqual('10', head['Content-Length'])
self.assertTrue('syncless' in head['Server'].lower(), head['Server'])
if is_new_date:
self.assertNotEqual(TEST_DATE, head['Date'])
self.assertTrue(head['Date'].endswith(' GMT'), head['Date'])
else:
self.assertEqual(TEST_DATE, head['Date'])
self.assertEqual('text/plain', head['Content-Type'])
def AssertSaveResponse(self, head, body, http_version='1.0',
is_new_date=False, msg='FOO\n'):
self.assertEqual(msg, body)
self.assertEqual('HTTP/%s 200 OK' % http_version, head['Status'])
self.assertEqual(str(len(msg)), head['Content-Length'])
self.assertTrue('syncless' in head['Server'].lower(), head['Server'])
if is_new_date:
self.assertNotEqual(TEST_DATE, head['Date'])
self.assertTrue(head['Date'].endswith(' GMT'), head['Date'])
else:
self.assertEqual(TEST_DATE, head['Date'])
self.assertEqual('text/plain', head['Content-Type'])
def testSingleRequestWithoutCr(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET / HTTP/1.0\n\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('close', head['Connection'])
self.AssertHelloResponse(head, body)
def testSingleGetRequest(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET / HTTP/1.0\r\n\r\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('close', head['Connection'])
self.AssertHelloResponse(head, body)
def testSingleTooLongRequest(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
max_size = min(coio.max_nonblocking_pipe_write_size, 33333)
request = 'GET / HTTP/1.0\r\n'
request += 'Xy: Z\r\n' * ((max_size - len(request)) / 7)
assert len(request) <= max_size
b.sendall(request)
b.shutdown(1)
CallWsgiWorker(a)
try:
response = b.recv(8192)
except IOError, e:
if e.errno != errno.ECONNRESET:
raise
# Some Linux 2.6.32 systems raise ECONNRESET if the peer is very fast
# to close the connection. The exact reasons why we get ECONNRESET
# instead of just an EOF sometimes is unclear to me.
response = ''
self.assertEqual('', response)
def testSinglePolicyFileRequest(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('<policy-file-request/>\0foobar')
b.shutdown(1)
CallWsgiWorker(a)
response = b.recv(8192)
self.assertEqual('I hope you like our policy.', response)
def testSinglePostRequest(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('POST /save HTTP/1.0\r\nContent-Length: 7\r\n'
'X-1: Z\r\n\r\nfoo\nbar')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('close', head['Connection'])
self.AssertSaveResponse(head, body)
def testContinuableHTTP10Request(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertHelloResponse(head, body)
def testContinuableHTTP11Request(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET /?foo=bar HTTP/1.1\r\n\r\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertHelloResponse(head, body, http_version='1.1')
def testTwoSequentialHTTP11GetFirstRequests(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET / HTTP/1.1\r\n\r\n')
CallWsgiWorker(a, do_multirequest=False)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertHelloResponse(head, body, http_version='1.1')
b.sendall('GET /answer?foo=bar HTTP/1.1\r\n\r\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertAnswerResponse(head, body, http_version='1.1')
def testTwoSequentialHTTP11PostFirstRequests(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('POST /save HTTP/1.1\r\nContent-Length: 7\r\n\r\nfoo\nbar')
CallWsgiWorker(a, do_multirequest=False)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertSaveResponse(head, body, http_version='1.1')
b.sendall('GET /answer?foo=bar HTTP/1.1\r\n\r\n')
b.shutdown(1)
CallWsgiWorker(a)
head, body = ParseHttpResponse(b.recv(8192))
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertAnswerResponse(head, body, http_version='1.1')
def testThreePipelinedHTTP11GetRequests(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('GET / HTTP/1.1\r\n\r\n'
'GET /answer?foo=x+y&bar= HTTP/1.0\r\n\r\n'
'GET /unreached... HTTP/1.1\r\n\r\n')
CallWsgiWorker(a)
responses = SplitHttpResponses(b.recv(8192))
# The WsgiWorker doesn't respond to request 2 (/unreached...), because
# the previous request was a HTTP/1.0 request with default Connection:
# close (so keep-alive is false).
self.assertEqual(2, len(responses))
head, body = ParseHttpResponse(responses[0])
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertHelloResponse(head, body, http_version='1.1')
head, body = ParseHttpResponse(responses[1])
self.assertEqual('close', head['Connection'])
self.AssertAnswerResponse(head, body, http_version='1.0',
is_new_date=True)
def testFourPipelinedHTTP11PostFirstRequests(self):
a, b = coio.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
b.sendall('POST /save HTTP/1.1\r\nContent-Length: 7\r\n\r\nfoo\nbar'
'POST /save HTTP/1.1\r\nContent-Length: 10\r\n\r\nNice!\ngood'
'GET /answer?foo=x+y&bar= HTTP/1.0\r\n\r\n'
'GET /unreached... HTTP/1.1\r\n\r\n')
CallWsgiWorker(a)
responses = SplitHttpResponses(b.recv(8192))
self.assertEqual(3, len(responses))
head, body = ParseHttpResponse(responses[0])
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertSaveResponse(head, body, http_version='1.1')
head, body = ParseHttpResponse(responses[1])
self.assertEqual('Keep-Alive', head['Connection'])
self.AssertSaveResponse(head, body, http_version='1.1',
msg='NICE!\n', is_new_date=True)
head, body = ParseHttpResponse(responses[2])
self.assertEqual('close', head['Connection'])
self.AssertAnswerResponse(head, body, http_version='1.0',
is_new_date=True)
if __name__ == '__main__':
if '-v' in sys.argv[1:]:
logging.BASIC_FORMAT = '[%(created)f] %(levelname)s %(message)s'
logging.root.setLevel(logging.DEBUG)
unittest.main()
|
HanWenfang/syncless
|
test/wsgi_test.py
|
Python
|
apache-2.0
| 9,998 | 0.005501 |
# coding: utf-8
__version__ = '0.1.0'
|
Locu/djredis
|
djredis/__init__.py
|
Python
|
mit
| 38 | 0 |
"""
Copyright (c) 2018 Doyub Kim
I am making my contributions/submissions to this project solely in my personal
capacity and am not conveying any rights to any intellectual property of any
third parties.
"""
import numpy as np
import pyjet
from pytest import approx
from pytest_utils import *
cnt = 0
def test_grid2():
global cnt
a = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOrigin=(7, 5))
assert a.resolution == (3, 4)
assert_vector_similar(a.origin, (7, 5))
assert_vector_similar(a.gridSpacing, (1, 2))
assert_bounding_box_similar(
a.boundingBox, pyjet.BoundingBox2D((7, 5), (10, 13)))
f = a.cellCenterPosition
assert_vector_similar(f(0, 0), (7.5, 6))
b = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOrigin=(7, 5))
assert a.hasSameShape(b)
def func(i, j):
global cnt
assert i >= 0 and i < 3
assert j >= 0 and j < 4
cnt += 1
cnt = 0
a.forEachCellIndex(func)
assert cnt == 12
def test_scalar_grid2():
global cnt
a = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOrigin=(7, 5))
a.resize(resolution=(12, 7),
gridSpacing=(3, 4),
gridOrigin=(9, 2))
assert a.resolution == (12, 7)
assert_vector_similar(a.origin, (9, 2))
assert_vector_similar(a.gridSpacing, (3, 4))
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == 0.0
a[5, 6] = 17.0
assert a[5, 6] == 17.0
a.fill(42.0)
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == 42.0
def func(pt):
return pt.x ** 2 + pt.y ** 2
a.fill(func)
pos = a.dataPosition()
acc = np.array(a.dataAccessor(), copy=False)
for j in range(a.resolution.y):
for i in range(a.resolution.x):
pt = pos(i, j)
assert func(pt) == a[i, j]
assert func(pt) == approx(a.sample(pt))
assert acc[j, i] == a[i, j]
# Can't compare to analytic solution because FDM with such a coarse
# grid will return inaccurate results by design.
assert_vector_similar(a.gradientAtDataPoint(i, j), a.gradient(pt))
assert a.laplacianAtDataPoint(i, j) == a.laplacian(pt)
def func(i, j):
global cnt
assert i >= 0 and i < a.resolution.x
assert j >= 0 and j < a.resolution.y
cnt += 1
cnt = 0
a.forEachDataPointIndex(func)
assert cnt == a.resolution.x * a.resolution.y
blob = a.serialize()
b = pyjet.CellCenteredScalarGrid2()
b.deserialize(blob)
assert b.resolution == (12, 7)
assert_vector_similar(b.origin, (9, 2))
assert_vector_similar(b.gridSpacing, (3, 4))
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == b[i, j]
def test_cell_centered_scalar_grid2():
# CTOR
a = pyjet.CellCenteredScalarGrid2()
assert a.resolution == (1, 1)
assert_vector_similar(a.origin, (0.0, 0.0))
assert_vector_similar(a.gridSpacing, (1.0, 1.0))
a = pyjet.CellCenteredScalarGrid2((3, 4), (1, 2), (7, 5))
assert a.resolution == (3, 4)
assert_vector_similar(a.origin, (7, 5))
assert_vector_similar(a.gridSpacing, (1, 2))
a = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOrigin=(7, 5))
assert a.resolution == (3, 4)
assert_vector_similar(a.origin, (7, 5))
assert_vector_similar(a.gridSpacing, (1, 2))
a = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
domainSizeX=12.0,
gridOrigin=(7, 5))
assert a.resolution == (3, 4)
assert_vector_similar(a.origin, (7, 5))
assert_vector_similar(a.gridSpacing, (4, 4))
# Properties
a = pyjet.CellCenteredScalarGrid2(resolution=(3, 4),
gridSpacing=(1, 2),
gridOrigin=(7, 5))
assert_vector_similar(a.dataSize, (3, 4))
assert_vector_similar(a.dataOrigin, (7.5, 6))
# Modifiers
b = pyjet.CellCenteredScalarGrid2(resolution=(6, 3),
gridSpacing=(5, 9),
gridOrigin=(1, 2))
a.fill(42.0)
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == 42.0
a.swap(b)
assert a.resolution == (6, 3)
assert_vector_similar(a.origin, (1, 2))
assert_vector_similar(a.gridSpacing, (5, 9))
assert b.resolution == (3, 4)
assert_vector_similar(b.origin, (7, 5))
assert_vector_similar(b.gridSpacing, (1, 2))
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == 0.0
for j in range(b.resolution.y):
for i in range(b.resolution.x):
assert b[i, j] == 42.0
a.set(b)
assert a.resolution == (3, 4)
assert_vector_similar(a.origin, (7, 5))
assert_vector_similar(a.gridSpacing, (1, 2))
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j] == 42.0
c = a.clone()
assert c.resolution == (3, 4)
assert_vector_similar(c.origin, (7, 5))
assert_vector_similar(c.gridSpacing, (1, 2))
for j in range(c.resolution.y):
for i in range(c.resolution.x):
assert c[i, j] == 42.0
# ------------------------------------------------------------------------------
def test_grid3():
global cnt
a = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
gridSpacing=(1, 2, 3),
gridOrigin=(7, 5, 3))
assert a.resolution == (3, 4, 5)
assert_vector_similar(a.origin, (7, 5, 3))
assert_vector_similar(a.gridSpacing, (1, 2, 3))
assert_bounding_box_similar(
a.boundingBox, pyjet.BoundingBox3D((7, 5, 3), (10, 13, 18)))
f = a.cellCenterPosition
assert_vector_similar(f(0, 0, 0), (7.5, 6, 4.5))
b = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
gridSpacing=(1, 2, 3),
gridOrigin=(7, 5, 3))
assert a.hasSameShape(b)
def func(i, j, k):
global cnt
assert i >= 0 and i < 3
assert j >= 0 and j < 4
assert k >= 0 and k < 5
cnt += 1
cnt = 0
a.forEachCellIndex(func)
assert cnt == 60
def test_scalar_grid3():
global cnt
a = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
gridSpacing=(1, 2, 3),
gridOrigin=(7, 5, 3))
a.resize(resolution=(12, 7, 2),
gridSpacing=(3, 4, 5),
gridOrigin=(9, 2, 5))
assert a.resolution == (12, 7, 2)
assert_vector_similar(a.origin, (9, 2, 5))
assert_vector_similar(a.gridSpacing, (3, 4, 5))
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == 0.0
a[5, 6, 1] = 17.0
assert a[5, 6, 1] == 17.0
a.fill(42.0)
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == 42.0
def func(pt):
return pt.x ** 2 + pt.y ** 2 + pt.z ** 2
a.fill(func)
pos = a.dataPosition()
acc = np.array(a.dataAccessor(), copy=False)
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
pt = pos(i, j, k)
assert func(pt) == a[i, j, k]
assert func(pt) == approx(a.sample(pt))
assert acc[k, j, i] == a[i, j, k]
# Can't compare to analytic solution because FDM with such a
# coarse grid will return inaccurate results by design.
assert_vector_similar(
a.gradientAtDataPoint(i, j, k), a.gradient(pt))
assert a.laplacianAtDataPoint(i, j, k) == a.laplacian(pt)
def func(i, j, k):
global cnt
assert i >= 0 and i < a.resolution.x
assert j >= 0 and j < a.resolution.y
assert k >= 0 and k < a.resolution.z
cnt += 1
cnt = 0
a.forEachDataPointIndex(func)
assert cnt == a.resolution.x * a.resolution.y * a.resolution.z
blob = a.serialize()
b = pyjet.CellCenteredScalarGrid3()
b.deserialize(blob)
assert b.resolution == (12, 7, 2)
assert_vector_similar(b.origin, (9, 2, 5))
assert_vector_similar(b.gridSpacing, (3, 4, 5))
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == b[i, j, k]
def test_cell_centered_scalar_grid3():
# CTOR
a = pyjet.CellCenteredScalarGrid3()
assert a.resolution == (1, 1, 1)
assert_vector_similar(a.origin, (0.0, 0.0, 0.0))
assert_vector_similar(a.gridSpacing, (1.0, 1.0, 1.0))
a = pyjet.CellCenteredScalarGrid3((3, 4, 5), (1, 2, 3), (7, 5, 2))
assert a.resolution == (3, 4, 5)
assert_vector_similar(a.origin, (7, 5, 2))
assert_vector_similar(a.gridSpacing, (1, 2, 3))
a = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
gridSpacing=(1, 2, 3),
gridOrigin=(7, 5, 2))
assert a.resolution == (3, 4, 5)
assert_vector_similar(a.origin, (7, 5, 2))
assert_vector_similar(a.gridSpacing, (1, 2, 3))
a = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
domainSizeX=12.0,
gridOrigin=(7, 5, 2))
assert a.resolution == (3, 4, 5)
assert_vector_similar(a.origin, (7, 5, 2))
assert_vector_similar(a.gridSpacing, (4, 4, 4))
# Properties
a = pyjet.CellCenteredScalarGrid3(resolution=(3, 4, 5),
gridSpacing=(1, 2, 3),
gridOrigin=(7, 5, 2))
assert_vector_similar(a.dataSize, (3, 4, 5))
assert_vector_similar(a.dataOrigin, (7.5, 6, 3.5))
# Modifiers
b = pyjet.CellCenteredScalarGrid3(resolution=(6, 3, 7),
gridSpacing=(5, 9, 3),
gridOrigin=(1, 2, 8))
a.fill(42.0)
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == 42.0
a.swap(b)
assert a.resolution == (6, 3, 7)
assert_vector_similar(a.origin, (1, 2, 8))
assert_vector_similar(a.gridSpacing, (5, 9, 3))
assert b.resolution == (3, 4, 5)
assert_vector_similar(b.origin, (7, 5, 2))
assert_vector_similar(b.gridSpacing, (1, 2, 3))
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == 0.0
for k in range(b.resolution.z):
for j in range(b.resolution.y):
for i in range(b.resolution.x):
assert b[i, j, k] == 42.0
a.set(b)
assert a.resolution == (3, 4, 5)
assert_vector_similar(a.origin, (7, 5, 2))
assert_vector_similar(a.gridSpacing, (1, 2, 3))
for k in range(a.resolution.z):
for j in range(a.resolution.y):
for i in range(a.resolution.x):
assert a[i, j, k] == 42.0
c = a.clone()
assert c.resolution == (3, 4, 5)
assert_vector_similar(c.origin, (7, 5, 2))
assert_vector_similar(c.gridSpacing, (1, 2, 3))
for k in range(c.resolution.z):
for j in range(c.resolution.y):
for i in range(c.resolution.x):
assert c[i, j, k] == 42.0
|
doyubkim/fluid-engine-dev
|
src/tests/python_tests/test_cell_centered_scalar_grid.py
|
Python
|
mit
| 12,197 | 0 |
# -*- coding: utf-8 -*-
from odoo.addons.account_edi.tests.common import AccountEdiTestCommon
from odoo.tests import tagged
from odoo import Command
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestL10nBeEdi(AccountEdiTestCommon):
@classmethod
def setUpClass(cls, chart_template_ref='l10n_be.l10nbe_chart_template', edi_format_ref='l10n_be_edi.edi_efff_1'):
super().setUpClass(chart_template_ref=chart_template_ref, edi_format_ref=edi_format_ref)
# ==== Init ====
cls.tax_10_include = cls.env['account.tax'].create({
'name': 'tax_10_include',
'amount_type': 'percent',
'amount': 10,
'type_tax_use': 'sale',
'price_include': True,
'include_base_amount': True,
'sequence': 10,
})
cls.tax_20 = cls.env['account.tax'].create({
'name': 'tax_20',
'amount_type': 'percent',
'amount': 20,
'invoice_repartition_line_ids': [
(0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}),
(0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}),
(0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}),
],
'refund_repartition_line_ids': [
(0, 0, {'factor_percent': 100.0, 'repartition_type': 'base'}),
(0, 0, {'factor_percent': 40.0, 'repartition_type': 'tax'}),
(0, 0, {'factor_percent': 60.0, 'repartition_type': 'tax'}),
],
'type_tax_use': 'sale',
'sequence': 20,
})
cls.tax_group = cls.env['account.tax'].create({
'name': 'tax_group',
'amount_type': 'group',
'amount': 0.0,
'type_tax_use': 'sale',
'children_tax_ids': [(6, 0, (cls.tax_10_include + cls.tax_20).ids)],
})
cls.partner_a.vat = 'BE0477472701'
# ==== Invoice ====
cls.invoice = cls.env['account.move'].create({
'move_type': 'out_invoice',
'journal_id': cls.journal.id,
'partner_id': cls.partner_b.id,
'invoice_date': '2017-01-01',
'date': '2017-01-01',
'currency_id': cls.currency_data['currency'].id,
'invoice_line_ids': [(0, 0, {
'product_id': cls.product_a.id,
'product_uom_id': cls.env.ref('uom.product_uom_dozen').id,
'price_unit': 275.0,
'quantity': 5,
'discount': 20.0,
'tax_ids': [(6, 0, cls.tax_20.ids)],
})],
})
cls.expected_invoice_efff_values = '''
<Invoice>
<UBLVersionID>2.0</UBLVersionID>
<ID>INV/2017/00001</ID>
<IssueDate>2017-01-01</IssueDate>
<InvoiceTypeCode>380</InvoiceTypeCode>
<DocumentCurrencyCode>Gol</DocumentCurrencyCode>
<AccountingSupplierParty>
<Party>
<PartyName>
<Name>company_1_data</Name>
</PartyName>
<Language>
<LocaleCode>en_US</LocaleCode>
</Language>
<PostalAddress/>
<Contact>
<Name>company_1_data</Name>
</Contact>
</Party>
</AccountingSupplierParty>
<AccountingCustomerParty>
<Party>
<PartyName>
<Name>partner_b</Name>
</PartyName>
<Language>
<LocaleCode>en_US</LocaleCode>
</Language>
<PostalAddress/>
<Contact>
<Name>partner_b</Name>
</Contact>
</Party>
</AccountingCustomerParty>
<PaymentMeans>
<PaymentMeansCode listID="UN/ECE 4461">31</PaymentMeansCode>
<PaymentDueDate>2017-01-01</PaymentDueDate>
<InstructionID>INV/2017/00001</InstructionID>
</PaymentMeans>
<TaxTotal>
<TaxAmount currencyID="Gol">220.000</TaxAmount>
</TaxTotal>
<LegalMonetaryTotal>
<LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount>
<TaxExclusiveAmount currencyID="Gol">1100.000</TaxExclusiveAmount>
<TaxInclusiveAmount currencyID="Gol">1320.000</TaxInclusiveAmount>
<PrepaidAmount currencyID="Gol">0.000</PrepaidAmount>
<PayableAmount currencyID="Gol">1320.000</PayableAmount>
</LegalMonetaryTotal>
<InvoiceLine>
<ID>___ignore___</ID>
<Note>Discount (20.0 %)</Note>
<InvoicedQuantity>5.0</InvoicedQuantity>
<LineExtensionAmount currencyID="Gol">1100.000</LineExtensionAmount>
<TaxTotal>
<TaxAmount currencyID="Gol">220.000</TaxAmount>
</TaxTotal>
<Item>
<Description>product_a</Description>
<Name>product_a</Name>
</Item>
<Price>
<PriceAmount currencyID="Gol">275.000</PriceAmount>
</Price>
</InvoiceLine>
</Invoice>
'''
####################################################
# Test export
####################################################
def test_efff_simple_case(self):
''' Test the generated Facturx Edi attachment without any modification of the invoice. '''
self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values)
def test_efff_group_of_taxes(self):
self.invoice.write({
'invoice_line_ids': [(1, self.invoice.invoice_line_ids.id, {'tax_ids': [Command.set(self.tax_group.ids)]})],
})
applied_xpath = '''
<xpath expr="//TaxTotal/TaxAmount" position="replace">
<TaxAmount currencyID="Gol">320.000</TaxAmount>
</xpath>
<xpath expr="//LegalMonetaryTotal/LineExtensionAmount" position="replace">
<LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount>
</xpath>
<xpath expr="//LegalMonetaryTotal/TaxExclusiveAmount" position="replace">
<TaxExclusiveAmount currencyID="Gol">1000.000</TaxExclusiveAmount>
</xpath>
<xpath expr="//InvoiceLine/LineExtensionAmount" position="replace">
<LineExtensionAmount currencyID="Gol">1000.000</LineExtensionAmount>
</xpath>
<xpath expr="//InvoiceLine/TaxTotal" position="replace">
<TaxTotal>
<TaxAmount currencyID="Gol">100.000</TaxAmount>
</TaxTotal>
<TaxTotal>
<TaxAmount currencyID="Gol">220.000</TaxAmount>
</TaxTotal>
</xpath>
'''
self.assert_generated_file_equal(self.invoice, self.expected_invoice_efff_values, applied_xpath)
####################################################
# Test import
####################################################
def test_invoice_edi_xml_update(self):
invoice = self._create_empty_vendor_bill()
invoice_count = len(self.env['account.move'].search([]))
self.update_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml', invoice)
self.assertEqual(len(self.env['account.move'].search([])), invoice_count)
self.assertEqual(invoice.amount_total, 666.50)
self.assertEqual(invoice.amount_tax, 115.67)
self.assertEqual(invoice.partner_id, self.partner_a)
def test_invoice_edi_xml_create(self):
invoice_count = len(self.env['account.move'].search([]))
invoice = self.create_invoice_from_file('l10n_be_edi', 'test_xml_file', 'efff_test.xml')
self.assertEqual(len(self.env['account.move'].search([])), invoice_count + 1)
self.assertEqual(invoice.amount_total, 666.50)
self.assertEqual(invoice.amount_tax, 115.67)
self.assertEqual(invoice.partner_id, self.partner_a)
|
jeremiahyan/odoo
|
addons/l10n_be_edi/tests/test_ubl.py
|
Python
|
gpl-3.0
| 8,636 | 0.002432 |
# Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 2 of the License, or
# (at your option) any later version.
#
# Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: MHL
@license: GNU General Public License 2.0
@contact: michael.ligh@mnin.org
This file provides support for Vista SP1 and SP2 x64
"""
syscalls = [
[
'NtMapUserPhysicalPagesScatter', # 0x0
'NtWaitForSingleObject', # 0x1
'NtCallbackReturn', # 0x2
'NtReadFile', # 0x3
'NtDeviceIoControlFile', # 0x4
'NtWriteFile', # 0x5
'NtRemoveIoCompletion', # 0x6
'NtReleaseSemaphore', # 0x7
'NtReplyWaitReceivePort', # 0x8
'NtReplyPort', # 0x9
'NtSetInformationThread', # 0xa
'NtSetEvent', # 0xb
'NtClose', # 0xc
'NtQueryObject', # 0xd
'NtQueryInformationFile', # 0xe
'NtOpenKey', # 0xf
'NtEnumerateValueKey', # 0x10
'NtFindAtom', # 0x11
'NtQueryDefaultLocale', # 0x12
'NtQueryKey', # 0x13
'NtQueryValueKey', # 0x14
'NtAllocateVirtualMemory', # 0x15
'NtQueryInformationProcess', # 0x16
'NtWaitForMultipleObjects32', # 0x17
'NtWriteFileGather', # 0x18
'NtSetInformationProcess', # 0x19
'NtCreateKey', # 0x1a
'NtFreeVirtualMemory', # 0x1b
'NtImpersonateClientOfPort', # 0x1c
'NtReleaseMutant', # 0x1d
'NtQueryInformationToken', # 0x1e
'NtRequestWaitReplyPort', # 0x1f
'NtQueryVirtualMemory', # 0x20
'NtOpenThreadToken', # 0x21
'NtQueryInformationThread', # 0x22
'NtOpenProcess', # 0x23
'NtSetInformationFile', # 0x24
'NtMapViewOfSection', # 0x25
'NtAccessCheckAndAuditAlarm', # 0x26
'NtUnmapViewOfSection', # 0x27
'NtReplyWaitReceivePortEx', # 0x28
'NtTerminateProcess', # 0x29
'NtSetEventBoostPriority', # 0x2a
'NtReadFileScatter', # 0x2b
'NtOpenThreadTokenEx', # 0x2c
'NtOpenProcessTokenEx', # 0x2d
'NtQueryPerformanceCounter', # 0x2e
'NtEnumerateKey', # 0x2f
'NtOpenFile', # 0x30
'NtDelayExecution', # 0x31
'NtQueryDirectoryFile', # 0x32
'NtQuerySystemInformation', # 0x33
'NtOpenSection', # 0x34
'NtQueryTimer', # 0x35
'NtFsControlFile', # 0x36
'NtWriteVirtualMemory', # 0x37
'NtCloseObjectAuditAlarm', # 0x38
'NtDuplicateObject', # 0x39
'NtQueryAttributesFile', # 0x3a
'NtClearEvent', # 0x3b
'NtReadVirtualMemory', # 0x3c
'NtOpenEvent', # 0x3d
'NtAdjustPrivilegesToken', # 0x3e
'NtDuplicateToken', # 0x3f
'NtContinue', # 0x40
'NtQueryDefaultUILanguage', # 0x41
'NtQueueApcThread', # 0x42
'NtYieldExecution', # 0x43
'NtAddAtom', # 0x44
'NtCreateEvent', # 0x45
'NtQueryVolumeInformationFile', # 0x46
'NtCreateSection', # 0x47
'NtFlushBuffersFile', # 0x48
'NtApphelpCacheControl', # 0x49
'NtCreateProcessEx', # 0x4a
'NtCreateThread', # 0x4b
'NtIsProcessInJob', # 0x4c
'NtProtectVirtualMemory', # 0x4d
'NtQuerySection', # 0x4e
'NtResumeThread', # 0x4f
'NtTerminateThread', # 0x50
'NtReadRequestData', # 0x51
'NtCreateFile', # 0x52
'NtQueryEvent', # 0x53
'NtWriteRequestData', # 0x54
'NtOpenDirectoryObject', # 0x55
'NtAccessCheckByTypeAndAuditAlarm', # 0x56
'NtQuerySystemTime', # 0x57
'NtWaitForMultipleObjects', # 0x58
'NtSetInformationObject', # 0x59
'NtCancelIoFile', # 0x5a
'NtTraceEvent', # 0x5b
'NtPowerInformation', # 0x5c
'NtSetValueKey', # 0x5d
'NtCancelTimer', # 0x5e
'NtSetTimer', # 0x5f
'NtAcceptConnectPort', # 0x60
'NtAccessCheck', # 0x61
'NtAccessCheckByType', # 0x62
'NtAccessCheckByTypeResultList', # 0x63
'NtAccessCheckByTypeResultListAndAuditAlarm', # 0x64
'NtAccessCheckByTypeResultListAndAuditAlarmByHandle', # 0x65
'NtAcquireCMFViewOwnership', # 0x66
'NtAddBootEntry', # 0x67
'NtAddDriverEntry', # 0x68
'NtAdjustGroupsToken', # 0x69
'NtAlertResumeThread', # 0x6a
'NtAlertThread', # 0x6b
'NtAllocateLocallyUniqueId', # 0x6c
'NtAllocateUserPhysicalPages', # 0x6d
'NtAllocateUuids', # 0x6e
'NtAlpcAcceptConnectPort', # 0x6f
'NtAlpcCancelMessage', # 0x70
'NtAlpcConnectPort', # 0x71
'NtAlpcCreatePort', # 0x72
'NtAlpcCreatePortSection', # 0x73
'NtAlpcCreateResourceReserve', # 0x74
'NtAlpcCreateSectionView', # 0x75
'NtAlpcCreateSecurityContext', # 0x76
'NtAlpcDeletePortSection', # 0x77
'NtAlpcDeleteResourceReserve', # 0x78
'NtAlpcDeleteSectionView', # 0x79
'NtAlpcDeleteSecurityContext', # 0x7a
'NtAlpcDisconnectPort', # 0x7b
'NtAlpcImpersonateClientOfPort', # 0x7c
'NtAlpcOpenSenderProcess', # 0x7d
'NtAlpcOpenSenderThread', # 0x7e
'NtAlpcQueryInformation', # 0x7f
'NtAlpcQueryInformationMessage', # 0x80
'NtAlpcRevokeSecurityContext', # 0x81
'NtAlpcSendWaitReceivePort', # 0x82
'NtAlpcSetInformation', # 0x83
'NtAreMappedFilesTheSame', # 0x84
'NtAssignProcessToJobObject', # 0x85
'NtCancelDeviceWakeupRequest', # 0x86
'NtCancelIoFileEx', # 0x87
'NtCancelSynchronousIoFile', # 0x88
'NtCommitComplete', # 0x89
'NtCommitEnlistment', # 0x8a
'NtCommitTransaction', # 0x8b
'NtCompactKeys', # 0x8c
'NtCompareTokens', # 0x8d
'NtCompleteConnectPort', # 0x8e
'NtCompressKey', # 0x8f
'NtConnectPort', # 0x90
'NtCreateDebugObject', # 0x91
'NtCreateDirectoryObject', # 0x92
'NtCreateEnlistment', # 0x93
'NtCreateEventPair', # 0x94
'NtCreateIoCompletion', # 0x95
'NtCreateJobObject', # 0x96
'NtCreateJobSet', # 0x97
'NtCreateKeyTransacted', # 0x98
'NtCreateKeyedEvent', # 0x99
'NtCreateMailslotFile', # 0x9a
'NtCreateMutant', # 0x9b
'NtCreateNamedPipeFile', # 0x9c
'NtCreatePagingFile', # 0x9d
'NtCreatePort', # 0x9e
'NtCreatePrivateNamespace', # 0x9f
'NtCreateProcess', # 0xa0
'NtCreateProfile', # 0xa1
'NtCreateResourceManager', # 0xa2
'NtCreateSemaphore', # 0xa3
'NtCreateSymbolicLinkObject', # 0xa4
'NtCreateThreadEx', # 0xa5
'NtCreateTimer', # 0xa6
'NtCreateToken', # 0xa7
'NtCreateTransaction', # 0xa8
'NtCreateTransactionManager', # 0xa9
'NtCreateUserProcess', # 0xaa
'NtCreateWaitablePort', # 0xab
'NtCreateWorkerFactory', # 0xac
'NtDebugActiveProcess', # 0xad
'NtDebugContinue', # 0xae
'NtDeleteAtom', # 0xaf
'NtDeleteBootEntry', # 0xb0
'NtDeleteDriverEntry', # 0xb1
'NtDeleteFile', # 0xb2
'NtDeleteKey', # 0xb3
'NtDeleteObjectAuditAlarm', # 0xb4
'NtDeletePrivateNamespace', # 0xb5
'NtDeleteValueKey', # 0xb6
'NtDisplayString', # 0xb7
'NtEnumerateBootEntries', # 0xb8
'NtEnumerateDriverEntries', # 0xb9
'NtEnumerateSystemEnvironmentValuesEx', # 0xba
'NtEnumerateTransactionObject', # 0xbb
'NtExtendSection', # 0xbc
'NtFilterToken', # 0xbd
'NtFlushInstallUILanguage', # 0xbe
'NtFlushInstructionCache', # 0xbf
'NtFlushKey', # 0xc0
'NtFlushProcessWriteBuffers', # 0xc1
'NtFlushVirtualMemory', # 0xc2
'NtFlushWriteBuffer', # 0xc3
'NtFreeUserPhysicalPages', # 0xc4
'NtFreezeRegistry', # 0xc5
'NtFreezeTransactions', # 0xc6
'NtGetContextThread', # 0xc7
'NtGetCurrentProcessorNumber', # 0xc8
'NtGetDevicePowerState', # 0xc9
'NtGetMUIRegistryInfo', # 0xca
'NtGetNextProcess', # 0xcb
'NtGetNextThread', # 0xcc
'NtGetNlsSectionPtr', # 0xcd
'NtGetNotificationResourceManager', # 0xce
'NtGetPlugPlayEvent', # 0xcf
'NtGetWriteWatch', # 0xd0
'NtImpersonateAnonymousToken', # 0xd1
'NtImpersonateThread', # 0xd2
'NtInitializeNlsFiles', # 0xd3
'NtInitializeRegistry', # 0xd4
'NtInitiatePowerAction', # 0xd5
'NtIsSystemResumeAutomatic', # 0xd6
'NtIsUILanguageComitted', # 0xd7
'NtListenPort', # 0xd8
'NtLoadDriver', # 0xd9
'NtLoadKey', # 0xda
'NtLoadKey2', # 0xdb
'NtLoadKeyEx', # 0xdc
'NtLockFile', # 0xdd
'NtLockProductActivationKeys', # 0xde
'NtLockRegistryKey', # 0xdf
'NtLockVirtualMemory', # 0xe0
'NtMakePermanentObject', # 0xe1
'NtMakeTemporaryObject', # 0xe2
'NtMapCMFModule', # 0xe3
'NtMapUserPhysicalPages', # 0xe4
'NtModifyBootEntry', # 0xe5
'NtModifyDriverEntry', # 0xe6
'NtNotifyChangeDirectoryFile', # 0xe7
'NtNotifyChangeKey', # 0xe8
'NtNotifyChangeMultipleKeys', # 0xe9
'NtOpenEnlistment', # 0xea
'NtOpenEventPair', # 0xeb
'NtOpenIoCompletion', # 0xec
'NtOpenJobObject', # 0xed
'NtOpenKeyTransacted', # 0xee
'NtOpenKeyedEvent', # 0xef
'NtOpenMutant', # 0xf0
'NtOpenObjectAuditAlarm', # 0xf1
'NtOpenPrivateNamespace', # 0xf2
'NtOpenProcessToken', # 0xf3
'NtOpenResourceManager', # 0xf4
'NtOpenSemaphore', # 0xf5
'NtOpenSession', # 0xf6
'NtOpenSymbolicLinkObject', # 0xf7
'NtOpenThread', # 0xf8
'NtOpenTimer', # 0xf9
'NtOpenTransaction', # 0xfa
'NtOpenTransactionManager', # 0xfb
'NtPlugPlayControl', # 0xfc
'NtPrePrepareComplete', # 0xfd
'NtPrePrepareEnlistment', # 0xfe
'NtPrepareComplete', # 0xff
'NtPrepareEnlistment', # 0x100
'NtPrivilegeCheck', # 0x101
'NtPrivilegeObjectAuditAlarm', # 0x102
'NtPrivilegedServiceAuditAlarm', # 0x103
'NtPropagationComplete', # 0x104
'NtPropagationFailed', # 0x105
'NtPulseEvent', # 0x106
'NtQueryBootEntryOrder', # 0x107
'NtQueryBootOptions', # 0x108
'NtQueryDebugFilterState', # 0x109
'NtQueryDirectoryObject', # 0x10a
'NtQueryDriverEntryOrder', # 0x10b
'NtQueryEaFile', # 0x10c
'NtQueryFullAttributesFile', # 0x10d
'NtQueryInformationAtom', # 0x10e
'NtQueryInformationEnlistment', # 0x10f
'NtQueryInformationJobObject', # 0x110
'NtQueryInformationPort', # 0x111
'NtQueryInformationResourceManager', # 0x112
'NtQueryInformationTransaction', # 0x113
'NtQueryInformationTransactionManager', # 0x114
'NtQueryInformationWorkerFactory', # 0x115
'NtQueryInstallUILanguage', # 0x116
'NtQueryIntervalProfile', # 0x117
'NtQueryIoCompletion', # 0x118
'NtQueryLicenseValue', # 0x119
'NtQueryMultipleValueKey', # 0x11a
'NtQueryMutant', # 0x11b
'NtQueryOpenSubKeys', # 0x11c
'NtQueryOpenSubKeysEx', # 0x11d
'NtQueryPortInformationProcess', # 0x11e
'NtQueryQuotaInformationFile', # 0x11f
'NtQuerySecurityObject', # 0x120
'NtQuerySemaphore', # 0x121
'NtQuerySymbolicLinkObject', # 0x122
'NtQuerySystemEnvironmentValue', # 0x123
'NtQuerySystemEnvironmentValueEx', # 0x124
'NtQueryTimerResolution', # 0x125
'NtRaiseException', # 0x126
'NtRaiseHardError', # 0x127
'NtReadOnlyEnlistment', # 0x128
'NtRecoverEnlistment', # 0x129
'NtRecoverResourceManager', # 0x12a
'NtRecoverTransactionManager', # 0x12b
'NtRegisterProtocolAddressInformation', # 0x12c
'NtRegisterThreadTerminatePort', # 0x12d
'NtReleaseCMFViewOwnership', # 0x12e
'NtReleaseKeyedEvent', # 0x12f
'NtReleaseWorkerFactoryWorker', # 0x130
'NtRemoveIoCompletionEx', # 0x131
'NtRemoveProcessDebug', # 0x132
'NtRenameKey', # 0x133
'NtRenameTransactionManager', # 0x134
'NtReplaceKey', # 0x135
'NtReplacePartitionUnit', # 0x136
'NtReplyWaitReplyPort', # 0x137
'NtRequestDeviceWakeup', # 0x138
'NtRequestPort', # 0x139
'NtRequestWakeupLatency', # 0x13a
'NtResetEvent', # 0x13b
'NtResetWriteWatch', # 0x13c
'NtRestoreKey', # 0x13d
'NtResumeProcess', # 0x13e
'NtRollbackComplete', # 0x13f
'NtRollbackEnlistment', # 0x140
'NtRollbackTransaction', # 0x141
'NtRollforwardTransactionManager', # 0x142
'NtSaveKey', # 0x143
'NtSaveKeyEx', # 0x144
'NtSaveMergedKeys', # 0x145
'NtSecureConnectPort', # 0x146
'NtSetBootEntryOrder', # 0x147
'NtSetBootOptions', # 0x148
'NtSetContextThread', # 0x149
'NtSetDebugFilterState', # 0x14a
'NtSetDefaultHardErrorPort', # 0x14b
'NtSetDefaultLocale', # 0x14c
'NtSetDefaultUILanguage', # 0x14d
'NtSetDriverEntryOrder', # 0x14e
'NtSetEaFile', # 0x14f
'NtSetHighEventPair', # 0x150
'NtSetHighWaitLowEventPair', # 0x151
'NtSetInformationDebugObject', # 0x152
'NtSetInformationEnlistment', # 0x153
'NtSetInformationJobObject', # 0x154
'NtSetInformationKey', # 0x155
'NtSetInformationResourceManager', # 0x156
'NtSetInformationToken', # 0x157
'NtSetInformationTransaction', # 0x158
'NtSetInformationTransactionManager', # 0x159
'NtSetInformationWorkerFactory', # 0x15a
'NtSetIntervalProfile', # 0x15b
'NtSetIoCompletion', # 0x15c
'NtSetLdtEntries', # 0x15d
'NtSetLowEventPair', # 0x15e
'NtSetLowWaitHighEventPair', # 0x15f
'NtSetQuotaInformationFile', # 0x160
'NtSetSecurityObject', # 0x161
'NtSetSystemEnvironmentValue', # 0x162
'NtSetSystemEnvironmentValueEx', # 0x163
'NtSetSystemInformation', # 0x164
'NtSetSystemPowerState', # 0x165
'NtSetSystemTime', # 0x166
'NtSetThreadExecutionState', # 0x167
'NtSetTimerResolution', # 0x168
'NtSetUuidSeed', # 0x169
'NtSetVolumeInformationFile', # 0x16a
'NtShutdownSystem', # 0x16b
'NtShutdownWorkerFactory', # 0x16c
'NtSignalAndWaitForSingleObject', # 0x16d
'NtSinglePhaseReject', # 0x16e
'NtStartProfile', # 0x16f
'NtStopProfile', # 0x170
'NtSuspendProcess', # 0x171
'NtSuspendThread', # 0x172
'NtSystemDebugControl', # 0x173
'NtTerminateJobObject', # 0x174
'NtTestAlert', # 0x175
'NtThawRegistry', # 0x176
'NtThawTransactions', # 0x177
'NtTraceControl', # 0x178
'NtTranslateFilePath', # 0x179
'NtUnloadDriver', # 0x17a
'NtUnloadKey', # 0x17b
'NtUnloadKey2', # 0x17c
'NtUnloadKeyEx', # 0x17d
'NtUnlockFile', # 0x17e
'NtUnlockVirtualMemory', # 0x17f
'NtVdmControl', # 0x180
'NtWaitForDebugEvent', # 0x181
'NtWaitForKeyedEvent', # 0x182
'NtWaitForWorkViaWorkerFactory', # 0x183
'NtWaitHighEventPair', # 0x184
'NtWaitLowEventPair', # 0x185
'NtWorkerFactoryWorkerReady', # 0x186
],
[
'NtUserGetThreadState', # 0x0
'NtUserPeekMessage', # 0x1
'NtUserCallOneParam', # 0x2
'NtUserGetKeyState', # 0x3
'NtUserInvalidateRect', # 0x4
'NtUserCallNoParam', # 0x5
'NtUserGetMessage', # 0x6
'NtUserMessageCall', # 0x7
'NtGdiBitBlt', # 0x8
'NtGdiGetCharSet', # 0x9
'NtUserGetDC', # 0xa
'NtGdiSelectBitmap', # 0xb
'NtUserWaitMessage', # 0xc
'NtUserTranslateMessage', # 0xd
'NtUserGetProp', # 0xe
'NtUserPostMessage', # 0xf
'NtUserQueryWindow', # 0x10
'NtUserTranslateAccelerator', # 0x11
'NtGdiFlush', # 0x12
'NtUserRedrawWindow', # 0x13
'NtUserWindowFromPoint', # 0x14
'NtUserCallMsgFilter', # 0x15
'NtUserValidateTimerCallback', # 0x16
'NtUserBeginPaint', # 0x17
'NtUserSetTimer', # 0x18
'NtUserEndPaint', # 0x19
'NtUserSetCursor', # 0x1a
'NtUserKillTimer', # 0x1b
'NtUserBuildHwndList', # 0x1c
'NtUserSelectPalette', # 0x1d
'NtUserCallNextHookEx', # 0x1e
'NtUserHideCaret', # 0x1f
'NtGdiIntersectClipRect', # 0x20
'NtUserCallHwndLock', # 0x21
'NtUserGetProcessWindowStation', # 0x22
'NtGdiDeleteObjectApp', # 0x23
'NtUserSetWindowPos', # 0x24
'NtUserShowCaret', # 0x25
'NtUserEndDeferWindowPosEx', # 0x26
'NtUserCallHwndParamLock', # 0x27
'NtUserVkKeyScanEx', # 0x28
'NtGdiSetDIBitsToDeviceInternal', # 0x29
'NtUserCallTwoParam', # 0x2a
'NtGdiGetRandomRgn', # 0x2b
'NtUserCopyAcceleratorTable', # 0x2c
'NtUserNotifyWinEvent', # 0x2d
'NtGdiExtSelectClipRgn', # 0x2e
'NtUserIsClipboardFormatAvailable', # 0x2f
'NtUserSetScrollInfo', # 0x30
'NtGdiStretchBlt', # 0x31
'NtUserCreateCaret', # 0x32
'NtGdiRectVisible', # 0x33
'NtGdiCombineRgn', # 0x34
'NtGdiGetDCObject', # 0x35
'NtUserDispatchMessage', # 0x36
'NtUserRegisterWindowMessage', # 0x37
'NtGdiExtTextOutW', # 0x38
'NtGdiSelectFont', # 0x39
'NtGdiRestoreDC', # 0x3a
'NtGdiSaveDC', # 0x3b
'NtUserGetForegroundWindow', # 0x3c
'NtUserShowScrollBar', # 0x3d
'NtUserFindExistingCursorIcon', # 0x3e
'NtGdiGetDCDword', # 0x3f
'NtGdiGetRegionData', # 0x40
'NtGdiLineTo', # 0x41
'NtUserSystemParametersInfo', # 0x42
'NtGdiGetAppClipBox', # 0x43
'NtUserGetAsyncKeyState', # 0x44
'NtUserGetCPD', # 0x45
'NtUserRemoveProp', # 0x46
'NtGdiDoPalette', # 0x47
'NtGdiPolyPolyDraw', # 0x48
'NtUserSetCapture', # 0x49
'NtUserEnumDisplayMonitors', # 0x4a
'NtGdiCreateCompatibleBitmap', # 0x4b
'NtUserSetProp', # 0x4c
'NtGdiGetTextCharsetInfo', # 0x4d
'NtUserSBGetParms', # 0x4e
'NtUserGetIconInfo', # 0x4f
'NtUserExcludeUpdateRgn', # 0x50
'NtUserSetFocus', # 0x51
'NtGdiExtGetObjectW', # 0x52
'NtUserDeferWindowPos', # 0x53
'NtUserGetUpdateRect', # 0x54
'NtGdiCreateCompatibleDC', # 0x55
'NtUserGetClipboardSequenceNumber', # 0x56
'NtGdiCreatePen', # 0x57
'NtUserShowWindow', # 0x58
'NtUserGetKeyboardLayoutList', # 0x59
'NtGdiPatBlt', # 0x5a
'NtUserMapVirtualKeyEx', # 0x5b
'NtUserSetWindowLong', # 0x5c
'NtGdiHfontCreate', # 0x5d
'NtUserMoveWindow', # 0x5e
'NtUserPostThreadMessage', # 0x5f
'NtUserDrawIconEx', # 0x60
'NtUserGetSystemMenu', # 0x61
'NtGdiDrawStream', # 0x62
'NtUserInternalGetWindowText', # 0x63
'NtUserGetWindowDC', # 0x64
'NtGdiD3dDrawPrimitives2', # 0x65
'NtGdiInvertRgn', # 0x66
'NtGdiGetRgnBox', # 0x67
'NtGdiGetAndSetDCDword', # 0x68
'NtGdiMaskBlt', # 0x69
'NtGdiGetWidthTable', # 0x6a
'NtUserScrollDC', # 0x6b
'NtUserGetObjectInformation', # 0x6c
'NtGdiCreateBitmap', # 0x6d
'NtGdiConsoleTextOut', # 0x6e
'NtUserFindWindowEx', # 0x6f
'NtGdiPolyPatBlt', # 0x70
'NtUserUnhookWindowsHookEx', # 0x71
'NtGdiGetNearestColor', # 0x72
'NtGdiTransformPoints', # 0x73
'NtGdiGetDCPoint', # 0x74
'NtUserCheckImeHotKey', # 0x75
'NtGdiCreateDIBBrush', # 0x76
'NtGdiGetTextMetricsW', # 0x77
'NtUserCreateWindowEx', # 0x78
'NtUserSetParent', # 0x79
'NtUserGetKeyboardState', # 0x7a
'NtUserToUnicodeEx', # 0x7b
'NtUserGetControlBrush', # 0x7c
'NtUserGetClassName', # 0x7d
'NtGdiAlphaBlend', # 0x7e
'NtGdiDdBlt', # 0x7f
'NtGdiOffsetRgn', # 0x80
'NtUserDefSetText', # 0x81
'NtGdiGetTextFaceW', # 0x82
'NtGdiStretchDIBitsInternal', # 0x83
'NtUserSendInput', # 0x84
'NtUserGetThreadDesktop', # 0x85
'NtGdiCreateRectRgn', # 0x86
'NtGdiGetDIBitsInternal', # 0x87
'NtUserGetUpdateRgn', # 0x88
'NtGdiDeleteClientObj', # 0x89
'NtUserGetIconSize', # 0x8a
'NtUserFillWindow', # 0x8b
'NtGdiExtCreateRegion', # 0x8c
'NtGdiComputeXformCoefficients', # 0x8d
'NtUserSetWindowsHookEx', # 0x8e
'NtUserNotifyProcessCreate', # 0x8f
'NtGdiUnrealizeObject', # 0x90
'NtUserGetTitleBarInfo', # 0x91
'NtGdiRectangle', # 0x92
'NtUserSetThreadDesktop', # 0x93
'NtUserGetDCEx', # 0x94
'NtUserGetScrollBarInfo', # 0x95
'NtGdiGetTextExtent', # 0x96
'NtUserSetWindowFNID', # 0x97
'NtGdiSetLayout', # 0x98
'NtUserCalcMenuBar', # 0x99
'NtUserThunkedMenuItemInfo', # 0x9a
'NtGdiExcludeClipRect', # 0x9b
'NtGdiCreateDIBSection', # 0x9c
'NtGdiGetDCforBitmap', # 0x9d
'NtUserDestroyCursor', # 0x9e
'NtUserDestroyWindow', # 0x9f
'NtUserCallHwndParam', # 0xa0
'NtGdiCreateDIBitmapInternal', # 0xa1
'NtUserOpenWindowStation', # 0xa2
'NtGdiDdDeleteSurfaceObject', # 0xa3
'NtGdiEnumFontClose', # 0xa4
'NtGdiEnumFontOpen', # 0xa5
'NtGdiEnumFontChunk', # 0xa6
'NtGdiDdCanCreateSurface', # 0xa7
'NtGdiDdCreateSurface', # 0xa8
'NtUserSetCursorIconData', # 0xa9
'NtGdiDdDestroySurface', # 0xaa
'NtUserCloseDesktop', # 0xab
'NtUserOpenDesktop', # 0xac
'NtUserSetProcessWindowStation', # 0xad
'NtUserGetAtomName', # 0xae
'NtGdiDdResetVisrgn', # 0xaf
'NtGdiExtCreatePen', # 0xb0
'NtGdiCreatePaletteInternal', # 0xb1
'NtGdiSetBrushOrg', # 0xb2
'NtUserBuildNameList', # 0xb3
'NtGdiSetPixel', # 0xb4
'NtUserRegisterClassExWOW', # 0xb5
'NtGdiCreatePatternBrushInternal', # 0xb6
'NtUserGetAncestor', # 0xb7
'NtGdiGetOutlineTextMetricsInternalW', # 0xb8
'NtGdiSetBitmapBits', # 0xb9
'NtUserCloseWindowStation', # 0xba
'NtUserGetDoubleClickTime', # 0xbb
'NtUserEnableScrollBar', # 0xbc
'NtGdiCreateSolidBrush', # 0xbd
'NtUserGetClassInfoEx', # 0xbe
'NtGdiCreateClientObj', # 0xbf
'NtUserUnregisterClass', # 0xc0
'NtUserDeleteMenu', # 0xc1
'NtGdiRectInRegion', # 0xc2
'NtUserScrollWindowEx', # 0xc3
'NtGdiGetPixel', # 0xc4
'NtUserSetClassLong', # 0xc5
'NtUserGetMenuBarInfo', # 0xc6
'NtGdiDdCreateSurfaceEx', # 0xc7
'NtGdiDdCreateSurfaceObject', # 0xc8
'NtGdiGetNearestPaletteIndex', # 0xc9
'NtGdiDdLockD3D', # 0xca
'NtGdiDdUnlockD3D', # 0xcb
'NtGdiGetCharWidthW', # 0xcc
'NtUserInvalidateRgn', # 0xcd
'NtUserGetClipboardOwner', # 0xce
'NtUserSetWindowRgn', # 0xcf
'NtUserBitBltSysBmp', # 0xd0
'NtGdiGetCharWidthInfo', # 0xd1
'NtUserValidateRect', # 0xd2
'NtUserCloseClipboard', # 0xd3
'NtUserOpenClipboard', # 0xd4
'NtGdiGetStockObject', # 0xd5
'NtUserSetClipboardData', # 0xd6
'NtUserEnableMenuItem', # 0xd7
'NtUserAlterWindowStyle', # 0xd8
'NtGdiFillRgn', # 0xd9
'NtUserGetWindowPlacement', # 0xda
'NtGdiModifyWorldTransform', # 0xdb
'NtGdiGetFontData', # 0xdc
'NtUserGetOpenClipboardWindow', # 0xdd
'NtUserSetThreadState', # 0xde
'NtGdiOpenDCW', # 0xdf
'NtUserTrackMouseEvent', # 0xe0
'NtGdiGetTransform', # 0xe1
'NtUserDestroyMenu', # 0xe2
'NtGdiGetBitmapBits', # 0xe3
'NtUserConsoleControl', # 0xe4
'NtUserSetActiveWindow', # 0xe5
'NtUserSetInformationThread', # 0xe6
'NtUserSetWindowPlacement', # 0xe7
'NtUserGetControlColor', # 0xe8
'NtGdiSetMetaRgn', # 0xe9
'NtGdiSetMiterLimit', # 0xea
'NtGdiSetVirtualResolution', # 0xeb
'NtGdiGetRasterizerCaps', # 0xec
'NtUserSetWindowWord', # 0xed
'NtUserGetClipboardFormatName', # 0xee
'NtUserRealInternalGetMessage', # 0xef
'NtUserCreateLocalMemHandle', # 0xf0
'NtUserAttachThreadInput', # 0xf1
'NtGdiCreateHalftonePalette', # 0xf2
'NtUserPaintMenuBar', # 0xf3
'NtUserSetKeyboardState', # 0xf4
'NtGdiCombineTransform', # 0xf5
'NtUserCreateAcceleratorTable', # 0xf6
'NtUserGetCursorFrameInfo', # 0xf7
'NtUserGetAltTabInfo', # 0xf8
'NtUserGetCaretBlinkTime', # 0xf9
'NtGdiQueryFontAssocInfo', # 0xfa
'NtUserProcessConnect', # 0xfb
'NtUserEnumDisplayDevices', # 0xfc
'NtUserEmptyClipboard', # 0xfd
'NtUserGetClipboardData', # 0xfe
'NtUserRemoveMenu', # 0xff
'NtGdiSetBoundsRect', # 0x100
'NtUserSetInformationProcess', # 0x101
'NtGdiGetBitmapDimension', # 0x102
'NtUserConvertMemHandle', # 0x103
'NtUserDestroyAcceleratorTable', # 0x104
'NtUserGetGUIThreadInfo', # 0x105
'NtGdiCloseFigure', # 0x106
'NtUserSetWindowsHookAW', # 0x107
'NtUserSetMenuDefaultItem', # 0x108
'NtUserCheckMenuItem', # 0x109
'NtUserSetWinEventHook', # 0x10a
'NtUserUnhookWinEvent', # 0x10b
'NtGdiSetupPublicCFONT', # 0x10c
'NtUserLockWindowUpdate', # 0x10d
'NtUserSetSystemMenu', # 0x10e
'NtUserThunkedMenuInfo', # 0x10f
'NtGdiBeginPath', # 0x110
'NtGdiEndPath', # 0x111
'NtGdiFillPath', # 0x112
'NtUserCallHwnd', # 0x113
'NtUserDdeInitialize', # 0x114
'NtUserModifyUserStartupInfoFlags', # 0x115
'NtUserCountClipboardFormats', # 0x116
'NtGdiAddFontMemResourceEx', # 0x117
'NtGdiEqualRgn', # 0x118
'NtGdiGetSystemPaletteUse', # 0x119
'NtGdiRemoveFontMemResourceEx', # 0x11a
'NtUserEnumDisplaySettings', # 0x11b
'NtUserPaintDesktop', # 0x11c
'NtGdiExtEscape', # 0x11d
'NtGdiSetBitmapDimension', # 0x11e
'NtGdiSetFontEnumeration', # 0x11f
'NtUserChangeClipboardChain', # 0x120
'NtUserResolveDesktop', # 0x121
'NtUserSetClipboardViewer', # 0x122
'NtUserShowWindowAsync', # 0x123
'NtUserSetConsoleReserveKeys', # 0x124
'NtGdiCreateColorSpace', # 0x125
'NtGdiDeleteColorSpace', # 0x126
'NtUserActivateKeyboardLayout', # 0x127
'NtGdiAbortDoc', # 0x128
'NtGdiAbortPath', # 0x129
'NtGdiAddEmbFontToDC', # 0x12a
'NtGdiAddFontResourceW', # 0x12b
'NtGdiAddRemoteFontToDC', # 0x12c
'NtGdiAddRemoteMMInstanceToDC', # 0x12d
'NtGdiAngleArc', # 0x12e
'NtGdiAnyLinkedFonts', # 0x12f
'NtGdiArcInternal', # 0x130
'NtGdiBRUSHOBJ_DeleteRbrush', # 0x131
'NtGdiBRUSHOBJ_hGetColorTransform', # 0x132
'NtGdiBRUSHOBJ_pvAllocRbrush', # 0x133
'NtGdiBRUSHOBJ_pvGetRbrush', # 0x134
'NtGdiBRUSHOBJ_ulGetBrushColor', # 0x135
'NtGdiCLIPOBJ_bEnum', # 0x136
'NtGdiCLIPOBJ_cEnumStart', # 0x137
'NtGdiCLIPOBJ_ppoGetPath', # 0x138
'NtGdiCancelDC', # 0x139
'NtGdiChangeGhostFont', # 0x13a
'NtGdiCheckBitmapBits', # 0x13b
'NtGdiClearBitmapAttributes', # 0x13c
'NtGdiClearBrushAttributes', # 0x13d
'NtGdiColorCorrectPalette', # 0x13e
'NtGdiConfigureOPMProtectedOutput', # 0x13f
'NtGdiConvertMetafileRect', # 0x140
'NtGdiCreateColorTransform', # 0x141
'NtGdiCreateEllipticRgn', # 0x142
'NtGdiCreateHatchBrushInternal', # 0x143
'NtGdiCreateMetafileDC', # 0x144
'NtGdiCreateOPMProtectedOutputs', # 0x145
'NtGdiCreateRoundRectRgn', # 0x146
'NtGdiCreateServerMetaFile', # 0x147
'NtGdiD3dContextCreate', # 0x148
'NtGdiD3dContextDestroy', # 0x149
'NtGdiD3dContextDestroyAll', # 0x14a
'NtGdiD3dValidateTextureStageState', # 0x14b
'NtGdiDDCCIGetCapabilitiesString', # 0x14c
'NtGdiDDCCIGetCapabilitiesStringLength', # 0x14d
'NtGdiDDCCIGetTimingReport', # 0x14e
'NtGdiDDCCIGetVCPFeature', # 0x14f
'NtGdiDDCCISaveCurrentSettings', # 0x150
'NtGdiDDCCISetVCPFeature', # 0x151
'NtGdiDdAddAttachedSurface', # 0x152
'NtGdiDdAlphaBlt', # 0x153
'NtGdiDdAttachSurface', # 0x154
'NtGdiDdBeginMoCompFrame', # 0x155
'NtGdiDdCanCreateD3DBuffer', # 0x156
'NtGdiDdColorControl', # 0x157
'NtGdiDdCreateD3DBuffer', # 0x158
'NtGdiDdCreateDirectDrawObject', # 0x159
'NtGdiDdCreateMoComp', # 0x15a
'NtGdiDdDDICheckExclusiveOwnership', # 0x15b
'NtGdiDdDDICheckMonitorPowerState', # 0x15c
'NtGdiDdDDICheckOcclusion', # 0x15d
'NtGdiDdDDICloseAdapter', # 0x15e
'NtGdiDdDDICreateAllocation', # 0x15f
'NtGdiDdDDICreateContext', # 0x160
'NtGdiDdDDICreateDCFromMemory', # 0x161
'NtGdiDdDDICreateDevice', # 0x162
'NtGdiDdDDICreateOverlay', # 0x163
'NtGdiDdDDICreateSynchronizationObject', # 0x164
'NtGdiDdDDIDestroyAllocation', # 0x165
'NtGdiDdDDIDestroyContext', # 0x166
'NtGdiDdDDIDestroyDCFromMemory', # 0x167
'NtGdiDdDDIDestroyDevice', # 0x168
'NtGdiDdDDIDestroyOverlay', # 0x169
'NtGdiDdDDIDestroySynchronizationObject', # 0x16a
'NtGdiDdDDIEscape', # 0x16b
'NtGdiDdDDIFlipOverlay', # 0x16c
'NtGdiDdDDIGetContextSchedulingPriority', # 0x16d
'NtGdiDdDDIGetDeviceState', # 0x16e
'NtGdiDdDDIGetDisplayModeList', # 0x16f
'NtGdiDdDDIGetMultisampleMethodList', # 0x170
'NtGdiDdDDIGetPresentHistory', # 0x171
'NtGdiDdDDIGetProcessSchedulingPriorityClass', # 0x172
'NtGdiDdDDIGetRuntimeData', # 0x173
'NtGdiDdDDIGetScanLine', # 0x174
'NtGdiDdDDIGetSharedPrimaryHandle', # 0x175
'NtGdiDdDDIInvalidateActiveVidPn', # 0x176
'NtGdiDdDDILock', # 0x177
'NtGdiDdDDIOpenAdapterFromDeviceName', # 0x178
'NtGdiDdDDIOpenAdapterFromHdc', # 0x179
'NtGdiDdDDIOpenResource', # 0x17a
'NtGdiDdDDIPollDisplayChildren', # 0x17b
'NtGdiDdDDIPresent', # 0x17c
'NtGdiDdDDIQueryAdapterInfo', # 0x17d
'NtGdiDdDDIQueryAllocationResidency', # 0x17e
'NtGdiDdDDIQueryResourceInfo', # 0x17f
'NtGdiDdDDIQueryStatistics', # 0x180
'NtGdiDdDDIReleaseProcessVidPnSourceOwners', # 0x181
'NtGdiDdDDIRender', # 0x182
'NtGdiDdDDISetAllocationPriority', # 0x183
'NtGdiDdDDISetContextSchedulingPriority', # 0x184
'NtGdiDdDDISetDisplayMode', # 0x185
'NtGdiDdDDISetDisplayPrivateDriverFormat', # 0x186
'NtGdiDdDDISetGammaRamp', # 0x187
'NtGdiDdDDISetProcessSchedulingPriorityClass', # 0x188
'NtGdiDdDDISetQueuedLimit', # 0x189
'NtGdiDdDDISetVidPnSourceOwner', # 0x18a
'NtGdiDdDDISharedPrimaryLockNotification', # 0x18b
'NtGdiDdDDISharedPrimaryUnLockNotification', # 0x18c
'NtGdiDdDDISignalSynchronizationObject', # 0x18d
'NtGdiDdDDIUnlock', # 0x18e
'NtGdiDdDDIUpdateOverlay', # 0x18f
'NtGdiDdDDIWaitForIdle', # 0x190
'NtGdiDdDDIWaitForSynchronizationObject', # 0x191
'NtGdiDdDDIWaitForVerticalBlankEvent', # 0x192
'NtGdiDdDeleteDirectDrawObject', # 0x193
'NtGdiDdDestroyD3DBuffer', # 0x194
'NtGdiDdDestroyMoComp', # 0x195
'NtGdiDdEndMoCompFrame', # 0x196
'NtGdiDdFlip', # 0x197
'NtGdiDdFlipToGDISurface', # 0x198
'NtGdiDdGetAvailDriverMemory', # 0x199
'NtGdiDdGetBltStatus', # 0x19a
'NtGdiDdGetDC', # 0x19b
'NtGdiDdGetDriverInfo', # 0x19c
'NtGdiDdGetDriverState', # 0x19d
'NtGdiDdGetDxHandle', # 0x19e
'NtGdiDdGetFlipStatus', # 0x19f
'NtGdiDdGetInternalMoCompInfo', # 0x1a0
'NtGdiDdGetMoCompBuffInfo', # 0x1a1
'NtGdiDdGetMoCompFormats', # 0x1a2
'NtGdiDdGetMoCompGuids', # 0x1a3
'NtGdiDdGetScanLine', # 0x1a4
'NtGdiDdLock', # 0x1a5
'NtGdiDdQueryDirectDrawObject', # 0x1a6
'NtGdiDdQueryMoCompStatus', # 0x1a7
'NtGdiDdReenableDirectDrawObject', # 0x1a8
'NtGdiDdReleaseDC', # 0x1a9
'NtGdiDdRenderMoComp', # 0x1aa
'NtGdiDdSetColorKey', # 0x1ab
'NtGdiDdSetExclusiveMode', # 0x1ac
'NtGdiDdSetGammaRamp', # 0x1ad
'NtGdiDdSetOverlayPosition', # 0x1ae
'NtGdiDdUnattachSurface', # 0x1af
'NtGdiDdUnlock', # 0x1b0
'NtGdiDdUpdateOverlay', # 0x1b1
'NtGdiDdWaitForVerticalBlank', # 0x1b2
'NtGdiDeleteColorTransform', # 0x1b3
'NtGdiDescribePixelFormat', # 0x1b4
'NtGdiDestroyOPMProtectedOutput', # 0x1b5
'NtGdiDestroyPhysicalMonitor', # 0x1b6
'NtGdiDoBanding', # 0x1b7
'NtGdiDrawEscape', # 0x1b8
'NtGdiDvpAcquireNotification', # 0x1b9
'NtGdiDvpCanCreateVideoPort', # 0x1ba
'NtGdiDvpColorControl', # 0x1bb
'NtGdiDvpCreateVideoPort', # 0x1bc
'NtGdiDvpDestroyVideoPort', # 0x1bd
'NtGdiDvpFlipVideoPort', # 0x1be
'NtGdiDvpGetVideoPortBandwidth', # 0x1bf
'NtGdiDvpGetVideoPortConnectInfo', # 0x1c0
'NtGdiDvpGetVideoPortField', # 0x1c1
'NtGdiDvpGetVideoPortFlipStatus', # 0x1c2
'NtGdiDvpGetVideoPortInputFormats', # 0x1c3
'NtGdiDvpGetVideoPortLine', # 0x1c4
'NtGdiDvpGetVideoPortOutputFormats', # 0x1c5
'NtGdiDvpGetVideoSignalStatus', # 0x1c6
'NtGdiDvpReleaseNotification', # 0x1c7
'NtGdiDvpUpdateVideoPort', # 0x1c8
'NtGdiDvpWaitForVideoPortSync', # 0x1c9
'NtGdiDwmGetDirtyRgn', # 0x1ca
'NtGdiDwmGetSurfaceData', # 0x1cb
'NtGdiDxgGenericThunk', # 0x1cc
'NtGdiEllipse', # 0x1cd
'NtGdiEnableEudc', # 0x1ce
'NtGdiEndDoc', # 0x1cf
'NtGdiEndPage', # 0x1d0
'NtGdiEngAlphaBlend', # 0x1d1
'NtGdiEngAssociateSurface', # 0x1d2
'NtGdiEngBitBlt', # 0x1d3
'NtGdiEngCheckAbort', # 0x1d4
'NtGdiEngComputeGlyphSet', # 0x1d5
'NtGdiEngCopyBits', # 0x1d6
'NtGdiEngCreateBitmap', # 0x1d7
'NtGdiEngCreateClip', # 0x1d8
'NtGdiEngCreateDeviceBitmap', # 0x1d9
'NtGdiEngCreateDeviceSurface', # 0x1da
'NtGdiEngCreatePalette', # 0x1db
'NtGdiEngDeleteClip', # 0x1dc
'NtGdiEngDeletePalette', # 0x1dd
'NtGdiEngDeletePath', # 0x1de
'NtGdiEngDeleteSurface', # 0x1df
'NtGdiEngEraseSurface', # 0x1e0
'NtGdiEngFillPath', # 0x1e1
'NtGdiEngGradientFill', # 0x1e2
'NtGdiEngLineTo', # 0x1e3
'NtGdiEngLockSurface', # 0x1e4
'NtGdiEngMarkBandingSurface', # 0x1e5
'NtGdiEngPaint', # 0x1e6
'NtGdiEngPlgBlt', # 0x1e7
'NtGdiEngStretchBlt', # 0x1e8
'NtGdiEngStretchBltROP', # 0x1e9
'NtGdiEngStrokeAndFillPath', # 0x1ea
'NtGdiEngStrokePath', # 0x1eb
'NtGdiEngTextOut', # 0x1ec
'NtGdiEngTransparentBlt', # 0x1ed
'NtGdiEngUnlockSurface', # 0x1ee
'NtGdiEnumObjects', # 0x1ef
'NtGdiEudcLoadUnloadLink', # 0x1f0
'NtGdiExtFloodFill', # 0x1f1
'NtGdiFONTOBJ_cGetAllGlyphHandles', # 0x1f2
'NtGdiFONTOBJ_cGetGlyphs', # 0x1f3
'NtGdiFONTOBJ_pQueryGlyphAttrs', # 0x1f4
'NtGdiFONTOBJ_pfdg', # 0x1f5
'NtGdiFONTOBJ_pifi', # 0x1f6
'NtGdiFONTOBJ_pvTrueTypeFontFile', # 0x1f7
'NtGdiFONTOBJ_pxoGetXform', # 0x1f8
'NtGdiFONTOBJ_vGetInfo', # 0x1f9
'NtGdiFlattenPath', # 0x1fa
'NtGdiFontIsLinked', # 0x1fb
'NtGdiForceUFIMapping', # 0x1fc
'NtGdiFrameRgn', # 0x1fd
'NtGdiFullscreenControl', # 0x1fe
'NtGdiGetBoundsRect', # 0x1ff
'NtGdiGetCOPPCompatibleOPMInformation', # 0x200
'NtGdiGetCertificate', # 0x201
'NtGdiGetCertificateSize', # 0x202
'NtGdiGetCharABCWidthsW', # 0x203
'NtGdiGetCharacterPlacementW', # 0x204
'NtGdiGetColorAdjustment', # 0x205
'NtGdiGetColorSpaceforBitmap', # 0x206
'NtGdiGetDeviceCaps', # 0x207
'NtGdiGetDeviceCapsAll', # 0x208
'NtGdiGetDeviceGammaRamp', # 0x209
'NtGdiGetDeviceWidth', # 0x20a
'NtGdiGetDhpdev', # 0x20b
'NtGdiGetETM', # 0x20c
'NtGdiGetEmbUFI', # 0x20d
'NtGdiGetEmbedFonts', # 0x20e
'NtGdiGetEudcTimeStampEx', # 0x20f
'NtGdiGetFontResourceInfoInternalW', # 0x210
'NtGdiGetFontUnicodeRanges', # 0x211
'NtGdiGetGlyphIndicesW', # 0x212
'NtGdiGetGlyphIndicesWInternal', # 0x213
'NtGdiGetGlyphOutline', # 0x214
'NtGdiGetKerningPairs', # 0x215
'NtGdiGetLinkedUFIs', # 0x216
'NtGdiGetMiterLimit', # 0x217
'NtGdiGetMonitorID', # 0x218
'NtGdiGetNumberOfPhysicalMonitors', # 0x219
'NtGdiGetOPMInformation', # 0x21a
'NtGdiGetOPMRandomNumber', # 0x21b
'NtGdiGetObjectBitmapHandle', # 0x21c
'NtGdiGetPath', # 0x21d
'NtGdiGetPerBandInfo', # 0x21e
'NtGdiGetPhysicalMonitorDescription', # 0x21f
'NtGdiGetPhysicalMonitors', # 0x220
'NtGdiGetRealizationInfo', # 0x221
'NtGdiGetServerMetaFileBits', # 0x222
'NtGdiGetSpoolMessage', # 0x223
'NtGdiGetStats', # 0x224
'NtGdiGetStringBitmapW', # 0x225
'NtGdiGetSuggestedOPMProtectedOutputArraySize', # 0x226
'NtGdiGetTextExtentExW', # 0x227
'NtGdiGetUFI', # 0x228
'NtGdiGetUFIPathname', # 0x229
'NtGdiGradientFill', # 0x22a
'NtGdiHT_Get8BPPFormatPalette', # 0x22b
'NtGdiHT_Get8BPPMaskPalette', # 0x22c
'NtGdiIcmBrushInfo', # 0x22d
'NtGdiInit', # 0x22e
'NtGdiInitSpool', # 0x22f
'NtGdiMakeFontDir', # 0x230
'NtGdiMakeInfoDC', # 0x231
'NtGdiMakeObjectUnXferable', # 0x232
'NtGdiMakeObjectXferable', # 0x233
'NtGdiMirrorWindowOrg', # 0x234
'NtGdiMonoBitmap', # 0x235
'NtGdiMoveTo', # 0x236
'NtGdiOffsetClipRgn', # 0x237
'NtGdiPATHOBJ_bEnum', # 0x238
'NtGdiPATHOBJ_bEnumClipLines', # 0x239
'NtGdiPATHOBJ_vEnumStart', # 0x23a
'NtGdiPATHOBJ_vEnumStartClipLines', # 0x23b
'NtGdiPATHOBJ_vGetBounds', # 0x23c
'NtGdiPathToRegion', # 0x23d
'NtGdiPlgBlt', # 0x23e
'NtGdiPolyDraw', # 0x23f
'NtGdiPolyTextOutW', # 0x240
'NtGdiPtInRegion', # 0x241
'NtGdiPtVisible', # 0x242
'NtGdiQueryFonts', # 0x243
'NtGdiRemoveFontResourceW', # 0x244
'NtGdiRemoveMergeFont', # 0x245
'NtGdiResetDC', # 0x246
'NtGdiResizePalette', # 0x247
'NtGdiRoundRect', # 0x248
'NtGdiSTROBJ_bEnum', # 0x249
'NtGdiSTROBJ_bEnumPositionsOnly', # 0x24a
'NtGdiSTROBJ_bGetAdvanceWidths', # 0x24b
'NtGdiSTROBJ_dwGetCodePage', # 0x24c
'NtGdiSTROBJ_vEnumStart', # 0x24d
'NtGdiScaleViewportExtEx', # 0x24e
'NtGdiScaleWindowExtEx', # 0x24f
'NtGdiSelectBrush', # 0x250
'NtGdiSelectClipPath', # 0x251
'NtGdiSelectPen', # 0x252
'NtGdiSetBitmapAttributes', # 0x253
'NtGdiSetBrushAttributes', # 0x254
'NtGdiSetColorAdjustment', # 0x255
'NtGdiSetColorSpace', # 0x256
'NtGdiSetDeviceGammaRamp', # 0x257
'NtGdiSetFontXform', # 0x258
'NtGdiSetIcmMode', # 0x259
'NtGdiSetLinkedUFIs', # 0x25a
'NtGdiSetMagicColors', # 0x25b
'NtGdiSetOPMSigningKeyAndSequenceNumbers', # 0x25c
'NtGdiSetPUMPDOBJ', # 0x25d
'NtGdiSetPixelFormat', # 0x25e
'NtGdiSetRectRgn', # 0x25f
'NtGdiSetSizeDevice', # 0x260
'NtGdiSetSystemPaletteUse', # 0x261
'NtGdiSetTextJustification', # 0x262
'NtGdiStartDoc', # 0x263
'NtGdiStartPage', # 0x264
'NtGdiStrokeAndFillPath', # 0x265
'NtGdiStrokePath', # 0x266
'NtGdiSwapBuffers', # 0x267
'NtGdiTransparentBlt', # 0x268
'NtGdiUMPDEngFreeUserMem', # 0x269
'NtGdiUnloadPrinterDriver', # 0x26a
'NtGdiUnmapMemFont', # 0x26b
'NtGdiUpdateColors', # 0x26c
'NtGdiUpdateTransform', # 0x26d
'NtGdiWidenPath', # 0x26e
'NtGdiXFORMOBJ_bApplyXform', # 0x26f
'NtGdiXFORMOBJ_iGetXform', # 0x270
'NtGdiXLATEOBJ_cGetPalette', # 0x271
'NtGdiXLATEOBJ_hGetColorTransform', # 0x272
'NtGdiXLATEOBJ_iXlate', # 0x273
'NtUserAddClipboardFormatListener', # 0x274
'NtUserAssociateInputContext', # 0x275
'NtUserBlockInput', # 0x276
'NtUserBuildHimcList', # 0x277
'NtUserBuildPropList', # 0x278
'NtUserCallHwndOpt', # 0x279
'NtUserChangeDisplaySettings', # 0x27a
'NtUserCheckAccessForIntegrityLevel', # 0x27b
'NtUserCheckDesktopByThreadId', # 0x27c
'NtUserCheckWindowThreadDesktop', # 0x27d
'NtUserChildWindowFromPointEx', # 0x27e
'NtUserClipCursor', # 0x27f
'NtUserCreateDesktopEx', # 0x280
'NtUserCreateInputContext', # 0x281
'NtUserCreateWindowStation', # 0x282
'NtUserCtxDisplayIOCtl', # 0x283
'NtUserDestroyInputContext', # 0x284
'NtUserDisableThreadIme', # 0x285
'NtUserDoSoundConnect', # 0x286
'NtUserDoSoundDisconnect', # 0x287
'NtUserDragDetect', # 0x288
'NtUserDragObject', # 0x289
'NtUserDrawAnimatedRects', # 0x28a
'NtUserDrawCaption', # 0x28b
'NtUserDrawCaptionTemp', # 0x28c
'NtUserDrawMenuBarTemp', # 0x28d
'NtUserDwmGetDxRgn', # 0x28e
'NtUserDwmHintDxUpdate', # 0x28f
'NtUserDwmStartRedirection', # 0x290
'NtUserDwmStopRedirection', # 0x291
'NtUserEndMenu', # 0x292
'NtUserEvent', # 0x293
'NtUserFlashWindowEx', # 0x294
'NtUserFrostCrashedWindow', # 0x295
'NtUserGetAppImeLevel', # 0x296
'NtUserGetCaretPos', # 0x297
'NtUserGetClipCursor', # 0x298
'NtUserGetClipboardViewer', # 0x299
'NtUserGetComboBoxInfo', # 0x29a
'NtUserGetCursorInfo', # 0x29b
'NtUserGetGuiResources', # 0x29c
'NtUserGetImeHotKey', # 0x29d
'NtUserGetImeInfoEx', # 0x29e
'NtUserGetInternalWindowPos', # 0x29f
'NtUserGetKeyNameText', # 0x2a0
'NtUserGetKeyboardLayoutName', # 0x2a1
'NtUserGetLayeredWindowAttributes', # 0x2a2
'NtUserGetListBoxInfo', # 0x2a3
'NtUserGetMenuIndex', # 0x2a4
'NtUserGetMenuItemRect', # 0x2a5
'NtUserGetMouseMovePointsEx', # 0x2a6
'NtUserGetPriorityClipboardFormat', # 0x2a7
'NtUserGetRawInputBuffer', # 0x2a8
'NtUserGetRawInputData', # 0x2a9
'NtUserGetRawInputDeviceInfo', # 0x2aa
'NtUserGetRawInputDeviceList', # 0x2ab
'NtUserGetRegisteredRawInputDevices', # 0x2ac
'NtUserGetUpdatedClipboardFormats', # 0x2ad
'NtUserGetWOWClass', # 0x2ae
'NtUserGetWindowMinimizeRect', # 0x2af
'NtUserGetWindowRgnEx', # 0x2b0
'NtUserGhostWindowFromHungWindow', # 0x2b1
'NtUserHardErrorControl', # 0x2b2
'NtUserHiliteMenuItem', # 0x2b3
'NtUserHungWindowFromGhostWindow', # 0x2b4
'NtUserImpersonateDdeClientWindow', # 0x2b5
'NtUserInitTask', # 0x2b6
'NtUserInitialize', # 0x2b7
'NtUserInitializeClientPfnArrays', # 0x2b8
'NtUserInternalGetWindowIcon', # 0x2b9
'NtUserLoadKeyboardLayoutEx', # 0x2ba
'NtUserLockWindowStation', # 0x2bb
'NtUserLockWorkStation', # 0x2bc
'NtUserLogicalToPhysicalPoint', # 0x2bd
'NtUserMNDragLeave', # 0x2be
'NtUserMNDragOver', # 0x2bf
'NtUserMenuItemFromPoint', # 0x2c0
'NtUserMinMaximize', # 0x2c1
'NtUserNotifyIMEStatus', # 0x2c2
'NtUserOpenInputDesktop', # 0x2c3
'NtUserOpenThreadDesktop', # 0x2c4
'NtUserPaintMonitor', # 0x2c5
'NtUserPhysicalToLogicalPoint', # 0x2c6
'NtUserPrintWindow', # 0x2c7
'NtUserQueryInformationThread', # 0x2c8
'NtUserQueryInputContext', # 0x2c9
'NtUserQuerySendMessage', # 0x2ca
'NtUserRealChildWindowFromPoint', # 0x2cb
'NtUserRealWaitMessageEx', # 0x2cc
'NtUserRegisterErrorReportingDialog', # 0x2cd
'NtUserRegisterHotKey', # 0x2ce
'NtUserRegisterRawInputDevices', # 0x2cf
'NtUserRegisterSessionPort', # 0x2d0
'NtUserRegisterTasklist', # 0x2d1
'NtUserRegisterUserApiHook', # 0x2d2
'NtUserRemoteConnect', # 0x2d3
'NtUserRemoteRedrawRectangle', # 0x2d4
'NtUserRemoteRedrawScreen', # 0x2d5
'NtUserRemoteStopScreenUpdates', # 0x2d6
'NtUserRemoveClipboardFormatListener', # 0x2d7
'NtUserResolveDesktopForWOW', # 0x2d8
'NtUserSetAppImeLevel', # 0x2d9
'NtUserSetClassWord', # 0x2da
'NtUserSetCursorContents', # 0x2db
'NtUserSetImeHotKey', # 0x2dc
'NtUserSetImeInfoEx', # 0x2dd
'NtUserSetImeOwnerWindow', # 0x2de
'NtUserSetInternalWindowPos', # 0x2df
'NtUserSetLayeredWindowAttributes', # 0x2e0
'NtUserSetMenu', # 0x2e1
'NtUserSetMenuContextHelpId', # 0x2e2
'NtUserSetMenuFlagRtoL', # 0x2e3
'NtUserSetMirrorRendering', # 0x2e4
'NtUserSetObjectInformation', # 0x2e5
'NtUserSetProcessDPIAware', # 0x2e6
'NtUserSetShellWindowEx', # 0x2e7
'NtUserSetSysColors', # 0x2e8
'NtUserSetSystemCursor', # 0x2e9
'NtUserSetSystemTimer', # 0x2ea
'NtUserSetThreadLayoutHandles', # 0x2eb
'NtUserSetWindowRgnEx', # 0x2ec
'NtUserSetWindowStationUser', # 0x2ed
'NtUserShowSystemCursor', # 0x2ee
'NtUserSoundSentry', # 0x2ef
'NtUserSwitchDesktop', # 0x2f0
'NtUserTestForInteractiveUser', # 0x2f1
'NtUserTrackPopupMenuEx', # 0x2f2
'NtUserUnloadKeyboardLayout', # 0x2f3
'NtUserUnlockWindowStation', # 0x2f4
'NtUserUnregisterHotKey', # 0x2f5
'NtUserUnregisterSessionPort', # 0x2f6
'NtUserUnregisterUserApiHook', # 0x2f7
'NtUserUpdateInputContext', # 0x2f8
'NtUserUpdateInstance', # 0x2f9
'NtUserUpdateLayeredWindow', # 0x2fa
'NtUserUpdatePerUserSystemParameters', # 0x2fb
'NtUserUpdateWindowTransform', # 0x2fc
'NtUserUserHandleGrantAccess', # 0x2fd
'NtUserValidateHandleSecure', # 0x2fe
'NtUserWaitForInputIdle', # 0x2ff
'NtUserWaitForMsgAndEvent', # 0x300
'NtUserWin32PoolAllocationStats', # 0x301
'NtUserWindowFromPhysicalPoint', # 0x302
'NtUserYieldTask', # 0x303
'NtUserSetClassLongPtr', # 0x304
'NtUserSetWindowLongPtr', # 0x305
],
]
|
Cisco-Talos/pyrebox
|
volatility/volatility/plugins/overlays/windows/vista_sp12_x64_syscalls.py
|
Python
|
gpl-2.0
| 43,395 | 0.053693 |
# (C) Copyright 2017, 2019-2020 by Rocky Bernstein
"""
CPython 3.0 bytecode opcodes
This is a like Python 3.0's opcode.py with some classification
of stack usage.
"""
from xdis.opcodes.base import (
def_op,
extended_format_ATTR,
extended_format_CALL_FUNCTION,
finalize_opcodes,
format_MAKE_FUNCTION_default_argc,
format_extended_arg,
init_opdata,
jrel_op,
rm_op,
update_pj2,
)
import xdis.opcodes.opcode_31 as opcode_31
version = 3.0
python_implementation = "CPython"
l = locals()
init_opdata(l, opcode_31, version)
# These are in Python 3.x but not in Python 3.0
rm_op(l, 'JUMP_IF_FALSE_OR_POP', 111)
rm_op(l, 'JUMP_IF_TRUE_OR_POP', 112)
rm_op(l, 'POP_JUMP_IF_FALSE', 114)
rm_op(l, 'POP_JUMP_IF_TRUE', 115)
rm_op(l, 'LIST_APPEND', 145)
rm_op(l, 'MAP_ADD', 147)
# These are are in 3.0 but are not in 3.1 or they have
# different opcode numbers. Note: As a result of opcode value
# changes, these have to be applied *after* removing ops (with
# the same name).
# OP NAME OPCODE POP PUSH
#--------------------------------------------
def_op(l, 'SET_ADD', 17, 2, 0) # Calls set.add(TOS1[-i], TOS).
# Used to implement set comprehensions.
def_op(l, 'LIST_APPEND', 18, 2, 0) # Calls list.append(TOS1, TOS).
# Used to implement list comprehensions.
jrel_op(l, 'JUMP_IF_FALSE', 111, 1, 1)
jrel_op(l, 'JUMP_IF_TRUE', 112, 1, 1)
# Yes, pj2 not pj3 - Python 3.0 is more like 2.7 here with its
# JUMP_IF rather than POP_JUMP_IF.
update_pj2(globals(), l)
opcode_arg_fmt = {
'MAKE_FUNCTION': format_MAKE_FUNCTION_default_argc,
'EXTENDED_ARG': format_extended_arg,
}
opcode_extended_fmt = {
"LOAD_ATTR": extended_format_ATTR,
"CALL_FUNCTION": extended_format_CALL_FUNCTION,
"STORE_ATTR": extended_format_ATTR,
}
finalize_opcodes(l)
|
TeamSPoon/logicmoo_workspace
|
packs_web/butterfly/lib/python3.7/site-packages/xdis/opcodes/opcode_30.py
|
Python
|
mit
| 1,967 | 0.004067 |
""" Local dev settings and globals. """
from base import *
""" DEBUG CONFIGURATION """
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
""" LOGGING """
for logger_key in LOGGING['loggers'].keys():
LOGGING['loggers'][logger_key]['level'] = 'DEBUG'
for handler_key in LOGGING['handlers'].keys():
LOGGING['handlers'][handler_key]['level'] = 'DEBUG'
""" TOOLBAR CONFIGURATION """
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INSTALLED_APPS += (
'debug_toolbar',
)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INTERNAL_IPS = ('127.0.0.1',)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
# Should be added as soon as possible in the order
MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware',) + MIDDLEWARE_CLASSES
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
DEBUG_TOOLBAR_PATCH_SETTINGS = False
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TEMPLATE_CONTEXT': True,
}
|
WimpyAnalytics/django-readonly-schema
|
readonly/readonly/settings/local.py
|
Python
|
mit
| 1,156 | 0.00519 |
#!/usr/bin/env python3
#
# build-utilities
# Copyright (c) 2015, Alexandre ACEBEDO, All rights reserved.
#
# 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 3.0 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.
#
"""
Setup script for build-utilities
"""
import sys
import os
from platform import python_version
try:
import versioneer
except Exception as e:
sys.exit("versioneer for python3 is missing")
try:
from setuptools import setup, find_packages
except Exception as e:
sys.exit("setuptools for python3 is missing")
from setuptools.command.install import install
class InstallCommand(install):
user_options = install.user_options + [
('prefix=', None, 'Install prefix pathsomething')
]
def initialize_options(self):
install.initialize_options(self)
self.prefix = None
def finalize_options(self):
#print('The custom option for install is ', self.custom_option)
install.finalize_options(self)
def run(self):
if self.prefix != None:
os.environ["PYTHONPATH"] = os.path.join(self.prefix,"lib","python{}.{}".format(python_version()[0],python_version()[2]),"site-packages")
install.run(self)
def process_setup():
"""
Setup function
"""
if sys.version_info < (3,0):
sys.exit("build-utilities only supports python3. Please run setup.py with python3.")
cmds = versioneer.get_cmdclass()
cmds["install"] = InstallCommand
setup(
name="build-utilities",
version=versioneer.get_version(),
cmdclass=cmds,
packages=find_packages("src"),
package_dir ={'':'src'},
install_requires=['GitPython>=2.0', 'progressbar2>=2.0.0'],
author="Alexandre ACEBEDO",
author_email="Alexandre ACEBEDO",
description="Build utilities for python and go projects.",
license="LGPLv3",
keywords="build go python",
url="http://github.com/aacebedo/build-utilities",
entry_points={'console_scripts':
['build-utilities = buildutilities.__main__:BuildUtilities.main']}
)
if __name__ == "__main__":
process_setup()
|
aacebedo/build-utilities
|
setup.py
|
Python
|
lgpl-3.0
| 2,674 | 0.008975 |
from zeit.cms.i18n import MessageFactory as _
import copy
import grokcore.component as grok
import lxml.objectify
import zeit.cms.content.property
import zeit.cms.interfaces
import zeit.cms.syndication.feed
import zeit.cms.syndication.interfaces
import zeit.content.cp.blocks.block
import zeit.content.cp.interfaces
import zeit.edit.interfaces
import zope.component
import zope.container.interfaces
import zope.interface
import zope.schema
class TeaserBlock(
zeit.content.cp.blocks.block.Block,
zeit.cms.syndication.feed.ContentList):
zope.interface.implementsOnly(
zeit.content.cp.interfaces.ITeaserBlock,
zeit.cms.syndication.interfaces.IFeed,
zope.container.interfaces.IContained)
type = 'teaser'
force_mobile_image = zeit.cms.content.property.ObjectPathAttributeProperty(
'.', 'force_mobile_image', zeit.content.cp.interfaces.ITeaserBlock[
'force_mobile_image'])
def __init__(self, context, xml):
super(TeaserBlock, self).__init__(context, xml)
if self.xml.get('module') == 'teaser':
if isinstance(self.layout, zeit.content.cp.layout.NoBlockLayout):
raise ValueError(_(
'No default teaser layout defined for this area.'))
self.layout = self.layout
assert self.xml.get('module') != 'teaser'
@property
def entries(self):
# overriden so that super.insert() and updateOrder() work
return self.xml
@property
def layout(self):
id = self.xml.get('module')
source = zeit.content.cp.interfaces.ITeaserBlock['layout'].source(
self)
layout = source.find(id)
if layout:
return layout
return zeit.content.cp.interfaces.IArea(self).default_teaser_layout \
or zeit.content.cp.layout.NoBlockLayout(self)
@layout.setter
def layout(self, layout):
self._p_changed = True
self.xml.set('module', layout.id)
TEASERBLOCK_FIELDS = (
set(zope.schema.getFieldNames(
zeit.content.cp.interfaces.ITeaserBlock)) -
set(zeit.cms.content.interfaces.IXMLRepresentation)
)
def update(self, other):
if not zeit.content.cp.interfaces.ITeaserBlock.providedBy(other):
raise ValueError('%r is not an ITeaserBlock' % other)
# Copy teaser contents.
for content in other:
self.append(content)
# Copy block properties (including __name__ and __parent__)
for name in self.TEASERBLOCK_FIELDS:
setattr(self, name, getattr(other, name))
class Factory(zeit.content.cp.blocks.block.BlockFactory):
produces = TeaserBlock
title = _('List of teasers')
@grok.adapter(zeit.content.cp.interfaces.IArea,
zeit.cms.interfaces.ICMSContent,
int)
@grok.implementer(zeit.edit.interfaces.IElement)
def make_block_from_content(container, content, position):
block = Factory(container)(position)
block.insert(0, content)
return block
@grok.adapter(zeit.content.cp.interfaces.ITeaserBlock)
@grok.implementer(zeit.edit.interfaces.IElementReferences)
def cms_content_iter(context):
for teaser in context:
yield teaser
@grok.adapter(zeit.content.cp.interfaces.ICenterPage)
@grok.implementer(zeit.content.cp.interfaces.ITeaseredContent)
def extract_teasers_from_cp(context):
for region in context.values():
for area in region.values():
for teaser in zeit.content.cp.interfaces.ITeaseredContent(area):
yield teaser
@grok.adapter(zeit.content.cp.interfaces.IArea)
@grok.implementer(zeit.content.cp.interfaces.ITeaseredContent)
def extract_teasers_from_area(context):
for teaser in context.filter_values(
zeit.content.cp.interfaces.ITeaserBlock):
for content in list(teaser):
yield content
def extract_manual_teasers(context):
for teaser in context.values():
if not zeit.content.cp.interfaces.ITeaserBlock.providedBy(teaser):
continue
for content in list(teaser):
yield content
@grok.subscribe(
zeit.content.cp.interfaces.ITeaserBlock,
zope.container.interfaces.IObjectMovedEvent)
def change_layout_if_not_allowed_in_new_area(context, event):
# Getting a default layout can mean that the current layout is not allowed
# in this area (can happen when a block was moved between areas). Thus, we
# want to change the XML to actually reflect the new default layout.
if context.layout.is_default(context):
context.layout = context.layout
@grok.subscribe(
zeit.content.cp.interfaces.ITeaserBlock,
zope.container.interfaces.IObjectAddedEvent)
def apply_layout_for_added(context, event):
"""Set layout for new teasers only."""
area = context.__parent__
if not area.apply_teaser_layouts_automatically:
return
# XXX The overflow_blocks handler also listens to the IObjectAddedEvent and
# may have removed this item from the container. Since overflow_blocks
# retrieves the item via a getitem access, it is newly created from the XML
# node. That means `context is not context.__parent__[context.__name__]`.
# Since it is not the same object, changes to the newly created object will
# not be reflected in the context given to event handlers. So we need a
# guard here to check if overflow_blocks has removed the item and skip the
# method in case it has. (Modifying __parent__ of context does not seem
# like a good idea, hell might break loose. So lets just forget about this
# possiblity.)
if context.__name__ not in area.keys():
return
if area.keys().index(context.__name__) == 0:
context.layout = area.first_teaser_layout
else:
context.layout = area.default_teaser_layout
@grok.subscribe(
zeit.content.cp.interfaces.IArea,
zeit.edit.interfaces.IOrderUpdatedEvent)
def set_layout_to_default_when_moved_down_from_first_position(area, event):
if not area.apply_teaser_layouts_automatically:
return
# XXX The overflow_blocks handler listens to the IObjectAddedEvent and may
# have removed this item from the container. In that case we have to do
# nothing, since checking the layout is handled by the new container.
if event.old_order[0] not in area.keys():
return
previously_first = area[event.old_order[0]]
if (zeit.content.cp.interfaces.ITeaserBlock.providedBy(
previously_first) and
area.values().index(previously_first)) > 0:
previously_first.layout = area.default_teaser_layout
@grok.adapter(zeit.content.cp.interfaces.ITeaserBlock)
@grok.implementer(zeit.content.cp.interfaces.IRenderedXML)
def rendered_xml_teaserblock(context):
container = getattr(
lxml.objectify.E, context.xml.tag)(**context.xml.attrib)
# Render non-content items like topiclinks.
for child in context.xml.getchildren():
# BBB: xinclude is not generated anymore, but some might still exist.
if child.tag not in [
'block', '{http://www.w3.org/2003/XInclude}include']:
container.append(copy.copy(child))
# Render content.
for entry in context:
node = zope.component.queryAdapter(
entry, zeit.content.cp.interfaces.IRenderedXML, name="content")
if node is not None:
container.append(node)
return container
@grok.adapter(zeit.cms.interfaces.ICMSContent, name="content")
@grok.implementer(zeit.content.cp.interfaces.IRenderedXML)
def rendered_xml_cmscontent(context):
if not context.uniqueId:
return None
block = lxml.objectify.E.block(
uniqueId=context.uniqueId, href=context.uniqueId)
updater = zeit.cms.content.interfaces.IXMLReferenceUpdater(context)
updater.update(block, suppress_errors=True)
return block
|
ZeitOnline/zeit.content.cp
|
src/zeit/content/cp/blocks/teaser.py
|
Python
|
bsd-3-clause
| 7,905 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.