code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
# Test which PDB entries error on PDB/mmCIF parsers # Writes output to a file labelled with the week import os from datetime import datetime from math import ceil from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser start = datetime.now() basedir = "." pdbl = PDBList() pdblist = pdbl.get_all_entries() outstrs = ["Checking all PDB entries at {}".format(start.isoformat()), "Checking {} entries".format(len(pdblist))] pdb_parser = PDBParser() mmcif_parser = MMCIFParser() for pu in sorted(pdblist): p = pu.lower() try: pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="pdb") except: # Not having a PDB file is acceptable, though a failure to download an # available file may hide an error in parsing try: os.remove("{}/pdb{}.ent".format(basedir, p)) except: pass if os.path.isfile("{}/pdb{}.ent".format(basedir, p)): try: s = pdb_parser.get_structure("", "{}/pdb{}.ent".format(basedir, p)) except: outstrs.append("{} - PDB parsing error".format(pu)) os.remove("{}/pdb{}.ent".format(basedir, p)) try: pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="mmCif") except: try: os.remove("{}/{}.cif".format(basedir, p)) except: pass outstrs.append("{} - no mmCIF download".format(pu)) if os.path.isfile("{}/{}.cif".format(basedir, p)): try: s = mmcif_parser.get_structure("", "{}/{}.cif".format(basedir, p)) except: outstrs.append("{} - mmCIF parsing error".format(pu)) os.remove("{}/{}.cif".format(basedir, p)) if len(outstrs) == 2: outstrs.append("All entries read fine") end = datetime.now() outstrs.append("Time taken - {} minute(s)".format(int(ceil((end - start).seconds / 60)))) datestr = str(end.date()).replace("-", "") # This overwrites any existing file with open("{}/wholepdb_py_{}.txt".format(basedir, datestr), "w") as f: for l in outstrs: f.write(l + "\n")
jgreener64/pdb-benchmarks
checkwholepdb/checkwholepdb.py
Python
mit
2,107
import rosbag from sensor_msgs.msg import PointCloud2 def pc_filter(topic, datatype, md5sum, msg_def, header): if datatype == 'sensor_msgs/PointCloud2': return True return False class MockCamera(object): """A MockCamera reads saved point clouds. """ def __init__(self): pass def read_cloud(self, path): """Returns the sensor_msgs/PointCloud2 in the given bag file. Args: path: string, the path to a bag file with a single sensor_msgs/PointCloud2 in it. Returns: A sensor_msgs/PointCloud2 message, or None if there were no PointCloud2 messages in the bag file. """ bag = rosbag.Bag(path) for topic, msg, time in bag.read_messages(connection_filter=pc_filter): return msg bag.close() return None
hcrlab/access_teleop
cse481wi18/perception/src/perception/mock_camera.py
Python
mit
858
''' Contains Vmstat() class Typical contents of vmstat file:: nr_free_pages 1757414 nr_inactive_anon 2604 nr_active_anon 528697 nr_inactive_file 841209 nr_active_file 382447 nr_unevictable 7836 nr_mlock 7837 nr_anon_pages 534070 nr_mapped 76013 nr_file_pages 1228693 nr_dirty 21 nr_writeback 0 nr_slab_reclaimable 511040 nr_slab_unreclaimable 13487 nr_page_table_pages 13920 nr_kernel_stack 809 nr_unstable 0 nr_bounce 0 nr_vmscan_write 0 nr_vmscan_immediate_reclaim 0 nr_writeback_temp 0 nr_isolated_anon 0 nr_isolated_file 0 nr_shmem 3583 nr_dirtied 1034714 nr_written 972154 numa_hit 29109076 numa_miss 0 numa_foreign 0 numa_interleave 11066 numa_local 29109076 numa_other 0 nr_anon_transparent_hugepages 0 nr_dirty_threshold 347004 nr_dirty_background_threshold 173502 pgpgin 6038832 pgpgout 6412006 pswpin 0 pswpout 0 pgalloc_dma 0 pgalloc_dma32 51 pgalloc_normal 30639735 pgalloc_movable 0 pgfree 32398292 pgactivate 2344853 pgdeactivate 1 pgfault 37440670 pgmajfault 3319 pgrefill_dma 0 pgrefill_dma32 0 pgrefill_normal 0 pgrefill_movable 0 pgsteal_kswapd_dma 0 pgsteal_kswapd_dma32 0 pgsteal_kswapd_normal 0 pgsteal_kswapd_movable 0 pgsteal_direct_dma 0 pgsteal_direct_dma32 0 pgsteal_direct_normal 0 pgsteal_direct_movable 0 pgscan_kswapd_dma 0 pgscan_kswapd_dma32 0 pgscan_kswapd_normal 0 pgscan_kswapd_movable 0 pgscan_direct_dma 0 pgscan_direct_dma32 0 pgscan_direct_normal 0 pgscan_direct_movable 0 zone_reclaim_failed 0 pginodesteal 0 slabs_scanned 0 kswapd_inodesteal 0 kswapd_low_wmark_hit_quickly 0 kswapd_high_wmark_hit_quickly 0 kswapd_skip_congestion_wait 0 pageoutrun 1 allocstall 0 pgrotated 23 compact_blocks_moved 0 compact_pages_moved 0 compact_pagemigrate_failed 0 compact_stall 0 compact_fail 0 compact_success 0 htlb_buddy_alloc_success 0 htlb_buddy_alloc_fail 0 unevictable_pgs_culled 8305 unevictable_pgs_scanned 0 unevictable_pgs_rescued 6377 unevictable_pgs_mlocked 15565 unevictable_pgs_munlocked 7197 unevictable_pgs_cleared 0 unevictable_pgs_stranded 0 unevictable_pgs_mlockfreed 0 thp_fault_alloc 0 thp_fault_fallback 0 thp_collapse_alloc 0 thp_collapse_alloc_failed 0 thp_split 0 ''' from logging import getLogger from os import path as ospath from .readfile import ReadFile LOGGER = getLogger(__name__) class VMstat(ReadFile): ''' VMstat handling ''' FILENAME = ospath.join('proc', 'vmstat') KEY = 'vmstat' def normalize(self): ''' Translates data into dictionary The vmstat file is a number of records keyed on ' ' separator ''' LOGGER.debug("Normalize") lines = self.lines ret = {} for line in lines: top, tail = line.split() ret[top.strip()] = int(tail.strip()) return ret
eccles/lnxproc
lnxproc/vmstat.py
Python
mit
3,041
# -*- coding: utf-8 -*- """ The output tab for the main toolbar @author: Chris Scott """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import shutil import subprocess import copy import logging import math import functools import datetime import time import numpy as np from PySide2 import QtGui, QtCore, QtWidgets from PIL import Image from ..visutils import utilities from ..visutils import threading_vis from ..visutils.utilities import iconPath from . import genericForm from ..plotting import rdf from ..algebra import _vectors as vectors_c from ..plotting import plotDialog from . import utils import six from six.moves import range class OutputDialog(QtWidgets.QDialog): def __init__(self, parent, mainWindow, width, index): super(OutputDialog, self).__init__(parent) self.parent = parent self.rendererWindow = parent self.mainToolbar = parent self.mainWindow = mainWindow self.width = width self.setWindowTitle("Output - Render window %d" % index) self.setModal(0) # size self.resize(QtCore.QSize(350, 600)) # layout outputTabLayout = QtWidgets.QVBoxLayout(self) outputTabLayout.setContentsMargins(0, 0, 0, 0) outputTabLayout.setSpacing(0) outputTabLayout.setAlignment(QtCore.Qt.AlignTop) # add tab bar self.outputTypeTabBar = QtWidgets.QTabWidget(self) self.outputTypeTabBar.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # add tabs to tab bar # image tab imageTabWidget = QtWidgets.QWidget() imageTabLayout = QtWidgets.QVBoxLayout(imageTabWidget) imageTabLayout.setContentsMargins(0, 0, 0, 0) self.imageTab = ImageTab(self, self.mainWindow, self.width) imageTabLayout.addWidget(self.imageTab) self.outputTypeTabBar.addTab(imageTabWidget, "Image") # file tab fileTabWidget = QtWidgets.QWidget() fileTabLayout = QtWidgets.QVBoxLayout(fileTabWidget) fileTabLayout.setContentsMargins(0, 0, 0, 0) self.fileTab = FileTab(self, self.mainWindow, self.width) fileTabLayout.addWidget(self.fileTab) self.outputTypeTabBar.addTab(fileTabWidget, "File") # plot tab self.plotTab = PlotTab(self.mainWindow, self.rendererWindow, parent=self) self.outputTypeTabBar.addTab(self.plotTab, "Plot") # add tab bar to layout outputTabLayout.addWidget(self.outputTypeTabBar) class ScalarsHistogramOptionsForm(genericForm.GenericForm): """ Main options form for scalars histograms """ def __init__(self, parent, mainWindow, rendererWindow): super(ScalarsHistogramOptionsForm, self).__init__(parent, 0, "Histogram plot options") self.mainWindow = mainWindow self.rendererWindow = rendererWindow # current number of scalar plots self.numScalarsPlots = 0 # current plots self.currentPlots = {} # add combo box self.scalarsCombo = QtWidgets.QComboBox() self.scalarsCombo.currentIndexChanged[int].connect(self.scalarsComboChanged) self.newRow().addWidget(self.scalarsCombo) # add stacked widget self.stackedWidget = QtWidgets.QStackedWidget() self.newRow().addWidget(self.stackedWidget) self.logger = logging.getLogger(__name__ + ".ScalarsHistogramOptionsForm") def scalarsComboChanged(self, index): """ Scalars combo changed """ self.stackedWidget.setCurrentIndex(index) def removeScalarPlotOptions(self): """ Remove scalar plot options """ self.logger.debug("Removing scalar plot options") for scalarsID in list(self.currentPlots.keys()): self.logger.debug(" Removing: '%s'", scalarsID) form = self.currentPlots.pop(scalarsID) self.stackedWidget.removeWidget(form) form.deleteLater() self.scalarsCombo.removeItem(0) self.numScalarsPlots = 0 def addAtomPropertyPlotOptions(self): """ Add atom property plot options """ self.logger.debug("Adding atom property plot options") # get current pipeline page pp = self.rendererWindow.getCurrentPipelinePage() ppindex = pp.pipelineIndex lattice = pp.inputState # add charge plot option scalarsArray = lattice.charge if np.min(scalarsArray) == 0 == np.max(scalarsArray): self.logger.debug(" Skipping charge: all zero") else: self.logger.debug(" Adding charge plot") scalarsName = "Charge" scalarsID = "%s (%d)" % (scalarsName, ppindex) self.addScalarPlotOptions(scalarsID, scalarsName, scalarsArray) def addScalarPlotOptions(self, scalarsID, scalarsName, scalarsArray): """ Add plot for scalar 'name' """ # don't add duplicates (should never happen anyway) if scalarsID in self.currentPlots: return # don't add empty arrays if not len(scalarsArray): return self.logger.debug("Adding scalar plot option: '%s'", scalarsID) # create form form = GenericHistogramPlotForm(self, scalarsID, scalarsName, scalarsArray) # add to stacked widget self.stackedWidget.addWidget(form) # add to combo box self.scalarsCombo.addItem(scalarsID) # store in dict self.currentPlots[scalarsID] = form # number of plots self.numScalarsPlots += 1 def refreshScalarPlotOptions(self): """ Refresh plot options * Called after pipeline page has run filters/single filter has run * loops over all filter lists under pipeline page, adding plots for all scalars * plots named after pipeline index and filter list index * also called when renderWindow pipeline index changes * also called when filter lists are cleared, etc...? """ self.logger.debug("Refreshing plot options") # remove old options self.removeScalarPlotOptions() # get current pipeline page pp = self.rendererWindow.getCurrentPipelinePage() ppindex = pp.pipelineIndex # get filter lists filterLists = pp.filterLists # first add atom properties (KE, PE, charge) self.addAtomPropertyPlotOptions() # loop over filter lists, adding scalars self.logger.debug("Looping over filter lists (%d)", len(filterLists)) for filterList in filterLists: # make unique name for pipeline page/filter list combo findex = filterList.tab filterListID = "%d-%d" % (ppindex, findex) self.logger.debug("Filter list %d; id '%s'", filterList.tab, filterListID) # loop over scalars in scalarsDict on filterer for scalarsName, scalarsArray in six.iteritems(filterList.filterer.scalarsDict): # make unique id scalarsID = "%s (%s)" % (scalarsName, filterListID) # add self.addScalarPlotOptions(scalarsID, scalarsName, scalarsArray) # loop over scalars in latticeScalarsDict on filterer latticeScalarKeys = list(filterList.pipelinePage.inputState.scalarsDict.keys()) for key in latticeScalarKeys: if key in filterList.filterer.latticeScalarsDict: scalarsArray = filterList.filterer.latticeScalarsDict[key] self.logger.debug("Using Filterer scalars for '%s'", key) else: scalarsArray = filterList.pipelinePage.inputState.scalarsDict[key] self.logger.debug("Using Lattice scalars for '%s'", key) # make unique id scalarsName = key scalarsID = "%s (%s)" % (scalarsName, filterListID) # add self.addScalarPlotOptions(scalarsID, scalarsName, scalarsArray) # add cluster size/volume distributions too if len(filterList.filterer.clusterList): clusterSizes = [] clusterVolumes = [] haveVolumes = True for c in filterList.filterer.clusterList: # cluster sizes clusterSizes.append(len(c)) # cluster volumes vol = c.getVolume() if vol is not None: clusterVolumes.append(vol) else: haveVolumes = False # plot cluster size scalarsID = "Cluster size (%s)" % filterListID self.addScalarPlotOptions(scalarsID, "Cluster size", np.asarray(clusterSizes, dtype=np.float64)) if haveVolumes: # plot volumes scalarsID = "Cluster volume (%s)" % filterListID self.addScalarPlotOptions(scalarsID, "Cluster volume", np.asarray(clusterVolumes, dtype=np.float64)) # hide if no plots, otherwise show if self.numScalarsPlots > 0: self.show() else: self.hide() class PlotTab(QtWidgets.QWidget): """ Plot tab """ def __init__(self, mainWindow, rendererWindow, parent=None): super(PlotTab, self).__init__(parent) self.mainWindow = mainWindow self.rendererWindow = rendererWindow # layout self.layout = QtWidgets.QVBoxLayout(self) self.layout.setAlignment(QtCore.Qt.AlignTop) self.layout.setSpacing(0) # rdf row = self.newRow() self.rdfForm = RDFForm(self, self.mainWindow) row.addWidget(self.rdfForm) # scalars histograms self.scalarsForm = ScalarsHistogramOptionsForm(self, mainWindow, rendererWindow) row = self.newRow() row.addWidget(self.scalarsForm) self.layout.addStretch(1) # logging self.logger = logging.getLogger(__name__ + ".PlotTab") def newRow(self): """ New row """ row = genericForm.FormRow() self.layout.addWidget(row) return row class GenericHistogramPlotForm(genericForm.GenericForm): """ Plot options for a histogram of scalar values """ def __init__(self, parent, scalarsID, scalarsName, scalarsArray): super(GenericHistogramPlotForm, self).__init__(parent, 0, "%s plot options" % scalarsID) self.parent = parent self.scalarsID = scalarsID self.scalarsName = scalarsName self.scalarsArray = scalarsArray self.logger = logging.getLogger(__name__ + ".GenericHistogramPlotForm") # scalar stats self.scalarMin = np.min(scalarsArray) self.scalarMax = np.max(scalarsArray) self.scalarMean = np.mean(scalarsArray) self.scalarSTD = np.std(scalarsArray) self.scalarSE = self.scalarSTD / math.sqrt(len(scalarsArray)) # default self.useNumBins = True self.numBins = 10 self.binWidth = 1.0 self.showAsFraction = False # stats labels row = self.newRow() row.addWidget(QtWidgets.QLabel("Min: %f" % self.scalarMin)) row = self.newRow() row.addWidget(QtWidgets.QLabel("Max: %f" % self.scalarMax)) row = self.newRow() row.addWidget(QtWidgets.QLabel("Mean: %f" % self.scalarMean)) row = self.newRow() row.addWidget(QtWidgets.QLabel("STD: %f; SE: %f" % (self.scalarSTD, self.scalarSE))) # num bins/bin width combo binCombo = QtWidgets.QComboBox() binCombo.addItem("Number of bins:") binCombo.addItem("Bin width:") binCombo.currentIndexChanged[int].connect(self.binComboChanged) # bin stack self.binStack = QtWidgets.QStackedWidget() # number of bins spin numBinsSpin = QtWidgets.QSpinBox() numBinsSpin.setMinimum(2) numBinsSpin.setMaximum(999) numBinsSpin.setSingleStep(1) numBinsSpin.setValue(self.numBins) numBinsSpin.valueChanged.connect(self.numBinsChanged) self.binStack.addWidget(numBinsSpin) # bin width spin binWidthSpin = QtWidgets.QDoubleSpinBox() binWidthSpin.setMinimum(0.01) binWidthSpin.setMaximum(99.99) binWidthSpin.setSingleStep(0.1) binWidthSpin.setValue(self.binWidth) binWidthSpin.valueChanged.connect(self.binWidthChanged) self.binStack.addWidget(binWidthSpin) binCombo.setCurrentIndex(1) # row row = self.newRow() row.addWidget(binCombo) row.addWidget(self.binStack) # show as fraction option showAsFractionCheck = QtWidgets.QCheckBox("Show as fraction") showAsFractionCheck.setCheckState(QtCore.Qt.Unchecked) showAsFractionCheck.stateChanged.connect(self.showAsFractionChanged) row = self.newRow() row.addWidget(showAsFractionCheck) # plot button plotButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/office-chart-bar.png")), "Plot") plotButton.clicked.connect(self.makePlot) row = self.newRow() row.addWidget(plotButton) # show self.show() def binWidthChanged(self, val): """ Bin width changed """ self.binWidth = val def binComboChanged(self, index): """ Bin combo changed """ if index == 0: self.useNumBins = True self.binStack.setCurrentIndex(index) elif index == 1: self.useNumBins = False self.binStack.setCurrentIndex(index) else: self.logger.error("Bin combo index error (%d)", index) def showAsFractionChanged(self, checkState): """ Show as fraction changed """ if checkState == QtCore.Qt.Unchecked: self.showAsFraction = False else: self.showAsFraction = True def numBinsChanged(self, val): """ Number of bins changed """ self.numBins = val def makePlot(self): """ Do the plot """ self.logger.debug("Plotting '%s'", self.scalarsID) if self.scalarMax == self.scalarMin: self.logger.error("Max val == min val; not plotting histogram") return scalars = self.scalarsArray minVal = self.scalarMin maxVal = self.scalarMax # number of bins if self.useNumBins: numBins = self.numBins else: binWidth = self.binWidth # min tmp = math.floor(minVal / binWidth) assert tmp * binWidth <= minVal and (tmp + 1) * binWidth > minVal minVal = tmp * binWidth # max maxVal = minVal while maxVal < self.scalarMax: maxVal += binWidth # num bins numBins = math.ceil((maxVal - minVal) / binWidth) # settings dict settingsDict = {} settingsDict["xlabel"] = self.scalarsName # make plot dialog if self.showAsFraction: # compute histogram hist, binEdges = np.histogram(scalars, numBins, range=(minVal, maxVal)) # make fraction fracHist = hist / float(len(scalars)) # bin width binWidth = (maxVal - minVal) / numBins # y label settingsDict["ylabel"] = "Fraction" # bar plot dlg = plotDialog.PlotDialog(self, self.parent.mainWindow, "%s histogram" % self.scalarsID, "bar", (binEdges[:-1], fracHist), {"width": binWidth}, settingsDict=settingsDict) else: # y label settingsDict["ylabel"] = "Number" # histogram plot dlg = plotDialog.PlotDialog(self, self.parent.mainWindow, "%s histogram" % self.scalarsID, "hist", (scalars, numBins), {"range": (minVal, maxVal)}, settingsDict=settingsDict) # show dialog dlg.show() class RDFForm(genericForm.GenericForm): """ RDF output form. """ def __init__(self, parent, mainWindow): super(RDFForm, self).__init__(parent, 0, "RDF plot options") self.parent = parent self.mainWindow = mainWindow self.rendererWindow = self.parent.rendererWindow self.logger = logging.getLogger(__name__ + ".RDFForm") # defaults self.spec1 = "ALL" self.spec2 = "ALL" self.binMin = 2.0 self.binMax = 10.0 self.binWidth = 0.1 # bond type label = QtWidgets.QLabel("Bond type:") row = self.newRow() row.addWidget(label) self.spec1Combo = QtWidgets.QComboBox() self.spec1Combo.addItem("ALL") self.spec1Combo.currentIndexChanged[str].connect(self.spec1Changed) row.addWidget(self.spec1Combo) label = QtWidgets.QLabel(" - ") row.addWidget(label) self.spec2Combo = QtWidgets.QComboBox() self.spec2Combo.addItem("ALL") self.spec2Combo.currentIndexChanged[str].connect(self.spec2Changed) row.addWidget(self.spec2Combo) # bin range label = QtWidgets.QLabel("Bin range:") row = self.newRow() row.addWidget(label) binMinSpin = QtWidgets.QDoubleSpinBox() binMinSpin.setMinimum(0.0) binMinSpin.setMaximum(500.0) binMinSpin.setSingleStep(1.0) binMinSpin.setValue(self.binMin) binMinSpin.valueChanged.connect(self.binMinChanged) row.addWidget(binMinSpin) label = QtWidgets.QLabel(" - ") row.addWidget(label) binMaxSpin = QtWidgets.QDoubleSpinBox() binMaxSpin.setMinimum(0.0) binMaxSpin.setMaximum(500.0) binMaxSpin.setSingleStep(1.0) binMaxSpin.setValue(self.binMax) binMaxSpin.valueChanged.connect(self.binMaxChanged) row.addWidget(binMaxSpin) # num bins label = QtWidgets.QLabel("Bin width:") row = self.newRow() row.addWidget(label) binWidthSpin = QtWidgets.QDoubleSpinBox() binWidthSpin.setMinimum(0.01) binWidthSpin.setMaximum(1.00) binWidthSpin.setSingleStep(0.1) binWidthSpin.setValue(self.binWidth) binWidthSpin.valueChanged.connect(self.binWidthChanged) row.addWidget(binWidthSpin) # plot button plotButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/office-chart-bar.png")), "Plot") plotButton.clicked.connect(self.plotRDF) row = self.newRow() row.addWidget(plotButton) # show self.show() def refresh(self): """ Should be called whenver a new input is loaded. Refreshes the combo boxes with input specie list. """ # lattice specieList = self.rendererWindow.getCurrentInputState().specieList # store current so can try to reselect spec1CurrentText = str(self.spec1Combo.currentText()) spec2CurrentText = str(self.spec2Combo.currentText()) # clear and rebuild combo box self.spec1Combo.clear() self.spec2Combo.clear() self.spec1Combo.addItem("ALL") self.spec2Combo.addItem("ALL") count = 1 match1 = False match2 = False for sym in specieList: self.spec1Combo.addItem(sym) self.spec2Combo.addItem(sym) if sym == spec1CurrentText: self.spec1Combo.setCurrentIndex(count) match1 = True if sym == spec2CurrentText: self.spec2Combo.setCurrentIndex(count) match2 = True count += 1 if not match1: self.spec1Combo.setCurrentIndex(0) if not match2: self.spec2Combo.setCurrentIndex(0) def plotRDF(self): """ Plot RDF. """ self.logger.info("Plotting RDF for visible atoms") # lattice and pipeline page inputLattice = self.rendererWindow.getCurrentInputState() pp = self.rendererWindow.getCurrentPipelinePage() # check system size warnDims = [] if pp.PBC[0] and self.binMax > inputLattice.cellDims[0] / 2.0: warnDims.append("x") if pp.PBC[1] and self.binMax > inputLattice.cellDims[1] / 2.0: warnDims.append("y") if pp.PBC[2] and self.binMax > inputLattice.cellDims[2] / 2.0: warnDims.append("z") if len(warnDims): msg = "The maximum radius you have requested is greater than half the box length" msg += " in the %s direction(s)!" % ", ".join(warnDims) self.mainWindow.displayError(msg) return # first gather vis atoms visibleAtoms = self.rendererWindow.gatherVisibleAtoms() if not len(visibleAtoms): self.mainWindow.displayWarning("No visible atoms: cannot calculate RDF") return # then determine species if self.spec1 == "ALL": spec1Index = -1 else: spec1Index = inputLattice.getSpecieIndex(self.spec1) if self.spec2 == "ALL": spec2Index = -1 else: spec2Index = inputLattice.getSpecieIndex(self.spec2) # rdf calulator rdfCalculator = rdf.RDFCalculator() # show progress dialog progDiag = utils.showProgressDialog("Calculating RDF", "Calculating RDF...", self) try: # then calculate xn, rdfArray = rdfCalculator.calculateRDF(visibleAtoms, inputLattice, self.binMin, self.binMax, self.binWidth, spec1Index, spec2Index) finally: utils.cancelProgressDialog(progDiag) # prepare to plot settingsDict = {} settingsDict["title"] = "Radial distribution function" settingsDict["xlabel"] = "Bond length (Angstroms)" settingsDict["ylabel"] = "g(r) (%s - %s)" % (self.spec1, self.spec2) # show plot dialog dialog = plotDialog.PlotDialog(self, self.mainWindow, "Radial distribution function ", "plot", (xn, rdfArray), {"linewidth": 2, "label": None}, settingsDict=settingsDict) dialog.show() def binWidthChanged(self, val): """ Num bins changed. """ self.binWidth = val def binMinChanged(self, val): """ Bin min changed. """ self.binMin = val def binMaxChanged(self, val): """ Bin max changed. """ self.binMax = val def spec1Changed(self, text): """ Spec 1 changed. """ self.spec1 = str(text) def spec2Changed(self, text): """ Spec 2 changed. """ self.spec2 = str(text) class FileTab(QtWidgets.QWidget): """ File output tab. """ def __init__(self, parent, mainWindow, width): super(FileTab, self).__init__(parent) self.parent = parent self.rendererWindow = parent.rendererWindow self.mainWindow = mainWindow self.width = width # initial values self.outputFileType = "LATTICE" self.writeFullLattice = True # layout mainLayout = QtWidgets.QVBoxLayout(self) mainLayout.setAlignment(QtCore.Qt.AlignTop) # name group fileNameGroup = genericForm.GenericForm(self, 0, "Output file options") fileNameGroup.show() # file type outputTypeCombo = QtWidgets.QComboBox() outputTypeCombo.addItem("LATTICE") # outputTypeCombo.addItem("LBOMD REF") # outputTypeCombo.addItem("LBOMD XYZ") # outputTypeCombo.addItem("LBOMD FAILSAFE") outputTypeCombo.currentIndexChanged[str].connect(self.outputTypeChanged) label = QtWidgets.QLabel("File type: ") row = fileNameGroup.newRow() row.addWidget(label) row.addWidget(outputTypeCombo) # option to write full lattice fullLatticeCheck = QtWidgets.QCheckBox("Write full lattice (not just visible)") fullLatticeCheck.setCheckState(QtCore.Qt.Checked) fullLatticeCheck.stateChanged.connect(self.fullLatticeCheckChanged) row = fileNameGroup.newRow() row.addWidget(fullLatticeCheck) # file name, save image button row = fileNameGroup.newRow() label = QtWidgets.QLabel("File name: ") self.outputFileName = QtWidgets.QLineEdit("lattice.dat") self.outputFileName.setFixedWidth(120) saveFileButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/document-save.png")), "") saveFileButton.setToolTip("Save to file") saveFileButton.clicked.connect(self.saveToFile) row.addWidget(label) row.addWidget(self.outputFileName) row.addWidget(saveFileButton) # dialog row = fileNameGroup.newRow() saveFileDialogButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath('oxygen/document-open.png')), "Save to file") saveFileDialogButton.setToolTip("Save to file") saveFileDialogButton.setCheckable(0) saveFileDialogButton.setFixedWidth(150) saveFileDialogButton.clicked.connect(self.saveToFileDialog) row.addWidget(saveFileDialogButton) # overwrite self.overwriteCheck = QtWidgets.QCheckBox("Overwrite") row = fileNameGroup.newRow() row.addWidget(self.overwriteCheck) mainLayout.addWidget(fileNameGroup) def fullLatticeCheckChanged(self, val): """ Full lattice check changed. """ if val == QtCore.Qt.Unchecked: self.writeFullLattice = False else: self.writeFullLattice = True def saveToFile(self): """ Save current system to file. """ filename = str(self.outputFileName.text()) if not len(filename): return if os.path.exists(filename) and not self.overwriteCheck.isChecked(): self.mainWindow.displayWarning("File already exists: not overwriting") return # lattice object lattice = self.rendererWindow.getCurrentInputState() # gather vis atoms if required if self.writeFullLattice: visibleAtoms = None else: visibleAtoms = self.rendererWindow.gatherVisibleAtoms() # write Lattice lattice.writeLattice(filename, visibleAtoms=visibleAtoms) def saveToFileDialog(self): """ Open dialog. """ filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File', '.')[0][0] if len(filename): self.outputFileName.setText(str(filename)) self.saveToFile() def outputTypeChanged(self, fileType): """ Output type changed. """ self.outputFileType = str(fileType) class ImageTab(QtWidgets.QWidget): def __init__(self, parent, mainWindow, width): super(ImageTab, self).__init__(parent) self.logger = logging.getLogger(__name__ + ".ImageTab") self.parent = parent self.mainWindow = mainWindow self.width = width self.rendererWindow = self.parent.rendererWindow # initial values self.renderType = "VTK" self.imageFormat = "jpg" # self.overlayImage = False imageTabLayout = QtWidgets.QVBoxLayout(self) # imageTabLayout.setContentsMargins(0, 0, 0, 0) # imageTabLayout.setSpacing(0) imageTabLayout.setAlignment(QtCore.Qt.AlignTop) # Add the generic image options at the top group = QtWidgets.QGroupBox("Image options") group.setAlignment(QtCore.Qt.AlignHCenter) groupLayout = QtWidgets.QVBoxLayout(group) groupLayout.setContentsMargins(0, 0, 0, 0) groupLayout.setSpacing(0) # render type (povray or vtk) renderTypeButtonGroup = QtWidgets.QButtonGroup(self) renderTypeButtonGroup.setExclusive(1) renderTypeButtonGroup.buttonClicked[int].connect(self.setRenderType) self.POVButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("other/pov-icon.png")), "POV-Ray") self.POVButton.setCheckable(1) self.POVButton.setChecked(0) self.VTKButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("other/vtk-icon.png")), "VTK") self.VTKButton.setCheckable(1) self.VTKButton.setChecked(1) renderTypeButtonGroup.addButton(self.VTKButton) renderTypeButtonGroup.addButton(self.POVButton) row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setAlignment(QtCore.Qt.AlignTop) rowLayout.addWidget(self.VTKButton) rowLayout.addWidget(self.POVButton) groupLayout.addWidget(row) # image format row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) imageFormatButtonGroup = QtWidgets.QButtonGroup(self) imageFormatButtonGroup.setExclusive(1) imageFormatButtonGroup.buttonClicked[int].connect(self.setImageFormat) self.JPEGCheck = QtWidgets.QCheckBox("JPEG") self.JPEGCheck.setChecked(1) self.PNGCheck = QtWidgets.QCheckBox("PNG") self.TIFFCheck = QtWidgets.QCheckBox("TIFF") imageFormatButtonGroup.addButton(self.JPEGCheck) imageFormatButtonGroup.addButton(self.PNGCheck) imageFormatButtonGroup.addButton(self.TIFFCheck) rowLayout.addWidget(self.JPEGCheck) rowLayout.addWidget(self.PNGCheck) rowLayout.addWidget(self.TIFFCheck) groupLayout.addWidget(row) # additional (POV-Ray) options row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) groupLayout.addWidget(row) imageTabLayout.addWidget(group) # tab bar for different types of image output self.imageTabBar = QtWidgets.QTabWidget(self) self.imageTabBar.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # add tabs to tab bar singleImageTabWidget = QtWidgets.QWidget() singleImageTabLayout = QtWidgets.QVBoxLayout(singleImageTabWidget) singleImageTabLayout.setContentsMargins(0, 0, 0, 0) self.singleImageTab = SingleImageTab(self, self.mainWindow, self.width) singleImageTabLayout.addWidget(self.singleImageTab) self.imageTabBar.addTab(singleImageTabWidget, "Single") imageSequenceTabWidget = QtWidgets.QWidget() imageSequenceTabLayout = QtWidgets.QVBoxLayout(imageSequenceTabWidget) imageSequenceTabLayout.setContentsMargins(0, 0, 0, 0) self.imageSequenceTab = ImageSequenceTab(self, self.mainWindow, self.width) imageSequenceTabLayout.addWidget(self.imageSequenceTab) self.imageTabBar.addTab(imageSequenceTabWidget, "Sequence") imageRotateTabWidget = QtWidgets.QWidget() imageRotateTabLayout = QtWidgets.QVBoxLayout(imageRotateTabWidget) imageRotateTabLayout.setContentsMargins(0, 0, 0, 0) self.imageRotateTab = ImageRotateTab(self, self.mainWindow, self.width) imageRotateTabLayout.addWidget(self.imageRotateTab) self.imageTabBar.addTab(imageRotateTabWidget, "Rotate") imageTabLayout.addWidget(self.imageTabBar) def setImageFormat(self, val): """ Set the image format. """ if self.JPEGCheck.isChecked(): self.imageFormat = "jpg" elif self.PNGCheck.isChecked(): self.imageFormat = "png" elif self.TIFFCheck.isChecked(): self.imageFormat = "tif" def setRenderType(self, val): """ Set current render type """ if self.POVButton.isChecked(): settings = self.mainWindow.preferences.povrayForm if not utilities.checkForExe(settings.pathToPovray): self.POVButton.setChecked(0) self.VTKButton.setChecked(1) utilities.warnExeNotFound(self, "%s (POV-Ray)" % (settings.pathToPovray,)) else: self.renderType = "POV" self.imageFormat = "png" self.PNGCheck.setChecked(1) elif self.VTKButton.isChecked(): self.renderType = "VTK" self.imageFormat = "jpg" self.JPEGCheck.setChecked(1) def createMovieLogger(self, level, message): """ Log message for create movie object """ logger = logging.getLogger(__name__ + ".MovieGenerator") method = getattr(logger, level, None) if method is not None: method(message) def createMovie(self, saveDir, inputText, createMovieBox, prefix=None): """ Create movie. """ settings = self.mainWindow.preferences.ffmpegForm ffmpeg = utilities.checkForExe(settings.pathToFFmpeg) if not ffmpeg: utilities.warnExeNotFound(self, "%s (FFmpeg)" % (settings.pathToFFmpeg,)) return 2 # settings settings = self.mainWindow.preferences.ffmpegForm framerate = createMovieBox.framerate bitrate = settings.bitrate if prefix is None: outputprefix = createMovieBox.prefix else: outputprefix = prefix outputprefix = os.path.join(saveDir, outputprefix) outputsuffix = createMovieBox.suffix self.logger.info("Creating movie file: %s.%s", outputprefix, outputsuffix) # movie generator object generator = MovieGenerator() generator.log.connect(self.createMovieLogger) generator.allDone.connect(generator.deleteLater) # runnable for sending to thread pool runnable = threading_vis.GenericRunnable(generator, args=(ffmpeg, framerate, inputText, self.imageFormat, bitrate, outputprefix, outputsuffix)) runnable.setAutoDelete(False) # add to thread pool QtCore.QThreadPool.globalInstance().start(runnable) # generator.run(ffmpeg, framerate, inputText, self.imageFormat, bitrate, outputprefix, outputsuffix) class MovieGenerator(QtCore.QObject): """ Call ffmpeg to generate a movie """ log = QtCore.Signal(str, str) allDone = QtCore.Signal() def __init__(self): super(MovieGenerator, self).__init__() def run(self, ffmpeg, framerate, saveText, imageFormat, bitrate, outputPrefix, outputSuffix): """ Create movie """ ffmpegTime = time.time() try: if outputSuffix == "mp4": # determine image size firstFile = "%s.%s" % (saveText, imageFormat) firstFile = firstFile % 0 self.log.emit("debug", "Checking first file size: '%s'" % firstFile) im = Image.open(firstFile) width, height = im.size self.log.emit("debug", "Image size: %s x %s" % (width, height)) # h264 requires width and height be divisible by 2 newWidth = width - 1 if width % 2 else width newHeight = height - 1 if height % 2 else height if newWidth != width: self.log.emit("debug", "Resizing image width: %d -> %d" % (width, newWidth)) if newHeight != height: self.log.emit("debug", "Resizing image height: %d -> %d" % (height, newHeight)) # construct command; scale if required if newWidth == width and newHeight == height: # no scaling required command = "'%s' -r %d -y -i %s.%s -c:v h264 -r %d -b:v %dk '%s.%s'" % (ffmpeg, framerate, saveText, imageFormat, 25, bitrate, outputPrefix, outputSuffix) else: # scaling required command = "'%s' -r %d -y -i %s.%s -vf scale=%d:%d -c:v h264 -r %d -b:v %dk '%s.%s'" % (ffmpeg, framerate, saveText, imageFormat, newWidth, newHeight, 25, bitrate, outputPrefix, outputSuffix) # run command self.log.emit("debug", 'Command: "%s"' % command) process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, stderr = process.communicate() status = process.poll() else: command = "'%s' -r %d -y -i %s.%s -r %d -b:v %dk '%s.%s'" % (ffmpeg, framerate, saveText, imageFormat, 25, bitrate, outputPrefix, outputSuffix) self.log.emit("debug", 'Command: "%s"' % command) process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, stderr = process.communicate() status = process.poll() if status: self.log.emit("error", "FFmpeg failed (%d)" % status) self.log.emit("error", output.decode('utf-8')) self.log.emit("error", stderr.decode('utf-8')) finally: ffmpegTime = time.time() - ffmpegTime self.log.emit("debug", "FFmpeg time taken: %f s" % ffmpegTime) self.allDone.emit() class SingleImageTab(QtWidgets.QWidget): def __init__(self, parent, mainWindow, width): super(SingleImageTab, self).__init__(parent) self.parent = parent self.mainWindow = mainWindow self.width = width self.rendererWindow = self.parent.rendererWindow # initial values self.overwriteImage = 0 self.openImage = 1 # layout mainLayout = QtWidgets.QVBoxLayout(self) # mainLayout.setContentsMargins(0, 0, 0, 0) # mainLayout.setSpacing(0) mainLayout.setAlignment(QtCore.Qt.AlignTop) # file name, save image button row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) label = QtWidgets.QLabel("File name") self.imageFileName = QtWidgets.QLineEdit("image") self.imageFileName.setFixedWidth(120) saveImageButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/document-save.png")), "") saveImageButton.setToolTip("Save image") saveImageButton.clicked.connect(functools.partial(self.saveSingleImage, True)) rowLayout.addWidget(label) rowLayout.addWidget(self.imageFileName) rowLayout.addWidget(saveImageButton) mainLayout.addWidget(row) # dialog row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) saveImageDialogButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath('oxygen/document-open.png')), "Save image") saveImageDialogButton.setToolTip("Save image") saveImageDialogButton.setCheckable(0) saveImageDialogButton.setFixedWidth(150) saveImageDialogButton.clicked.connect(self.saveSingleImageDialog) rowLayout.addWidget(saveImageDialogButton) mainLayout.addWidget(row) # options row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) self.overwriteCheck = QtWidgets.QCheckBox("Overwrite") self.overwriteCheck.stateChanged[int].connect(self.overwriteCheckChanged) self.openImageCheck = QtWidgets.QCheckBox("Open image") self.openImageCheck.setChecked(True) self.openImageCheck.stateChanged[int].connect(self.openImageCheckChanged) rowLayout.addWidget(self.overwriteCheck) rowLayout.addWidget(self.openImageCheck) mainLayout.addWidget(row) def saveSingleImageDialog(self): """ Open dialog to get save file name """ filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File', '.')[0][0] if len(filename): self.imageFileName.setText(str(filename)) self.saveSingleImage(showProgress=True) def saveSingleImage(self, showProgress=False): """ Screen capture. """ if self.parent.renderType == "POV": settings = self.mainWindow.preferences.povrayForm povray = utilities.checkForExe(settings.pathToPovray) if not povray: utilities.warnExeNotFound(self, "%s (POV-Ray)" % (settings.pathToPovray,)) return else: povray = "" filename = str(self.imageFileName.text()) if not len(filename): return # show progress dialog if showProgress and self.parent.renderType == "POV": progress = QtWidgets.QProgressDialog(parent=self) progress.setWindowModality(QtCore.Qt.WindowModal) progress.setWindowTitle("Busy") progress.setLabelText("Running POV-Ray...") progress.setRange(0, 0) progress.setMinimumDuration(0) QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) progress.show() filename = self.rendererWindow.renderer.saveImage(self.parent.renderType, self.parent.imageFormat, filename, self.overwriteImage, povray=povray) # hide progress dialog if showProgress and self.parent.renderType == "POV": QtWidgets.QApplication.restoreOverrideCursor() progress.cancel() if filename is None: print("SAVE IMAGE FAILED") return # open image viewer if self.openImage: dirname = os.path.dirname(filename) if not dirname: dirname = os.getcwd() self.mainWindow.imageViewer.changeDir(dirname) self.mainWindow.imageViewer.showImage(filename) self.mainWindow.imageViewer.hide() self.mainWindow.imageViewer.show() def openImageCheckChanged(self, val): """ Open image """ if self.openImageCheck.isChecked(): self.openImage = 1 else: self.openImage = 0 def overwriteCheckChanged(self, val): """ Overwrite file """ if self.overwriteCheck.isChecked(): self.overwriteImage = 1 else: self.overwriteImage = 0 class CreateMovieBox(QtWidgets.QGroupBox): """ Create movie settings """ def __init__(self, parent=None): super(CreateMovieBox, self).__init__(parent) self.setTitle("Create movie") self.setCheckable(True) self.setChecked(True) self.setAlignment(QtCore.Qt.AlignCenter) # defaults self.framerate = 10 self.prefix = "movie" self.suffix = "mp4" # layout self.contentLayout = QtWidgets.QVBoxLayout(self) self.contentLayout.setContentsMargins(0, 0, 0, 0) self.contentLayout.setSpacing(0) # framerate rowLayout = self.newRow() label = QtWidgets.QLabel("Framerate:") rowLayout.addWidget(label) framerateSpin = QtWidgets.QSpinBox() framerateSpin.setMinimum(1) framerateSpin.setMaximum(10000) framerateSpin.setValue(self.framerate) framerateSpin.valueChanged.connect(self.framerateChanged) rowLayout.addWidget(framerateSpin) label = QtWidgets.QLabel(" fps") rowLayout.addWidget(label) # file prefix rowLayout = self.newRow() label = QtWidgets.QLabel("File prefix:") rowLayout.addWidget(label) prefixLineEdit = QtWidgets.QLineEdit(self.prefix) prefixLineEdit.setFixedWidth(130) prefixLineEdit.textChanged.connect(self.prefixChanged) rowLayout.addWidget(prefixLineEdit) # container rowLayout = self.newRow() label = QtWidgets.QLabel("Container:") rowLayout.addWidget(label) containerCombo = QtWidgets.QComboBox() containerCombo.addItem("mp4") containerCombo.addItem("flv") containerCombo.addItem("mpg") containerCombo.addItem("avi") # containerCombo.addItem("mov") containerCombo.currentIndexChanged[str].connect(self.suffixChanged) rowLayout.addWidget(containerCombo) def suffixChanged(self, text): """ Suffix changed """ self.suffix = str(text) def framerateChanged(self, val): """ Framerate changed. """ self.framerate = val def prefixChanged(self, text): """ Prefix changed. """ self.prefix = str(text) def newRow(self, align=None): """ New row """ row = genericForm.FormRow(align=align) self.contentLayout.addWidget(row) return row class ImageSequenceTab(QtWidgets.QWidget): def __init__(self, parent, mainWindow, width): super(ImageSequenceTab, self).__init__(parent) self.parent = parent self.mainWindow = mainWindow self.width = width self.rendererWindow = self.parent.rendererWindow self.logger = logging.getLogger(__name__ + ".ImageSequenceTab") # initial values self.numberFormats = ["%04d", "%d"] self.numberFormat = self.numberFormats[0] self.minIndex = 0 self.maxIndex = -1 self.interval = 1 self.fileprefixText = "guess" self.overwrite = False self.flickerFlag = False self.rotateAfter = False # self.createMovie = 1 # layout mainLayout = QtWidgets.QVBoxLayout(self) # mainLayout.setContentsMargins(0, 0, 0, 0) # mainLayout.setSpacing(0) mainLayout.setAlignment(QtCore.Qt.AlignTop) # output directory row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) label = QtWidgets.QLabel("Output folder") self.outputFolder = QtWidgets.QLineEdit("sequencer") self.outputFolder.setFixedWidth(120) rowLayout.addWidget(label) rowLayout.addWidget(self.outputFolder) mainLayout.addWidget(row) # file prefix row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) label = QtWidgets.QLabel("File prefix") self.fileprefix = QtWidgets.QLineEdit(self.fileprefixText) self.fileprefix.setFixedWidth(120) self.fileprefix.textChanged[str].connect(self.fileprefixChanged) resetPrefixButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/edit-find.png")), "") resetPrefixButton.setStatusTip("Set prefix to input file") resetPrefixButton.setToolTip("Set prefix to input file") resetPrefixButton.clicked.connect(self.resetPrefix) rowLayout.addWidget(label) rowLayout.addWidget(self.fileprefix) rowLayout.addWidget(resetPrefixButton) mainLayout.addWidget(row) group = QtWidgets.QGroupBox("Numbering") group.setAlignment(QtCore.Qt.AlignHCenter) groupLayout = QtWidgets.QVBoxLayout(group) groupLayout.setContentsMargins(0, 0, 0, 0) groupLayout.setSpacing(0) # numbering format row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) # label = QtGui.QLabel("Number format") self.numberFormatCombo = QtWidgets.QComboBox() self.numberFormatCombo.addItems(self.numberFormats) self.numberFormatCombo.currentIndexChanged[str].connect(self.numberFormatChanged) # rowLayout.addWidget(label) rowLayout.addWidget(self.numberFormatCombo) groupLayout.addWidget(row) row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) self.minIndexSpinBox = QtWidgets.QSpinBox() self.minIndexSpinBox.setMinimum(0) self.minIndexSpinBox.setMaximum(99999) self.minIndexSpinBox.setValue(self.minIndex) self.minIndexSpinBox.valueChanged[int].connect(self.minIndexChanged) label = QtWidgets.QLabel("to") self.maxIndexSpinBox = QtWidgets.QSpinBox() self.maxIndexSpinBox.setMinimum(-1) self.maxIndexSpinBox.setMaximum(99999) self.maxIndexSpinBox.setValue(self.maxIndex) self.maxIndexSpinBox.valueChanged[int].connect(self.maxIndexChanged) self.maxIndexSpinBox.setToolTip("The max index (inclusive; if less than min index do all we can find)") label2 = QtWidgets.QLabel("by") self.intervalSpinBox = QtWidgets.QSpinBox() self.intervalSpinBox.setMinimum(1) self.intervalSpinBox.setMaximum(99999) self.intervalSpinBox.setValue(self.interval) self.intervalSpinBox.valueChanged[int].connect(self.intervalChanged) rowLayout.addWidget(self.minIndexSpinBox) rowLayout.addWidget(label) rowLayout.addWidget(self.maxIndexSpinBox) rowLayout.addWidget(label2) rowLayout.addWidget(self.intervalSpinBox) groupLayout.addWidget(row) mainLayout.addWidget(group) # first file row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) label = QtWidgets.QLabel("First file:") self.firstFileLabel = QtWidgets.QLabel("") self.setFirstFileLabel() rowLayout.addWidget(label) rowLayout.addWidget(self.firstFileLabel) mainLayout.addWidget(row) # overwrite check box # row = QtGui.QWidget(self) # rowLayout = QtGui.QHBoxLayout(row) # # rowLayout.setSpacing(0) # rowLayout.setContentsMargins(0, 0, 0, 0) # rowLayout.setAlignment(QtCore.Qt.AlignHCenter) # self.overwriteCheck = QtGui.QCheckBox("Overwrite") # self.overwriteCheck.stateChanged[int].connect(self.overwriteCheckChanged) # rowLayout.addWidget(self.overwriteCheck) # mainLayout.addWidget(row) # eliminate flicker check row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) self.flickerCheck = QtWidgets.QCheckBox("Eliminate flicker") self.flickerCheck.stateChanged[int].connect(self.flickerCheckChanged) rowLayout.addWidget(self.flickerCheck) # mainLayout.addWidget(row) # rotate at end # row = QtGui.QWidget(self) # rowLayout = QtGui.QHBoxLayout(row) # rowLayout.setContentsMargins(0, 0, 0, 0) # rowLayout.setAlignment(QtCore.Qt.AlignHCenter) rowLayout.addStretch() self.rotateAfterCheck = QtWidgets.QCheckBox("Rotate at end") self.rotateAfterCheck.stateChanged[int].connect(self.rotateAfterCheckChanged) rowLayout.addWidget(self.rotateAfterCheck) mainLayout.addWidget(row) # link to other renderer combo self.linkedRenderWindowIndex = None self.linkedRendererCombo = QtWidgets.QComboBox() self.linkedRendererCombo.currentIndexChanged[str].connect(self.linkedRendererChanged) row = QtWidgets.QHBoxLayout() row.setContentsMargins(0, 0, 0, 0) row.setAlignment(QtCore.Qt.AlignHCenter) row.addWidget(QtWidgets.QLabel("Linked render window:")) row.addWidget(self.linkedRendererCombo) mainLayout.addLayout(row) # populate self.linkedRendererCombo.addItem("<Off>") myrwi = self.rendererWindow.rendererIndex rws = [str(rw.rendererIndex) for rw in self.mainWindow.rendererWindows if rw.rendererIndex != myrwi] self.linkedRendererCombo.addItems(rws) # create movie box self.createMovieBox = CreateMovieBox(self) mainLayout.addWidget(self.createMovieBox) # start button row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) startSequencerButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/go-last.png")), "START") startSequencerButton.setStatusTip("Start sequencer") startSequencerButton.setToolTip("Start sequencer") startSequencerButton.clicked.connect(self.startSequencer) rowLayout.addWidget(startSequencerButton) mainLayout.addWidget(row) def refreshLinkedRenderers(self): """ Refresh the linked renderers combo """ self.logger.debug("Refreshing linked renderer options") # clear self.linkedRendererCombo.clear() self.linkedRenderWindowIndex = None # populate self.linkedRendererCombo.addItem("<Off>") myrwi = self.rendererWindow.rendererIndex rws = [str(rw.rendererIndex) for rw in self.mainWindow.rendererWindows if rw.rendererIndex != myrwi] assert len(self.mainWindow.rendererWindows) == len(rws) + 1 self.linkedRendererCombo.addItems(rws) def linkedRendererChanged(self, currentText): """ Linked renderer changed """ if self.linkedRendererCombo.currentIndex() > 0: index = int(currentText) rw2 = None for rwIndex, rw in enumerate(self.mainWindow.rendererWindows): if rw.rendererIndex == index: rw2 = rw break if rw2 is None: self.logger.error("Cannot find linked render window (%d)", index) self.linkedRenderWindowIndex = None return # do some checks if rw2.currentPipelineIndex == self.rendererWindow.currentPipelineIndex: if rw2.vtkRenWinInteract.size().height() == self.rendererWindow.vtkRenWinInteract.size().height(): self.linkedRenderWindowIndex = rwIndex return rw2 else: self.logger.error("Cannot select linked render window %d; heights do not match", index) self.linkedRendererCombo.setCurrentIndex(0) else: self.logger.error("Cannote select linked render window %d; cannot handle different pipelines yet (ask me...)", index) self.linkedRendererCombo.setCurrentIndex(0) else: self.linkedRenderWindowIndex = None def rotateAfterCheckChanged(self, state): """ Rotate after sequencer changed """ if state == QtCore.Qt.Unchecked: self.rotateAfter = False else: self.rotateAfter = True def resetPrefix(self): """ Reset the prefix to the one from the input page """ pp = self.rendererWindow.getCurrentPipelinePage() if pp is None: filename = "" else: filename = pp.filename guess = self.guessFilePrefix(filename) self.fileprefix.setText(guess) def guessFilePrefix(self, filename): """ Guess the file prefix """ count = 0 lim = None for i in range(len(filename)): if filename[i] == ".": break try: int(filename[i]) if lim is None: lim = count except ValueError: lim = None count += 1 if lim is None: array = os.path.splitext(filename) if array[1] == '.gz' or array[1] == '.bz2': array = os.path.splitext(array[0]) filename = array[0] else: filename = filename[:lim] return filename def startSequencer(self): """ Start the sequencer """ self.runSequencer() def runSequencer(self): """ Run the sequencer """ self.logger.info("Running sequencer") if self.parent.renderType == "POV": settings = self.mainWindow.preferences.povrayForm povray = utilities.checkForExe(settings.pathToPovray) if not povray: utilities.warnExeNotFound(self, "%s (POV-Ray)" % (settings.pathToPovray,)) return else: povray = "" self.setFirstFileLabel() # get pipeline page pipelinePage = self.rendererWindow.getCurrentPipelinePage() # check this is not a generated system if pipelinePage.fileFormat is None: self.logger.error("Cannot sequence a generated file") self.mainWindow.displayError("Cannot sequence a generated file") return # formatted string fileText = "%s%s%s" % (str(self.fileprefix.text()), self.numberFormat, pipelinePage.extension) # check abspath (for sftp) abspath = pipelinePage.abspath sftpBrowser = None if pipelinePage.fromSFTP: self.logger.debug("Sequencing SFTP file: '%s'", abspath) array = abspath.split(":") sftpHost = array[0] # handle case where ":"'s are in the file path sftpFile = ":".join(array[1:]) self.logger.debug("Host: '%s'; path: '%s'", sftpHost, sftpFile) sysDiag = self.mainWindow.systemsDialog sftpDlg = sysDiag.load_system_form.sftp_browser match = False for i in range(sftpDlg.stackedWidget.count()): w = sftpDlg.stackedWidget.widget(i) if w.connectionID == sftpHost: match = True break if not match: self.logger.error("Could not find SFTP browser for '%s'", sftpHost) return # browser sftpBrowser = w # check first file exists if sftpBrowser is None: firstFileExists = utilities.checkForFile(str(self.firstFileLabel.text())) else: rp = os.path.join(os.path.dirname(sftpFile), str(self.firstFileLabel.text())) self.logger.debug("Checking first file exists (SFTP): '%s'", rp) firstFileExists = bool(sftpBrowser.checkPathExists(rp)) or bool(sftpBrowser.checkPathExists(rp+".gz")) or bool(sftpBrowser.checkPathExists(rp+".bz2")) if not firstFileExists: self.warnFileNotPresent(str(self.firstFileLabel.text()), tag="first") return # check last file exists if self.maxIndex > self.minIndex: lastFile = fileText % self.maxIndex if sftpBrowser is None: lastFileExists = utilities.checkForFile(lastFile) else: rp = os.path.join(os.path.dirname(sftpFile), lastFile) self.logger.debug("Checking last file exists (SFTP): '%s'", rp) lastFileExists = bool(sftpBrowser.checkPathExists(rp)) or bool(sftpBrowser.checkPathExists(rp+".gz")) or bool(sftpBrowser.checkPathExists(rp+".bz2")) if not lastFileExists: self.warnFileNotPresent(lastFile, tag="last") return maxIndex = self.maxIndex else: # find greatest file self.logger.info("Auto-detecting last sequencer file") lastIndex = self.minIndex lastFile = fileText % lastIndex if sftpBrowser is None: def _checkForLastFile(fn): return utilities.checkForFile(fn) else: def _checkForLastFile(fn): rp = os.path.join(os.path.dirname(sftpFile), lastFile) return bool(sftpBrowser.checkPathExists(rp)) or bool(sftpBrowser.checkPathExists(rp+".gz")) or bool(sftpBrowser.checkPathExists(rp+".bz2")) while _checkForLastFile(lastFile): lastIndex += 1 lastFile = fileText % lastIndex lastIndex -= 1 lastFile = fileText % lastIndex maxIndex = lastIndex self.logger.info("Last file detected as: '%s'", lastFile) # store current input state origInput = copy.deepcopy(self.rendererWindow.getCurrentInputState()) # pipeline index pipelineIndex = self.rendererWindow.currentPipelineIndex # systems dialog systemsDialog = self.mainWindow.systemsDialog loadPage = systemsDialog.load_system_form # reader readerForm = loadPage.readerForm reader = readerForm.latticeReader self.logger.debug(" Reader: %s %s", str(readerForm), str(reader)) # directory saveDir = str(self.outputFolder.text()) saveDir += "-%s" % datetime.datetime.now().strftime("%y%m%d-%H%M%S") if os.path.exists(saveDir): if self.overwrite: shutil.rmtree(saveDir) else: count = 0 while os.path.exists(saveDir): count += 1 saveDir = "%s.%d" % (str(self.outputFolder.text()), count) os.mkdir(saveDir) saveText = os.path.join(saveDir, "%s%s" % (str(self.fileprefix.text()), self.numberFormat)) # check if linked rw2 = None if self.linkedRenderWindowIndex is not None: # make sure still ok to use this index rw2 = self.linkedRendererChanged(self.linkedRendererCombo.currentText()) if rw2 is not None: saveText2 = saveText + "_2" # progress dialog NSteps = int((maxIndex - self.minIndex) / self.interval) + 1 progDialog = QtWidgets.QProgressDialog("Running sequencer...", "Cancel", self.minIndex, NSteps) progDialog.setWindowModality(QtCore.Qt.WindowModal) progDialog.setWindowTitle("Progress") progDialog.setValue(self.minIndex) progDialog.show() QtWidgets.QApplication.processEvents() # loop over files status = 0 previousPos = None try: count = 0 for i in range(self.minIndex, maxIndex + self.interval, self.interval): if sftpBrowser is None: currentFile = fileText % i self.logger.info("Current file: '%s'", currentFile) else: # we have to copy current file locally and use that, then delete it afterwards basename = fileText % i remoteFile = os.path.join(os.path.dirname(sftpFile), basename) currentFile = os.path.join(self.mainWindow.tmpDirectory, basename) # check exists remoteFileTest = remoteFile fileExists = bool(sftpBrowser.checkPathExists(remoteFileTest)) if not fileExists: # check gzip remoteFileTest = remoteFile + ".gz" fileExists = bool(sftpBrowser.checkPathExists(remoteFileTest)) if fileExists: currentFile += ".gz" else: # check bzip remoteFileTest = remoteFile + ".bz2" fileExists = bool(sftpBrowser.checkPathExists(remoteFileTest)) if fileExists: currentFile += ".bz2" else: self.logger.error("SFTP sequencer file does not exist: '%s'", remoteFile) return remoteFile = remoteFileTest # copy locally self.logger.debug("Copying file for sequencer: '%s' to '%s'", remoteFile, currentFile) # copy file and roulette if exists.., sftpBrowser.copySystem(remoteFile, currentFile) # read in state status, state = reader.readFile(currentFile, pipelinePage.fileFormat, rouletteIndex=i-1, linkedLattice=pipelinePage.linkedLattice) if status: self.logger.error("Sequencer read file failed with status: %d" % status) break # eliminate flicker across PBCs if self.flickerFlag: self.eliminateFlicker(state, previousPos, pipelinePage) previousPos = copy.deepcopy(state.pos) # set PBCs the same state.PBC[:] = origInput.PBC[:] # attempt to read any scalars/vectors files for vectorsName, vectorsFile in six.iteritems(origInput.vectorsFiles): self.logger.debug("Sequencer checking vectors file: '%s'", vectorsFile) vdn, vbn = os.path.split(vectorsFile) # guess prefix guessvfn = self.guessFilePrefix(vbn) if guessvfn != vbn: ext = "." + vbn.split(".")[-1] if ext == vbn: ext = "" vfn = "%s%s%s" % (guessvfn, self.numberFormat, ext) if len(vdn): vfn = os.path.join(vdn, vfn) vfn = vfn % i self.logger.debug("Looking for vectors file: '%s' (%s)", vfn, os.path.exists(vfn)) if os.path.exists(vfn): # read vectors file ok = True with open(vfn) as f: vectors = [] try: for line in f: array = line.split() array[0] = float(array[0]) array[1] = float(array[1]) array[2] = float(array[2]) vectors.append(array) except: self.logger.error("Error reading vector file") ok = False if ok and len(vectors) != state.NAtoms: self.logger.error("The vector data is the wrong length") ok = False if ok: # convert to numpy array vectors = np.asarray(vectors, dtype=np.float64) assert vectors.shape[0] == state.NAtoms and vectors.shape[1] == 3 state.vectorsDict[vectorsName] = vectors state.vectorsFiles[vectorsName] = vfn self.logger.debug("Added vectors data (%s) to sequencer lattice", vectorsName) # set input state on current pipeline pipelinePage.inputState = state # exit if cancelled if progDialog.wasCanceled(): if sftpBrowser is not None: os.unlink(currentFile) return # now apply all filters pipelinePage.runAllFilterLists(sequencer=True) # exit if cancelled if progDialog.wasCanceled(): if sftpBrowser is not None: os.unlink(currentFile) return saveName = saveText % count self.logger.info(" Saving image: '%s'", saveName) # now save image filename = self.rendererWindow.renderer.saveImage(self.parent.renderType, self.parent.imageFormat, saveName, 1, povray=povray) # linked image if rw2 is not None: saveName2 = saveText2 % count self.logger.info(" Saving linked image: '%s'", saveName2) filename2 = rw2.renderer.saveImage(self.parent.renderType, self.parent.imageFormat, saveName2, 1, povray=povray) # merge the files mergeFn = os.path.join(saveDir, "merge%d.%s" % (i, self.parent.imageFormat)) self.logger.debug("Merging the files together: '%s'", mergeFn) # read images im1 = Image.open(filename) im2 = Image.open(filename2) assert im1.size[1] == im2.size[1], "Image sizes do not match: %r != %r" % (im1.size, im2.size) # new empty image newSize = (im1.size[0] + im2.size[0], im1.size[1]) newIm = Image.new('RGB', newSize) # paste images newIm.paste(im1, (0, 0)) newIm.paste(im2, (im1.size[0], 0)) # save newIm.save(mergeFn) # increment output counter count += 1 # exit if cancelled if progDialog.wasCanceled(): if sftpBrowser is not None: os.unlink(currentFile) return # delete local copy of file (SFTP) if sftpBrowser is not None: os.unlink(currentFile) # update progress progDialog.setValue(count) QtWidgets.QApplication.processEvents() # create movie if not status and self.createMovieBox.isChecked(): # show wait cursor # QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) try: self.parent.createMovie(saveDir, saveText, self.createMovieBox) if rw2 is not None: self.parent.createMovie(saveDir, os.path.join(saveDir, "merge%d"), self.createMovieBox, prefix="merged") finally: # set cursor to normal # QtGui.QApplication.restoreOverrideCursor() pass # rotate? if self.rotateAfter: self.logger.debug("Running rotator after sequencer...") self.parent.imageRotateTab.startRotator() finally: self.logger.debug("Reloading original input") # reload original input pipelinePage.inputState = origInput pipelinePage.postInputLoaded() # run filter list if didn't auto run if origInput.NAtoms > self.mainWindow.preferences.renderingForm.maxAtomsAutoRun: pipelinePage.runAllFilterLists() # close progress dialog progDialog.close() def eliminateFlicker(self, state, previousPos, pipelinePage): """ Attempt to eliminate flicker across PBCs """ if previousPos is None: return pbc = pipelinePage.PBC if not pbc[0] and not pbc[1] and not pbc[2]: return logger = self.logger logger.debug("Attempting to eliminate PBC flicker") if len(previousPos) < len(state.pos): prevNAtoms = len(previousPos)/3 count = vectors_c.eliminatePBCFlicker(prevNAtoms, state.pos, previousPos, state.cellDims, pbc) else: count = vectors_c.eliminatePBCFlicker(state.NAtoms, state.pos, previousPos, state.cellDims, pbc) logger.debug("Modified: %d", count) def warnFileNotPresent(self, filename, tag="first"): """ Warn the first file is not present. """ # QtGui.QMessageBox.warning(self, "Warning", "Could not locate %s file in sequence: %s" % (tag, filename)) message = "Could not locate %s file in sequence: %s" % (tag, filename) msgBox = QtWidgets.QMessageBox(self) msgBox.setText(message) msgBox.setWindowFlags(msgBox.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgBox.setIcon(QtWidgets.QMessageBox.Warning) msgBox.exec_() def flickerCheckChanged(self, state): """ Flicker check changed """ if state == QtCore.Qt.Unchecked: self.flickerFlag = False else: self.flickerFlag = True def overwriteCheckChanged(self, val): """ Overwrite check changed """ if self.overwriteCheck.isChecked(): self.overwrite = 1 else: self.overwrite = 0 def fileprefixChanged(self, text): """ File prefix has changed """ self.fileprefixText = str(text) self.setFirstFileLabel() def setFirstFileLabel(self): """ Set the first file label """ pp = self.rendererWindow.getCurrentPipelinePage() if pp is None: ext = "" else: ext = pp.extension text = "%s%s%s" % (self.fileprefix.text(), self.numberFormat, ext) foundFormat = False testfn = text % self.minIndex if not (os.path.isfile(testfn) or os.path.isfile(testfn+'.gz') or os.path.isfile(testfn+'.bz2')): self.logger.debug("First file does not exist; checking other number formats") for i, nfmt in enumerate(self.numberFormats): if nfmt == self.numberFormat: continue testText = "%s%s%s" % (self.fileprefix.text(), nfmt, ext) testfn = testText % self.minIndex if os.path.isfile(testfn) or os.path.isfile(testfn+'.gz') or os.path.isfile(testfn+'.bz2'): foundFormat = True break if foundFormat: self.logger.debug("Found suitable number format: '%s'", nfmt) self.numberFormatCombo.setCurrentIndex(i) if not foundFormat: self.firstFileLabel.setText(text % (self.minIndex,)) def minIndexChanged(self, val): """ Minimum index changed """ self.minIndex = val self.setFirstFileLabel() def maxIndexChanged(self, val): """ Maximum index changed """ self.maxIndex = val def intervalChanged(self, val): """ Interval changed """ self.interval = val def numberFormatChanged(self, text): """ Change number format """ self.numberFormat = str(text) self.setFirstFileLabel() ################################################################################ class ImageRotateTab(QtWidgets.QWidget): def __init__(self, parent, mainWindow, width): super(ImageRotateTab, self).__init__(parent) self.parent = parent self.mainWindow = mainWindow self.width = width self.rendererWindow = self.parent.rendererWindow # initial values self.fileprefixText = "rotate" self.overwrite = 0 self.degreesPerRotation = 5.0 self.logger = logging.getLogger(__name__+".ImageRotateTab") # layout mainLayout = QtWidgets.QVBoxLayout(self) # mainLayout.setContentsMargins(0, 0, 0, 0) # mainLayout.setSpacing(0) mainLayout.setAlignment(QtCore.Qt.AlignTop) # output directory row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) label = QtWidgets.QLabel("Output folder") self.outputFolder = QtWidgets.QLineEdit("rotate") self.outputFolder.setFixedWidth(120) rowLayout.addWidget(label) rowLayout.addWidget(self.outputFolder) mainLayout.addWidget(row) # file prefix row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) label = QtWidgets.QLabel("File prefix") self.fileprefix = QtWidgets.QLineEdit(self.fileprefixText) self.fileprefix.setFixedWidth(120) self.fileprefix.textChanged[str].connect(self.fileprefixChanged) rowLayout.addWidget(label) rowLayout.addWidget(self.fileprefix) mainLayout.addWidget(row) # degrees per rotation label = QtWidgets.QLabel("Degrees per rotation") degPerRotSpinBox = QtWidgets.QSpinBox(self) degPerRotSpinBox.setMinimum(1) degPerRotSpinBox.setMaximum(360) degPerRotSpinBox.setValue(self.degreesPerRotation) degPerRotSpinBox.valueChanged.connect(self.degPerRotChanged) row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) rowLayout.addWidget(label) rowLayout.addWidget(degPerRotSpinBox) mainLayout.addWidget(row) # overwrite check box row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) self.overwriteCheck = QtWidgets.QCheckBox("Overwrite") self.overwriteCheck.stateChanged[int].connect(self.overwriteCheckChanged) rowLayout.addWidget(self.overwriteCheck) mainLayout.addWidget(row) # create movie box self.createMovieBox = CreateMovieBox(self) mainLayout.addWidget(self.createMovieBox) # start button row = QtWidgets.QWidget(self) rowLayout = QtWidgets.QHBoxLayout(row) # rowLayout.setSpacing(0) rowLayout.setContentsMargins(0, 0, 0, 0) rowLayout.setAlignment(QtCore.Qt.AlignHCenter) startRotatorButton = QtWidgets.QPushButton(QtGui.QIcon(iconPath("oxygen/go-last.png")), "START") startRotatorButton.setToolTip("Start sequencer") startRotatorButton.clicked.connect(self.startRotator) rowLayout.addWidget(startRotatorButton) mainLayout.addWidget(row) def startRotator(self): """ Start the rotator. """ if self.parent.renderType == "POV": settings = self.mainWindow.preferences.povrayForm povray = utilities.checkForExe(settings.pathToPovray) if not povray: utilities.warnExeNotFound(self, "%s (POV-Ray)" % (settings.pathToPovray,)) return else: povray = "" self.logger.debug("Running rotator") # directory saveDir = str(self.outputFolder.text()) saveDir += "-%s" % datetime.datetime.now().strftime("%y%m%d-%H%M%S") if os.path.exists(saveDir): if self.overwrite: shutil.rmtree(saveDir) else: count = 0 while os.path.exists(saveDir): count += 1 saveDir = "%s.%d" % (str(self.outputFolder.text()), count) os.mkdir(saveDir) # file name prefix fileprefix = os.path.join(saveDir, str(self.fileprefix.text())) # send to renderer status = self.rendererWindow.renderer.rotateAndSaveImage(self.parent.renderType, self.parent.imageFormat, fileprefix, 1, self.degreesPerRotation, povray=povray) # movie? if status: print("ERROR: rotate failed") else: # create movie if self.createMovieBox.isChecked(): # show wait cursor QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) try: saveText = os.path.join(saveDir, "%s%s" % (str(self.fileprefix.text()), "%d")) self.parent.createMovie(saveDir, saveText, self.createMovieBox) finally: # set cursor to normal QtWidgets.QApplication.restoreOverrideCursor() def degPerRotChanged(self, val): """ Degrees per rotation changed. """ self.degreesPerRotation = val def overwriteCheckChanged(self, val): """ Overwrite check changed """ if self.overwriteCheck.isChecked(): self.overwrite = 1 else: self.overwrite = 0 def fileprefixChanged(self, text): """ File prefix has changed """ self.fileprefixText = str(text)
chrisdjscott/Atoman
atoman/gui/outputDialog.py
Python
mit
83,383
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import logging import os import pkg_resources import sys import ConfigParser from paste.deploy import loadapp, loadwsgi SERVER = loadwsgi.SERVER from gunicorn.app.base import Application from gunicorn.config import Config class PasterBaseApplication(Application): def app_config(self): cx = loadwsgi.loadcontext(SERVER, self.cfgurl, relative_to=self.relpath) gc, lc = cx.global_conf.copy(), cx.local_conf.copy() cfg = {} host, port = lc.pop('host', ''), lc.pop('port', '') if host and port: cfg['bind'] = '%s:%s' % (host, port) elif host: cfg['bind'] = host cfg['workers'] = int(lc.get('workers', 1)) cfg['umask'] = int(lc.get('umask', 0)) cfg['default_proc_name'] = gc.get('__file__') for k, v in gc.items(): if k not in self.cfg.settings: continue cfg[k] = v for k, v in lc.items(): if k not in self.cfg.settings: continue cfg[k] = v return cfg def configure_logging(self): if hasattr(self, "cfgfname"): self.logger = logging.getLogger('gunicorn') # from paste.script.command parser = ConfigParser.ConfigParser() parser.read([self.cfgfname]) if parser.has_section('loggers'): if sys.version_info >= (2, 6): from logging.config import fileConfig else: # Use our custom fileConfig -- 2.5.1's with a custom Formatter class # and less strict whitespace (which were incorporated into 2.6's) from gunicorn.logging_config import fileConfig config_file = os.path.abspath(self.cfgfname) fileConfig(config_file, dict(__file__=config_file, here=os.path.dirname(config_file))) return super(PasterBaseApplication, self).configure_logging() class PasterApplication(PasterBaseApplication): def init(self, parser, opts, args): if len(args) != 1: parser.error("No application name specified.") cfgfname = os.path.normpath(os.path.join(os.getcwd(), args[0])) cfgfname = os.path.abspath(cfgfname) if not os.path.exists(cfgfname): parser.error("Config file not found: %s" % cfgfname) self.cfgurl = 'config:%s' % cfgfname self.relpath = os.path.dirname(cfgfname) self.cfgfname = cfgfname sys.path.insert(0, self.relpath) pkg_resources.working_set.add_entry(self.relpath) return self.app_config() def load(self): return loadapp(self.cfgurl, relative_to=self.relpath) class PasterServerApplication(PasterBaseApplication): def __init__(self, app, gcfg=None, host="127.0.0.1", port=None, *args, **kwargs): self.cfg = Config() self.app = app self.callable = None gcfg = gcfg or {} cfgfname = gcfg.get("__file__") if cfgfname is not None: self.cfgurl = 'config:%s' % cfgfname self.relpath = os.path.dirname(cfgfname) self.cfgfname = cfgfname cfg = kwargs.copy() if port and not host.startswith("unix:"): bind = "%s:%s" % (host, port) else: bind = host cfg["bind"] = bind if gcfg: for k, v in gcfg.items(): cfg[k] = v cfg["default_proc_name"] = cfg['__file__'] try: for k, v in cfg.items(): if k.lower() in self.cfg.settings and v is not None: self.cfg.set(k.lower(), v) except Exception, e: sys.stderr.write("\nConfig error: %s\n" % str(e)) sys.stderr.flush() sys.exit(1) self.configure_logging() def load_config(self): if not hasattr(self, "cfgfname"): return cfg = self.app_config() for k,v in cfg.items(): try: self.cfg.set(k.lower(), v) except: sys.stderr.write("Invalid value for %s: %s\n\n" % (k, v)) raise def load(self): if hasattr(self, "cfgfname"): return loadapp(self.cfgurl, relative_to=self.relpath) return self.app def run(): """\ The ``gunicorn_paster`` command for launcing Paster compatible apllications like Pylons or Turbogears2 """ from gunicorn.app.pasterapp import PasterApplication PasterApplication("%prog [OPTIONS] pasteconfig.ini").run() def paste_server(app, gcfg=None, host="127.0.0.1", port=None, *args, **kwargs): """\ A paster server. Then entry point in your paster ini file should looks like this: [server:main] use = egg:gunicorn#main host = 127.0.0.1 port = 5000 """ from gunicorn.app.pasterapp import PasterServerApplication PasterServerApplication(app, gcfg=gcfg, host=host, port=port, *args, **kwargs).run()
pschanely/gunicorn
gunicorn/app/pasterapp.py
Python
mit
5,258
#!/usr/bin/env python from flask import Flask, jsonify, request, abort, render_template app = Flask(__name__) @app.route("/",methods=['GET']) def index(): if request.method == 'GET': return render_template('index.html') else: abort(400) @app.route("/devices",methods=['GET']) def devices(): if request.method == 'GET': return render_template('devices.html') else: abort(400) if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0')
mattiasgiese/squeezie
app/master.py
Python
mit
476
''' Stores syntax file from last activated view and reuses this for a new view. @author: Oktay Acikalin <ok@ryotic.de> @license: MIT (http://www.opensource.org/licenses/mit-license.php) @since: 2011-03-05 @todo: Remove odd workaround below when/if "on_deactivated", "on_new" and "on_activated" events get fired in correct order. ''' import sublime_plugin class NewFileSyntaxListener(sublime_plugin.EventListener): def __init__(self, *args, **kwargs): super(NewFileSyntaxListener, self).__init__(*args, **kwargs) self.last_syntax = None self.new_buffers = [] def on_new(self, view): # print 'on_new', self.last_syntax, view.buffer_id() self.new_buffers.append(view.buffer_id()) def on_activated(self, view): # print 'on_activated', self.last_syntax, view.buffer_id() if view.buffer_id() in self.new_buffers: if self.last_syntax: view.set_syntax_file(self.last_syntax) self.new_buffers.remove(view.buffer_id()) def on_deactivated(self, view): # print 'on_deactivated', self.last_syntax, view.buffer_id() if view.buffer_id() not in self.new_buffers: self.last_syntax = view.settings().get('syntax')
nashby/sublime_config
new_file_syntax.py
Python
mit
1,254
import numpy as np from Other_samples.testCases import * from Other_samples.Gradient_check.gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, \ gradients_to_vector def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x) Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: J -- the value of function J, computed using the formula J(theta) = theta * x """ J = theta * x return J x, theta = 2, 4 J = forward_propagation(x, theta) print("J = " + str(J)) def backward_propagation(x, theta): """ Computes the derivative of J with respect to theta (see Figure 1). Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: dtheta -- the gradient of the cost with respect to theta """ dtheta = x return dtheta x, theta = 2, 4 dtheta = backward_propagation(x, theta) print("dtheta = " + str(dtheta)) def gradient_check(x, theta, epsilon=1e-7): """ Implement the backward propagation presented in Figure 1. Arguments: x -- a real-valued input theta -- our parameter, a real number as well epsilon -- tiny shift to the input to compute approximated gradient with formula(1) Returns: difference -- difference (2) between the approximated gradient and the backward propagation gradient """ thetaplus = theta + epsilon # Step 1 thetaminus = theta - epsilon # Step 2 J_plus = forward_propagation(x, thetaplus) # Step 3 J_minus = forward_propagation(x, thetaminus) # Step 4 gradapprox = (J_plus - J_minus) / (2 * epsilon) # Step 5 grad = backward_propagation(x, gradapprox) numerator = np.linalg.norm(grad - gradapprox) # Step 1' denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2' difference = numerator / denominator # Step 3' if difference < 1e-7: print("The gradient is correct!") else: print("The gradient is wrong!") return difference x, theta = 2, 4 difference = gradient_check(x, theta) print("difference = " + str(difference)) def forward_propagation_n(X, Y, parameters): """ Implements the forward propagation (and computes the cost) presented in Figure 3. Arguments: X -- training set for m examples Y -- labels for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": W1 -- weight matrix of shape (5, 4) b1 -- bias vector of shape (5, 1) W2 -- weight matrix of shape (3, 5) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector of shape (1, 1) Returns: cost -- the cost function (logistic cost for one example) """ # retrieve parameters m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) # Cost logprobs = np.multiply(-np.log(A3), Y) + np.multiply(-np.log(1 - A3), 1 - Y) cost = 1. / m * np.sum(logprobs) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) return cost, cache def backward_propagation_n(X, Y, cache): """ Implement the backward propagation presented in figure 2. Arguments: X -- input datapoint, of shape (input size, 1) Y -- true "label" cache -- cache output from forward_propagation_n() Returns: gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables. """ m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y dW3 = 1. / m * np.dot(dZ3, A2.T) db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True) dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) dW2 = 1. / m * np.dot(dZ2, A1.T) db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = 1. / m * np.dot(dZ1, X.T) db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7): """ Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. x -- input datapoint, of shape (input size, 1) y -- true "label" epsilon -- tiny shift to the input to compute approximated gradient with formula(1) Returns: difference -- difference (2) between the approximated gradient and the backward propagation gradient """ # Set-up variables parameters_values, _ = dictionary_to_vector(parameters) grad = gradients_to_vector(gradients) num_parameters = parameters_values.shape[0] J_plus = np.zeros((num_parameters, 1)) J_minus = np.zeros((num_parameters, 1)) gradapprox = np.zeros((num_parameters, 1)) # Compute gradapprox for i in range(num_parameters): thetaplus = np.copy(parameters_values) # Step 1 thetaplus[i][0] = thetaplus[i] + epsilon # Step 2 J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Step 3 thetaminus = np.copy(parameters_values) # Step 1 thetaminus[i][0] = thetaminus[i] - epsilon # Step 2 J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Step 3 gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon) numerator = np.linalg.norm(grad - gradapprox) # Step 1' denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2' difference = numerator / denominator # Step 3' if difference > 1e-7: print( "\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m") else: print( "\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m") return difference X, Y, parameters = gradient_check_n_test_case() cost, cache = forward_propagation_n(X, Y, parameters) gradients = backward_propagation_n(X, Y, cache) difference = gradient_check_n(parameters, gradients, X, Y)
adexin/Python-Machine-Learning-Samples
Other_samples/Gradient_check/gradient_check.py
Python
mit
7,033
"""Axis class and associated.""" # --- import -------------------------------------------------------------------------------------- import re import numexpr import operator import functools import numpy as np from .. import exceptions as wt_exceptions from .. import kit as wt_kit from .. import units as wt_units # --- define -------------------------------------------------------------------------------------- __all__ = ["Axis"] operator_to_identifier = {} operator_to_identifier["/"] = "__d__" operator_to_identifier["="] = "__e__" operator_to_identifier["-"] = "__m__" operator_to_identifier["+"] = "__p__" operator_to_identifier["*"] = "__t__" identifier_to_operator = {value: key for key, value in operator_to_identifier.items()} operators = "".join(operator_to_identifier.keys()) # --- class --------------------------------------------------------------------------------------- class Axis(object): """Axis class.""" def __init__(self, parent, expression, units=None): """Data axis. Parameters ---------- parent : WrightTools.Data Parent data object. expression : string Axis expression. units : string (optional) Axis units. Default is None. """ self.parent = parent self.expression = expression if units is None: self.units = self.variables[0].units else: self.units = units def __getitem__(self, index): vs = {} for variable in self.variables: arr = variable[index] vs[variable.natural_name] = wt_units.converter(arr, variable.units, self.units) return numexpr.evaluate(self.expression.split("=")[0], local_dict=vs) def __repr__(self) -> str: return "<WrightTools.Axis {0} ({1}) at {2}>".format( self.expression, str(self.units), id(self) ) @property def _leaf(self): out = self.expression if self.units is not None: out += " ({0})".format(self.units) out += " {0}".format(self.shape) return out @property def full(self) -> np.ndarray: """Axis expression evaluated and repeated to match the shape of the parent data object.""" arr = self[:] for i in range(arr.ndim): if arr.shape[i] == 1: arr = np.repeat(arr, self.parent.shape[i], axis=i) return arr @property def identity(self) -> str: """Complete identifier written to disk in data.attrs['axes'].""" return self.expression + " {%s}" % self.units @property def label(self) -> str: """A latex formatted label representing axis expression.""" label = self.expression.replace("_", "\\;") if self.units_kind: symbol = wt_units.get_symbol(self.units) if symbol is not None: for v in self.variables: vl = "%s_{%s}" % (symbol, v.label) vl = vl.replace("_{}", "") # label can be empty, no empty subscripts label = label.replace(v.natural_name, vl) label += rf"\,\left({wt_units.ureg.Unit(self.units):~}\right)" label = r"$\mathsf{%s}$" % label return label @property def natural_name(self) -> str: """Valid python identifier representation of the expession.""" name = self.expression.strip() for op in operators: name = name.replace(op, operator_to_identifier[op]) return wt_kit.string2identifier(name) @property def ndim(self) -> int: """Get number of dimensions.""" try: assert self._ndim is not None except (AssertionError, AttributeError): self._ndim = self.variables[0].ndim finally: return self._ndim @property def points(self) -> np.ndarray: """Squeezed array.""" return np.squeeze(self[:]) @property def shape(self) -> tuple: """Shape.""" return wt_kit.joint_shape(*self.variables) @property def size(self) -> int: """Size.""" return functools.reduce(operator.mul, self.shape) @property def units(self): return self._units @units.setter def units(self, value): if value == "None": value = None if value is not None and value not in wt_units.ureg: raise ValueError(f"'{value}' is not in the unit registry") self._units = value @property def units_kind(self) -> str: """Units kind.""" return wt_units.kind(self.units) @property def variables(self) -> list: """Variables.""" try: assert self._variables is not None except (AssertionError, AttributeError): pattern = "|".join(map(re.escape, operators)) keys = re.split(pattern, self.expression) indices = [] for key in keys: if key in self.parent.variable_names: indices.append(self.parent.variable_names.index(key)) self._variables = [self.parent.variables[i] for i in indices] finally: return self._variables @property def masked(self) -> np.ndarray: """Axis expression evaluated, and masked with NaN shared from data channels.""" arr = self[:] arr.shape = self.shape arr = wt_kit.share_nans(arr, *self.parent.channels)[0] return np.nanmean( arr, keepdims=True, axis=tuple(i for i in range(self.ndim) if self.shape[i] == 1) ) def convert(self, destination_units, *, convert_variables=False): """Convert axis to destination_units. Parameters ---------- destination_units : string Destination units. convert_variables : boolean (optional) Toggle conversion of stored arrays. Default is False. """ if self.units is None and (destination_units is None or destination_units == "None"): return if not wt_units.is_valid_conversion(self.units, destination_units): valid = wt_units.get_valid_conversions(self.units) raise wt_exceptions.UnitsError(valid, destination_units) if convert_variables: for v in self.variables: v.convert(destination_units) self.units = destination_units self.parent._on_axes_updated() def max(self): """Axis max.""" return np.nanmax(self[:]) def min(self): """Axis min.""" return np.nanmin(self[:])
wright-group/WrightTools
WrightTools/data/_axis.py
Python
mit
6,659
# -*- coding: utf-8 -*- # # Speedcurve.py documentation build configuration file, created by # sphinx-quickstart on Mon Nov 16 12:29:28 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex import sphinx.environment from docutils.utils import get_source_line def _warn_node(self, msg, node): if not msg.startswith('nonlocal image URI found:'): self._warnfunc(msg, '%s:%s' % get_source_line(node)) sphinx.environment.BuildEnvironment.warn_node = _warn_node # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Speedcurve.py' copyright = u'2015, Matt Chung' author = u'Matt Chung' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'Speedcurvepydoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Speedcurvepy.tex', u'Speedcurve.py Documentation', u'Matt Chung', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'speedcurvepy', u'Speedcurve.py Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Speedcurvepy', u'Speedcurve.py Documentation', author, 'Speedcurvepy', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False autodoc_mock_imports = ['requests']
itsmemattchung/speedcurve.py
docs/conf.py
Python
mit
9,566
import asyncio import collections import logging import aiohttp import typing from lbry import utils from lbry.conf import Config from lbry.extras import system_info ANALYTICS_ENDPOINT = 'https://api.segment.io/v1' ANALYTICS_TOKEN = 'Ax5LZzR1o3q3Z3WjATASDwR5rKyHH0qOIRIbLmMXn2H=' # Things We Track SERVER_STARTUP = 'Server Startup' SERVER_STARTUP_SUCCESS = 'Server Startup Success' SERVER_STARTUP_ERROR = 'Server Startup Error' DOWNLOAD_STARTED = 'Download Started' DOWNLOAD_ERRORED = 'Download Errored' DOWNLOAD_FINISHED = 'Download Finished' HEARTBEAT = 'Heartbeat' CLAIM_ACTION = 'Claim Action' # publish/create/update/abandon NEW_CHANNEL = 'New Channel' CREDITS_SENT = 'Credits Sent' UPNP_SETUP = "UPnP Setup" BLOB_BYTES_UPLOADED = 'Blob Bytes Uploaded' TIME_TO_FIRST_BYTES = "Time To First Bytes" log = logging.getLogger(__name__) def _event_properties(installation_id: str, session_id: str, event_properties: typing.Optional[typing.Dict]) -> typing.Dict: properties = { 'lbry_id': installation_id, 'session_id': session_id, } properties.update(event_properties or {}) return properties def _download_properties(conf: Config, external_ip: str, resolve_duration: float, total_duration: typing.Optional[float], download_id: str, name: str, outpoint: str, active_peer_count: int, tried_peers_count: int, added_fixed_peers: bool, fixed_peer_delay: float, sd_hash: str, sd_download_duration: typing.Optional[float] = None, head_blob_hash: typing.Optional[str] = None, head_blob_length: typing.Optional[int] = None, head_blob_download_duration: typing.Optional[float] = None, error: typing.Optional[str] = None) -> typing.Dict: return { "external_ip": external_ip, "download_id": download_id, "total_duration": round(total_duration, 4), "resolve_duration": None if not resolve_duration else round(resolve_duration, 4), "error": error, 'name': name, "outpoint": outpoint, "node_rpc_timeout": conf.node_rpc_timeout, "peer_connect_timeout": conf.peer_connect_timeout, "blob_download_timeout": conf.blob_download_timeout, "use_fixed_peers": len(conf.reflector_servers) > 0, "fixed_peer_delay": fixed_peer_delay, "added_fixed_peers": added_fixed_peers, "active_peer_count": active_peer_count, "tried_peers_count": tried_peers_count, "sd_blob_hash": sd_hash, "sd_blob_duration": None if not sd_download_duration else round(sd_download_duration, 4), "head_blob_hash": head_blob_hash, "head_blob_length": head_blob_length, "head_blob_duration": None if not head_blob_download_duration else round(head_blob_download_duration, 4) } def _make_context(platform): # see https://segment.com/docs/spec/common/#context # they say they'll ignore fields outside the spec, but evidently they don't context = { 'app': { 'version': platform['lbrynet_version'], 'build': platform['build'], }, # TODO: expand os info to give linux/osx specific info 'os': { 'name': platform['os_system'], 'version': platform['os_release'] }, } if 'desktop' in platform and 'distro' in platform: context['os']['desktop'] = platform['desktop'] context['os']['distro'] = platform['distro'] return context class AnalyticsManager: def __init__(self, conf: Config, installation_id: str, session_id: str): self.conf = conf self.cookies = {} self.url = ANALYTICS_ENDPOINT self._write_key = utils.deobfuscate(ANALYTICS_TOKEN) self._enabled = conf.share_usage_data self._tracked_data = collections.defaultdict(list) self.context = _make_context(system_info.get_platform()) self.installation_id = installation_id self.session_id = session_id self.task: asyncio.Task = None self.external_ip: typing.Optional[str] = None @property def is_started(self): return self.task is not None async def start(self): if self._enabled and self.task is None: self.external_ip = await utils.get_external_ip() self.task = asyncio.create_task(self.run()) async def run(self): while True: await self._send_heartbeat() await asyncio.sleep(1800) self.external_ip = await utils.get_external_ip() def stop(self): if self.task is not None and not self.task.done(): self.task.cancel() async def _post(self, data: typing.Dict): request_kwargs = { 'method': 'POST', 'url': self.url + '/track', 'headers': {'Connection': 'Close'}, 'auth': aiohttp.BasicAuth(self._write_key, ''), 'json': data, 'cookies': self.cookies } try: async with utils.aiohttp_request(**request_kwargs) as response: self.cookies.update(response.cookies) except Exception as e: log.debug('Encountered an exception while POSTing to %s: ', self.url + '/track', exc_info=e) async def track(self, event: typing.Dict): """Send a single tracking event""" if self._enabled: log.debug('Sending track event: %s', event) await self._post(event) async def send_upnp_setup_success_fail(self, success, status): await self.track( self._event(UPNP_SETUP, { 'success': success, 'status': status, }) ) async def send_server_startup(self): await self.track(self._event(SERVER_STARTUP)) async def send_server_startup_success(self): await self.track(self._event(SERVER_STARTUP_SUCCESS)) async def send_server_startup_error(self, message): await self.track(self._event(SERVER_STARTUP_ERROR, {'message': message})) async def send_time_to_first_bytes(self, resolve_duration: typing.Optional[float], total_duration: typing.Optional[float], download_id: str, name: str, outpoint: str, found_peers_count: int, tried_peers_count: int, added_fixed_peers: bool, fixed_peers_delay: float, sd_hash: str, sd_download_duration: typing.Optional[float] = None, head_blob_hash: typing.Optional[str] = None, head_blob_length: typing.Optional[int] = None, head_blob_duration: typing.Optional[int] = None, error: typing.Optional[str] = None): await self.track(self._event(TIME_TO_FIRST_BYTES, _download_properties( self.conf, self.external_ip, resolve_duration, total_duration, download_id, name, outpoint, found_peers_count, tried_peers_count, added_fixed_peers, fixed_peers_delay, sd_hash, sd_download_duration, head_blob_hash, head_blob_length, head_blob_duration, error ))) async def send_download_finished(self, download_id, name, sd_hash): await self.track( self._event( DOWNLOAD_FINISHED, { 'download_id': download_id, 'name': name, 'stream_info': sd_hash } ) ) async def send_claim_action(self, action): await self.track(self._event(CLAIM_ACTION, {'action': action})) async def send_new_channel(self): await self.track(self._event(NEW_CHANNEL)) async def send_credits_sent(self): await self.track(self._event(CREDITS_SENT)) async def _send_heartbeat(self): await self.track(self._event(HEARTBEAT)) def _event(self, event, properties: typing.Optional[typing.Dict] = None): return { 'userId': 'lbry', 'event': event, 'properties': _event_properties(self.installation_id, self.session_id, properties), 'context': self.context, 'timestamp': utils.isonow() }
lbryio/lbry
lbry/lbry/extras/daemon/analytics.py
Python
mit
8,491
"""KDE of Temps.""" import calendar from datetime import date, datetime import pandas as pd from pyiem.plot.util import fitbox from pyiem.plot import figure from pyiem.util import get_autoplot_context, get_sqlalchemy_conn from pyiem.exceptions import NoDataFound from matplotlib.ticker import MaxNLocator from scipy.stats import gaussian_kde import numpy as np from sqlalchemy import text PDICT = { "high": "High Temperature [F]", "low": "Low Temperature [F]", "avgt": "Average Temperature [F]", } MDICT = dict( [ ("all", "No Month/Time Limit"), ("spring", "Spring (MAM)"), ("fall", "Fall (SON)"), ("winter", "Winter (DJF)"), ("summer", "Summer (JJA)"), ("jan", "January"), ("feb", "February"), ("mar", "March"), ("apr", "April"), ("may", "May"), ("jun", "June"), ("jul", "July"), ("aug", "August"), ("sep", "September"), ("oct", "October"), ("nov", "November"), ("dec", "December"), ] ) def get_description(): """Return a dict describing how to call this plotter""" desc = {} desc["cache"] = 3600 desc["data"] = True desc[ "description" ] = """This autoplot generates some metrics on the distribution of temps over a given period of years. The plotted distribution in the upper panel is using a guassian kernel density estimate. """ desc["arguments"] = [ dict( type="station", name="station", default="IATDSM", label="Select station:", network="IACLIMATE", ), dict( type="select", options=PDICT, name="v", default="high", label="Daily Variable to Plot:", ), dict( type="select", name="month", default="all", label="Month Limiter", options=MDICT, ), dict( type="year", min=1880, name="sy1", default=1981, label="Inclusive Start Year for First Period of Years:", ), dict( type="year", min=1880, name="ey1", default=2010, label="Inclusive End Year for First Period of Years:", ), dict( type="year", min=1880, name="sy2", default=1991, label="Inclusive Start Year for Second Period of Years:", ), dict( type="year", min=1880, name="ey2", default=2020, label="Inclusive End Year for Second Period of Years:", ), ] return desc def get_df(ctx, period): """Get our data.""" table = "alldata_%s" % (ctx["station"][:2]) month = ctx["month"] ctx["mlabel"] = f"{month.capitalize()} Season" if month == "all": months = range(1, 13) ctx["mlabel"] = "All Year" elif month == "fall": months = [9, 10, 11] elif month == "winter": months = [12, 1, 2] elif month == "spring": months = [3, 4, 5] elif month == "summer": months = [6, 7, 8] else: ts = datetime.strptime("2000-" + month + "-01", "%Y-%b-%d") months = [ts.month] ctx["mlabel"] = calendar.month_name[ts.month] with get_sqlalchemy_conn("coop") as conn: df = pd.read_sql( text( f"SELECT high, low, (high+low)/2. as avgt from {table} WHERE " "day >= :d1 and day <= :d2 and station = :station " "and high is not null " "and low is not null and month in :months" ), conn, params={ "d1": date(ctx[f"sy{period}"], 1, 1), "d2": date(ctx[f"ey{period}"], 12, 31), "station": ctx["station"], "months": tuple(months), }, ) return df def f2s(value): """HAAAAAAAAAAAAACK.""" return ("%.5f" % value).rstrip("0").rstrip(".") def plotter(fdict): """Go""" ctx = get_autoplot_context(fdict, get_description()) df1 = get_df(ctx, "1") df2 = get_df(ctx, "2") if df1.empty or df2.empty: raise NoDataFound("Failed to find data for query!") kern1 = gaussian_kde(df1[ctx["v"]]) kern2 = gaussian_kde(df2[ctx["v"]]) xpos = np.arange( min([df1[ctx["v"]].min(), df2[ctx["v"]].min()]), max([df1[ctx["v"]].max(), df2[ctx["v"]].max()]) + 1, dtype="i", ) period1 = "%s-%s" % (ctx["sy1"], ctx["ey1"]) period2 = "%s-%s" % (ctx["sy2"], ctx["ey2"]) label1 = "%s-%s %s" % (ctx["sy1"], ctx["ey1"], ctx["v"]) label2 = "%s-%s %s" % (ctx["sy2"], ctx["ey2"], ctx["v"]) df = pd.DataFrame({label1: kern1(xpos), label2: kern2(xpos)}, index=xpos) fig = figure(apctx=ctx) title = "[%s] %s %s Distribution\n%s vs %s over %s" % ( ctx["station"], ctx["_nt"].sts[ctx["station"]]["name"], PDICT[ctx["v"]], period2, period1, ctx["mlabel"], ) fitbox(fig, title, 0.12, 0.9, 0.91, 0.99) ax = fig.add_axes([0.12, 0.38, 0.75, 0.52]) C1 = "blue" C2 = "red" alpha = 0.4 ax.plot( df.index.values, df[label1], lw=2, c=C1, label=rf"{label1} - $\mu$={df1[ctx['v']].mean():.2f}", zorder=4, ) ax.fill_between(xpos, 0, df[label1], color=C1, alpha=alpha, zorder=3) ax.axvline(df1[ctx["v"]].mean(), color=C1) ax.plot( df.index.values, df[label2], lw=2, c=C2, label=rf"{label2} - $\mu$={df2[ctx['v']].mean():.2f}", zorder=4, ) ax.fill_between(xpos, 0, df[label2], color=C2, alpha=alpha, zorder=3) ax.axvline(df2[ctx["v"]].mean(), color=C2) ax.set_ylabel("Guassian Kernel Density Estimate") ax.legend(loc="best") ax.grid(True) ax.xaxis.set_major_locator(MaxNLocator(20)) # Sub ax ax2 = fig.add_axes([0.12, 0.1, 0.75, 0.22]) delta = df[label2] - df[label1] ax2.plot(df.index.values, delta) dam = delta.abs().max() * 1.1 ax2.set_ylim(0 - dam, dam) ax2.set_xlabel(PDICT[ctx["v"]]) ax2.set_ylabel("%s minus\n%s" % (period2, period1)) ax2.grid(True) ax2.fill_between(xpos, 0, delta, where=delta > 0, color=C2, alpha=alpha) ax2.fill_between(xpos, 0, delta, where=delta < 0, color=C1, alpha=alpha) ax2.axhline(0, ls="--", lw=2, color="k") ax2.xaxis.set_major_locator(MaxNLocator(20)) # Percentiles levels = [0.001, 0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75] levels.extend([0.9, 0.95, 0.99, 0.995, 0.999]) p1 = df1[ctx["v"]].describe(percentiles=levels) p2 = df2[ctx["v"]].describe(percentiles=levels) y = 0.8 fig.text(0.88, y, "Percentile", rotation=70) fig.text(0.91, y, period1, rotation=70) fig.text(0.945, y, period2, rotation=70) for ptile in levels: y -= 0.03 val = f2s(ptile * 100.0) fig.text(0.88, y, val) fig.text(0.91, y, "%.1f" % (p1[f"{val}%"],)) fig.text(0.95, y, "%.1f" % (p2[f"{val}%"],)) return fig, df if __name__ == "__main__": plotter(dict())
akrherz/iem
htdocs/plotting/auto/scripts200/p215.py
Python
mit
7,271
from django.contrib import admin from pieces.models import ( PieceTag, Piece, Venue, Study, Keyword, PieceToStudyAssociation) # {{{ studies class KeywordInline(admin.TabularInline): model = Keyword extra = 10 class StudyAdmin(admin.ModelAdmin): list_display = ("id", "name", "start_date") date_hierarchy = "start_date" inlines = [KeywordInline] admin.site.register(Study, StudyAdmin) # }}} # {{{ pieces admin.site.register(PieceTag) class PieceToStudyInline(admin.StackedInline): model = PieceToStudyAssociation extra = 2 class PieceAdmin(admin.ModelAdmin): list_display = ("id", "title", "venue", "pub_date", "create_date") list_filter = ("tags", "studies", "publication_type", "samples", "venue") list_display_links = ("id", "title") search_fields = ('title', 'content', 'id') date_hierarchy = "pub_date" filter_horizontal = ("tags",) save_on_top = True inlines = [PieceToStudyInline] admin.site.register(Piece, PieceAdmin) # }}} class VenueAdmin(admin.ModelAdmin): list_display = ("id", "name") list_display_links = ("id", "name") search_fields = ("name", "id") admin.site.register(Venue, VenueAdmin) # vim: foldmethod=marker
inducer/codery
pieces/admin.py
Python
mit
1,253
# Copyright (C) 2010-2013 Claudio Guarnieri. # Copyright (C) 2014-2016 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. import os import logging import datetime import re import dateutil.parser from lib.cuckoo.common.abstracts import BehaviorHandler log = logging.getLogger(__name__) class FilteredProcessLog(list): def __init__(self, eventstream, **kwfilters): self.eventstream = eventstream self.kwfilters = kwfilters def __iter__(self): for event in self.eventstream: for k, v in self.kwfilters.items(): if event[k] != v: continue del event["type"] yield event def __nonzero__(self): return True class LinuxSystemTap(BehaviorHandler): """Parses systemtap generated plaintext logs (see data/strace.stp).""" key = "processes" def __init__(self, *args, **kwargs): super(LinuxSystemTap, self).__init__(*args, **kwargs) self.processes = [] self.pids_seen = set() self.forkmap = {} self.matched = False self._check_for_probelkm() def _check_for_probelkm(self): path_lkm = os.path.join(self.analysis.logs_path, "all.lkm") if os.path.exists(path_lkm): lines = open(path_lkm).readlines() forks = [re.findall("task (\d+)@0x[0-9a-f]+ forked to (\d+)@0x[0-9a-f]+", line) for line in lines] self.forkmap = dict((j, i) for i, j in reduce(lambda x, y: x+y, forks, [])) # self.results["source"].append("probelkm") def handles_path(self, path): if path.endswith(".stap"): self.matched = True return True def parse(self, path): parser = StapParser(open(path)) for event in parser: pid = event["pid"] if pid not in self.pids_seen: self.pids_seen.add(pid) ppid = self.forkmap.get(pid, -1) process = { "pid": pid, "ppid": ppid, "process_name": event["process_name"], "first_seen": event["time"], } # create a process event as we don't have those with linux+systemtap pevent = dict(process) pevent["type"] = "process" yield pevent process["calls"] = FilteredProcessLog(parser, pid=pid) self.processes.append(process) yield event def run(self): if not self.matched: return self.processes.sort(key=lambda process: process["first_seen"]) return self.processes class StapParser(object): """Handle .stap logs from the Linux analyzer.""" def __init__(self, fd): self.fd = fd def __iter__(self): self.fd.seek(0) for line in self.fd: # 'Thu May 7 14:58:43 2015.390178 python@7f798cb95240[2114] close(6) = 0\n' # datetime is 31 characters datetimepart, rest = line[:31], line[32:] # incredibly sophisticated date time handling dtms = datetime.timedelta(0, 0, int(datetimepart.split(".", 1)[1])) dt = dateutil.parser.parse(datetimepart.split(".", 1)[0]) + dtms parts = re.match("^(.+)@([a-f0-9]+)\[(\d+)\] (\w+)\((.*)\) = (\S+){0,1}\s{0,1}(\(\w+\)){0,1}$", rest) if not parts: log.warning("Could not parse syscall trace line: %s", line) continue pname, ip, pid, fn, arguments, retval, ecode = parts.groups() argsplit = arguments.split(", ") arguments = dict(("p%u" % pos, argsplit[pos]) for pos in range(len(argsplit))) pid = int(pid) if pid.isdigit() else -1 yield { "time": dt, "process_name": pname, "pid": pid, "instruction_pointer": ip, "api": fn, "arguments": arguments, "return_value": retval, "status": ecode, "type": "apicall", "raw": line, }
mburakergenc/Malware-Detection-using-Machine-Learning
cuckoo/modules/processing/platform/linux.py
Python
mit
4,175
# coding=utf-8 """ An API used by the UI and RESTful API. """ from bson import ObjectId __author__ = 'tmetsch' import collections import json import pika import pika.exceptions as pikaex import uuid from suricate.data import object_store from suricate.data import streaming TEMPLATE = ''' % if len(error.strip()) > 0: <div class="error">{{!error}}</div> % end % for item in output: % if item[:6] == 'image:': <div><img src="data:{{item[6:]}}"/></div> % elif item[:6] == 'embed:': <div>{{!item[6:]}}</div> % elif item[:1] == '#': <div>{{item.rstrip()}}</div> % elif item.strip() != '': <div class="code">{{item.rstrip()}}</div> % end % end ''' class API(object): """ Little helper class to abstract the REST and UI from. """ def __init__(self, amqp_uri, mongo_uri): self.clients = {} self.amqp_uri = amqp_uri # get obj/streaming client up! self.obj_str = object_store.MongoStore(mongo_uri) self.stream = streaming.AMQPClient(mongo_uri) # Data sources... def info_data(self, uid, token): """ Return dictionary with key/values about data objects and streams. :param uid: Identifier for the user. :param token: The token of the user. """ data_info = self.obj_str.info(uid, token) data_info.update(self.stream.info(uid, token)) return data_info def list_data_sources(self, uid, token): """ List available data sources. Return list of ids for objects & streams. :param uid: Identifier for the user. :param token: The token of the user. """ tmp = self.obj_str.list_objects(uid, token) tmp2 = self.stream.list_streams(uid, token) return tmp, tmp2 # Objects def create_object(self, content, uid, token, meta_dat): """ Create a data object. :param content: Object content. :param uid: Identifier for the user. :param token: The token of the user. """ self.obj_str.create_object(uid, token, content, meta=meta_dat) def retrieve_object(self, iden, uid, token): """ Retrieve a data object. :param iden: Id of the object. :param uid: Identifier for the user. :param token: The token of the user. """ tmp = self.obj_str.retrieve_object(uid, token, iden) return tmp def delete_object(self, iden, uid, token): """ Delete a data object. :param iden: Id of the object. :param uid: Identifier for the user. :param token: The token of the user. """ self.obj_str.delete_object(uid, token, iden) # Streams def create_stream(self, uri, queue, uid, token): """ Create a data stream. :param uri: RabbitMQ Broker URI. :param queue: Queue. :param uid: Identifier for the user. :param token: The token of the user. """ self.stream.create(uid, token, uri, queue) def retrieve_stream(self, iden, uid, token): """ Retrieve a data stream. :param iden: Id of the stream. :param uid: Identifier for the user. :param token: The token of the user. """ uri, queue, msgs = self.stream.retrieve(uid, token, iden) return uri, queue, msgs def delete_stream(self, iden, uid, token): """ Delete a data stream. :param iden: Id of the stream. :param uid: Identifier for the user. :param token: The token of the user. """ self.stream.delete(uid, token, iden) def set_meta(self, data_src, iden, tags, uid, token): """ Set meta information. :param data_src: Reflects to db name. :param iden: Id of the object/stream. :param tags: Metadata dict. :param uid: Identifier for the user. :param token: The token of the user. """ database = self.obj_str.client[uid] database.authenticate(uid, token) collection = database[data_src] collection.update({'_id': ObjectId(iden)}, {"$set": {'meta.tags': tags}}) #### # Everything below this is RPC! #### # TODO: check if can work with function name and kwargs to construct # payload. # Projects def list_projects(self, uid, token): """ RPC call to list notebooks. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'call': 'list_projects'} tmp = self._call_rpc(uid, payload) return tmp['projects'] def retrieve_project(self, proj_name, uid, token): """ RPC call to retrieve projects. :param proj_name: Name of the project. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'call': 'retrieve_project'} tmp = self._call_rpc(uid, payload) return tmp['project'] def delete_project(self, proj_name, uid, token): """ RPC call to delete a project. :param proj_name: Name of the project. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'call': 'delete_project'} self._call_rpc(uid, payload) # Notebooks def create_notebook(self, proj_name, uid, token, ntb_name='start.py', src='\n'): """ RPC call to create a notebook (or creating an empty project). :param proj_name: Name of the project. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': None, 'notebook': {'meta': {'tags': [], 'name': ntb_name, 'mime-type': 'text/x-script.phyton'}, 'src': src, 'dashboard_template': TEMPLATE, 'out': [], 'err': ''}, 'call': 'create_notebook'} self._call_rpc(uid, payload) def retrieve_notebook(self, proj_name, ntb_id, uid, token): """ RPC call to retrieve a notebook. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'call': 'retrieve_notebook'} tmp = self._call_rpc(uid, payload) return tmp['notebook'] def update_notebook(self, proj_name, ntb_id, ntb, uid, token): """ RPC call to update a notebook. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param ntb: New notebook structure. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'src': ntb, 'call': 'update_notebook'} self._call_rpc(uid, payload) def delete_notebook(self, proj_name, ntb_id, uid, token): """ RPC call to delete a notebook. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'call': 'delete_notebook'} self._call_rpc(uid, payload) def run_notebook(self, proj_name, ntb_id, src, uid, token): """ RPC call to run a notebook. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param src: source code to run. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'src': src, 'call': 'run_notebook'} self._call_rpc(uid, payload) def interact(self, proj_name, ntb_id, loc, uid, token): """ RPC call to interact with an notebook's intepreter. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param loc: Line of code. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'loc': loc, 'call': 'interact'} self._call_rpc(uid, payload) # Jobs. def list_jobs(self, uid, token): """ RPC call to run a notebook. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'call': 'list_jobs'} tmp = self._call_rpc(uid, payload) return tmp['jobs'] def run_job(self, proj_name, ntb_id, src, uid, token): """ RPC call to run a notebook. :param proj_name: Name of the project. :param ntb_id: Id of the notebook. :param src: source code to run. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'project_id': proj_name, 'notebook_id': ntb_id, 'src': src, 'call': 'run_job'} self._call_rpc(uid, payload) def clear_job_list(self, uid, token): """ Clear job list. :param uid: Identifier for the user. :param token: The token of the user. """ payload = {'uid': uid, 'token': token, 'call': 'clear_job_list'} self._call_rpc(uid, payload) def _call_rpc(self, uid, payload): """ Make a lovely RPC (blocking) call. :param uid: user's id. :param payload: JSON payload for the message. """ if uid not in self.clients: self.clients[uid] = RPCClient(self.amqp_uri) return self.clients[uid].call(uid, payload) class RPCClient(object): """ An RPC client using AMQP. """ json_dec = json.JSONDecoder(object_pairs_hook=collections.OrderedDict) def __init__(self, uri): self.para = pika.URLParameters(uri) self.connection = pika.BlockingConnection(self.para) self.corr_id = None self.response = None def callback(self, channel, method, props, body): """ Handle a response call. :param channel: The channel. :param method: The method. :param props: The properties. :param body: The body. """ if self.corr_id == props.correlation_id: self.response = body def call(self, uid, payload): """ Perform an RPC call. :param uid: Identifier of the user. :param payload: The payload. """ self.response = None self.corr_id = str(uuid.uuid4()) try: channel = self.connection.channel() except pikaex.ChannelClosed: # idle connections are closed... self.connection = pika.BlockingConnection(self.para) channel = self.connection.channel() result = channel.queue_declare(exclusive=True) callback_queue = result.method.queue channel.basic_consume(self.callback, no_ack=True, queue=callback_queue) prop = pika.BasicProperties(reply_to=callback_queue, correlation_id=self.corr_id) channel.basic_publish(exchange='', routing_key=uid, properties=prop, body=json.dumps(payload)) while self.response is None: self.connection.process_data_events() # making sure order is in place! res = self.json_dec.decode(self.response) self.response = None return res
tmetsch/suricate
suricate/ui/api.py
Python
mit
13,237
# -*- coding: utf-8 -*- import vim import itertools as it from orgmode._vim import echom, ORGMODE, apply_count, repeat, realign_tags from orgmode import settings from orgmode.liborgmode.base import Direction from orgmode.menu import Submenu, ActionEntry from orgmode.keybinding import Keybinding, Plug from orgmode.exceptions import PluginError # temporary todo states for differnent orgmode buffers ORGTODOSTATES = {} from orgmode.py3compat.xrange_compatibility import * from orgmode.py3compat.encode_compatibility import * from orgmode.py3compat.unicode_compatibility import * from orgmode.py3compat.py_py3_string import * def split_access_key(t, sub=None): u""" Split access key Args: t (str): Todo state sub: A value that will be returned instead of access key if there was not access key Returns: tuple: Todo state and access key separated (TODO, ACCESS_KEY) Example: >>> split_access_key('TODO(t)') >>> ('TODO', '(t)') >>> split_access_key('WANT', sub='(hi)') >>> ('WANT', '(hi)') """ if type(t) != unicode: echom("String must be unicode") return (None, None) idx = t.find(u'(') v, k = (t, sub) if idx != -1 and t[idx + 1:-1]: v, k = (t[:idx], t[idx + 1:-1]) return (v, k) class Todo(object): u""" Todo plugin. Description taken from orgmode.org: You can use TODO keywords to indicate different sequential states in the process of working on an item, for example: ["TODO", "FEEDBACK", "VERIFY", "|", "DONE", "DELEGATED"] The vertical bar separates the TODO keywords (states that need action) from the DONE states (which need no further action). If you don't provide the separator bar, the last state is used as the DONE state. With this setup, the command ``,d`` will cycle an entry from TODO to FEEDBACK, then to VERIFY, and finally to DONE and DELEGATED. """ def __init__(self): u""" Initialize plugin """ object.__init__(self) # menu entries this plugin should create self.menu = ORGMODE.orgmenu + Submenu(u'&TODO Lists') # key bindings for this plugin # key bindings are also registered through the menu so only additional # bindings should be put in this variable self.keybindings = [] @classmethod def _process_all_states(cls, all_states): u""" verify if states defined by user is valid. Return cleaned_todo and flattened if is. Raise Exception if not. Valid checking: * no two state share a same name """ # TODO Write tests. -- Ron89 cleaned_todos = [[ split_access_key(todo)[0] for todo in it.chain.from_iterable(x)] for x in all_states] + [[None]] flattened_todos = list(it.chain.from_iterable(cleaned_todos)) if len(flattened_todos) != len(set(flattened_todos)): raise PluginError(u"Duplicate names detected in TODO keyword list. Please examine `g/b:org_todo_keywords`") # TODO This is the case when there are 2 todo states with the same # name. It should be handled by making a simple class to hold TODO # states, which would avoid mixing 2 todo states with the same name # since they would have a different reference (but same content), # albeit this can fail because python optimizes short strings (i.e. # they hold the same ref) so care should be taken in implementation return (cleaned_todos, flattened_todos) @classmethod def _get_next_state( cls, current_state, all_states, direction=Direction.FORWARD, next_set=False): u""" Get the next todo state Args: current_state (str): The current todo state all_states (list): A list containing all todo states within sublists. The todo states may contain access keys direction: Direction of state or keyword set change (forward or backward) next_set: Advance to the next keyword set in defined direction. Returns: str or None: next todo state, or None if there is no next state. Note: all_states should have the form of: [(['TODO(t)'], ['DONE(d)']), (['REPORT(r)', 'BUG(b)', 'KNOWNCAUSE(k)'], ['FIXED(f)']), ([], ['CANCELED(c)'])] """ cleaned_todos, flattened_todos = cls._process_all_states(all_states) # backward direction should really be -1 not 2 next_dir = -1 if direction == Direction.BACKWARD else 1 # work only with top level index if next_set: top_set = next(( todo_set[0] for todo_set in enumerate(cleaned_todos) if current_state in todo_set[1]), -1) ind = (top_set + next_dir) % len(cleaned_todos) if ind != len(cleaned_todos) - 1: echom("Using set: %s" % str(all_states[ind])) else: echom("Keyword removed.") return cleaned_todos[ind][0] # No next set, cycle around everything else: ind = next(( todo_iter[0] for todo_iter in enumerate(flattened_todos) if todo_iter[1] == current_state), -1) return flattened_todos[(ind + next_dir) % len(flattened_todos)] @classmethod @realign_tags @repeat @apply_count def toggle_todo_state( cls, direction=Direction.FORWARD, interactive=False, next_set=False): u""" Toggle state of TODO item :returns: The changed heading """ d = ORGMODE.get_document(allow_dirty=True) # get heading heading = d.find_current_heading() if not heading: vim.eval(u'feedkeys("^", "n")') return todo_states = d.get_todo_states(strip_access_key=False) # get todo states if not todo_states: echom(u'No todo keywords configured.') return current_state = heading.todo # get new state interactively if interactive: # determine position of the interactive prompt prompt_pos = settings.get(u'org_todo_prompt_position', u'botright') if prompt_pos not in [u'botright', u'topleft']: prompt_pos = u'botright' # pass todo states to new window ORGTODOSTATES[d.bufnr] = todo_states settings.set( u'org_current_state_%d' % d.bufnr, current_state if current_state is not None else u'', overwrite=True) todo_buffer_exists = bool(int(vim.eval(u_encode( u'bufexists("org:todo/%d")' % (d.bufnr, ))))) if todo_buffer_exists: # if the buffer already exists, reuse it vim.command(u_encode( u'%s sbuffer org:todo/%d' % (prompt_pos, d.bufnr, ))) else: # create a new window vim.command(u_encode( u'keepalt %s %dsplit org:todo/%d' % (prompt_pos, len(todo_states), d.bufnr))) else: new_state = Todo._get_next_state( current_state, todo_states, direction=direction, next_set=next_set) cls.set_todo_state(new_state) # plug plug = u'OrgTodoForward' if direction == Direction.BACKWARD: plug = u'OrgTodoBackward' return plug @classmethod def set_todo_state(cls, state): u""" Set todo state for buffer. :bufnr: Number of buffer the todo state should be updated for :state: The new todo state """ lineno, colno = vim.current.window.cursor d = ORGMODE.get_document(allow_dirty=True) heading = d.find_current_heading() if not heading: return current_state = heading.todo # set new headline heading.todo = state d.write_heading(heading) # move cursor along with the inserted state only when current position # is in the heading; otherwite do nothing if heading.start_vim == lineno and colno > heading.level: if current_state is not None and \ colno <= heading.level + len(current_state): # the cursor is actually on the todo keyword # move it back to the beginning of the keyword in that case vim.current.window.cursor = (lineno, heading.level + 1) else: # the cursor is somewhere in the text, move it along if current_state is None and state is None: offset = 0 elif current_state is None and state is not None: offset = len(state) + 1 elif current_state is not None and state is None: offset = -len(current_state) - 1 else: offset = len(state) - len(current_state) vim.current.window.cursor = (lineno, colno + offset) @classmethod def init_org_todo(cls): u""" Initialize org todo selection window. """ bufnr = int(vim.current.buffer.name.split('/')[-1]) all_states = ORGTODOSTATES.get(bufnr, None) vim_commands = [ u'let g:org_sav_timeoutlen=&timeoutlen', u'au orgmode BufEnter <buffer> :if ! exists("g:org_sav_timeoutlen")|let g:org_sav_timeoutlen=&timeoutlen|set timeoutlen=1|endif', u'au orgmode BufLeave <buffer> :if exists("g:org_sav_timeoutlen")|let &timeoutlen=g:org_sav_timeoutlen|unlet g:org_sav_timeoutlen|endif', u'setlocal nolist tabstop=16 buftype=nofile timeout timeoutlen=1 winfixheight', u'setlocal statusline=Org\\ todo\\ (%s)' % vim.eval(u_encode(u'fnameescape(fnamemodify(bufname(%d), ":t"))' % bufnr)), u'nnoremap <silent> <buffer> <Esc> :%sbw<CR>' % vim.eval(u_encode(u'bufnr("%")')), u'nnoremap <silent> <buffer> <CR> :let g:org_state = fnameescape(expand("<cword>"))<Bar>bw<Bar>exec "%s ORGMODE.plugins[u\'Todo\'].set_todo_state(\'".g:org_state."\')"<Bar>unlet! g:org_state<CR>' % VIM_PY_CALL, ] # because timeoutlen can only be set globally it needs to be stored and # restored later # make window a scratch window and set the statusline differently for cmd in vim_commands: vim.command(u_encode(cmd)) if all_states is None: vim.command(u_encode(u'bw')) echom(u'No todo states avaiable for buffer %s' % vim.current.buffer.name) for idx, state in enumerate(all_states): pairs = [split_access_key(x, sub=u' ') for x in it.chain(*state)] line = u'\t'.join(u''.join((u'[%s] ' % x[1], x[0])) for x in pairs) vim.current.buffer.append(u_encode(line)) for todo, key in pairs: # FIXME if double key is used for access modified this doesn't work vim.command(u_encode(u'nnoremap <silent> <buffer> %s :bw<CR><c-w><c-p>%s ORGMODE.plugins[u"Todo"].set_todo_state("%s")<CR>' % (key, VIM_PY_CALL, u_decode(todo)))) # position the cursor of the current todo item vim.command(u_encode(u'normal! G')) current_state = settings.unset(u'org_current_state_%d' % bufnr) if current_state is not None and current_state != '': for i, buf in enumerate(vim.current.buffer): idx = buf.find(current_state) if idx != -1: vim.current.window.cursor = (i + 1, idx) break else: vim.current.window.cursor = (2, 4) # finally make buffer non modifiable vim.command(u_encode(u'setfiletype orgtodo')) vim.command(u_encode(u'setlocal nomodifiable')) # remove temporary todo states for the current buffer del ORGTODOSTATES[bufnr] def register(self): u""" Registration of plugin. Key bindings and other initialization should be done. """ self.keybindings.append(Keybinding(u'<localleader>ct', Plug( u'OrgTodoToggleNonInteractive', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state(interactive=False)<CR>' % VIM_PY_CALL))) self.menu + ActionEntry(u'&TODO/DONE/-', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<localleader>d', Plug( u'OrgTodoToggleInteractive', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state(interactive=True)<CR>' % VIM_PY_CALL))) self.menu + ActionEntry(u'&TODO/DONE/- (interactiv)', self.keybindings[-1]) # add submenu submenu = self.menu + Submenu(u'Select &keyword') self.keybindings.append(Keybinding(u'<S-Right>', Plug( u'OrgTodoForward', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state()<CR>' % VIM_PY_CALL))) submenu + ActionEntry(u'&Next keyword', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<S-Left>', Plug( u'OrgTodoBackward', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state(direction=2)<CR>' % VIM_PY_CALL))) submenu + ActionEntry(u'&Previous keyword', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<C-S-Right>', Plug( u'OrgTodoSetForward', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state(next_set=True)<CR>' % VIM_PY_CALL))) submenu + ActionEntry(u'Next keyword &set', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<C-S-Left>', Plug( u'OrgTodoSetBackward', u'%s ORGMODE.plugins[u"Todo"].toggle_todo_state(direction=2, next_set=True)<CR>' % VIM_PY_CALL))) submenu + ActionEntry(u'Previous &keyword set', self.keybindings[-1]) settings.set(u'org_todo_keywords', [u_encode(u'TODO'), u_encode(u'|'), u_encode(u'DONE')]) settings.set(u'org_todo_prompt_position', u'botright') vim.command(u_encode(u'au orgmode BufReadCmd org:todo/* %s ORGMODE.plugins[u"Todo"].init_org_todo()' % VIM_PY_CALL)) # vim: set noexpandtab:
lucianp/dotfiles
link/.vim/ftplugin/orgmode/plugins/Todo.py
Python
mit
12,249
import yaml import os from ..boids import Boids from nose.tools import assert_equal import random import numpy as np from unittest.mock import patch import unittest.mock as mock def test_Boids(): flock = Boids(boid_number=10,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # make sure the class is initialised correctly: assert_equal(flock.boid_number,10) assert_equal(flock.move_to_middle_strength,0.1) assert_equal(flock.all_the_boids,range(10)) def test_fly_to_middle(): flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # make sure self.all_the_boids corresponds to the right thing, i.e. range(self.boid_number) np.testing.assert_array_equal(range(2),flock.all_the_boids) assert_equal(flock.move_to_middle_strength,0.1) # make sure arrays are updated to what we expect them to - #1 flock.x_velocities = [1, 2] flock.x_positions = [2, 1] flock.fly_to_middle() np.testing.assert_array_almost_equal(flock.x_velocities,[0.95, 2.05]) # make sure arrays are updated to what we expect them to - #2 flock.x_velocities = [5, 2] flock.x_positions = [2, 46] flock.fly_to_middle() np.testing.assert_array_almost_equal(flock.x_velocities,[7.2, -0.2]) def test_fly_away(): flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # make sure self.all_the_boids corresponds to the right thing, i.e. range(self.boid_number) np.testing.assert_array_equal(range(2),flock.all_the_boids) assert_equal(flock.alert_distance,100) # make sure arrays are updated to what we expect them to - #1 flock.x_velocities = [1, 2] flock.x_positions = [2, 1] flock.fly_away() np.testing.assert_array_almost_equal(flock.x_velocities,[2, 1]) # make sure arrays are updated to what we expect them to - #2 flock.x_velocities = [5, 2] flock.x_positions = [2, 46] flock.fly_away() np.testing.assert_array_almost_equal(flock.x_velocities,[5, 2]) def test_match_speed(): flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # make sure self.all_the_boids corresponds to the right thing, i.e. range(self.boid_number) np.testing.assert_array_equal(range(2),flock.all_the_boids) assert_equal(flock.formation_flying_distance,900) assert_equal(flock.formation_flying_strength,0.5) # make sure arrays are updated to what we expect them to - #1 flock.y_velocities = [1, 2] flock.match_speed() np.testing.assert_array_almost_equal(flock.y_velocities,[1., 2.] ) # make sure arrays are updated to what we expect them to - #2 flock.y_velocities = [14, 15] flock.match_speed() np.testing.assert_array_almost_equal(flock.y_velocities,[14., 15.]) def test_update_boids(): flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # test that update_boids() is called all right with mock.patch.object(flock,'update_boids') as mock_update: updated = flock.update_boids('') mock_update.assert_called_with('') # test that fly_to_middle() works with mock.patch.object(flock,'fly_to_middle') as mock_middle: flown_to_middle = flock.fly_to_middle('') mock_middle.assert_called_with('') # test that fly_away() works with mock.patch.object(flock,'fly_away') as mock_away: flown_away = flock.fly_away('') mock_away.assert_called_with('') # test that match_speed() works with mock.patch.object(flock,'match_speed') as mock_match: matched = flock.match_speed('') mock_match.assert_called_with('') # test that move() works with mock.patch.object(flock,'move') as mock_move: moved = flock.move('') mock_move.assert_called_with('') def test_animate(): flock = Boids(boid_number=2,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_flying_strength=0.5, x_position_min=0,x_position_max=200,y_position_min=-5,y_position_max=5, x_velocity_min=-10,x_velocity_max=30,y_velocity_min=-20,y_velocity_max=20) # test that animate() is called correctly with mock.patch.object(flock,'animate') as mock_animate: animated = flock.animate('frame') mock_animate.assert_called_with('frame')
GarlandDA/bad-boids
bad_boids/test/test_boids.py
Python
mit
5,230
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from api.views import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^ui/', include('ui.urls', namespace='build_ui')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^explorer/', include('rest_framework_swagger.urls', namespace='swagger')), ] # Setting up static files for development: if settings.DEBUG is True: urlpatterns = urlpatterns + \ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
TangentMicroServices/BuildService
buildservice/urls.py
Python
mit
697
# # $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $ # # Proprietary and confidential. # Copyright $Date:: 2011#$ Perfect Search Corporation. # All rights reserved. # import unittest, os, sys, StringIO from textui.prompt import * from nose.tools import istest, nottest from nose.plugins.attrib import attr _explained = False def _text_repeats(txt, fragment): i = txt.find(fragment) if i > -1: i = txt[i + len(fragment):].find(fragment) return i > -1 return False def _text_has(txt, fragment): return txt.find(fragment) > -1 @attr('interactive') class InteractivePromptTest(unittest.TestCase): def stuff(self, txt_for_stdin): # Overridden in AutomatedPromptTest pass def assertStdout(self, expectFunc, arg): # Overridden in AutomatedPromptTest return True def explain(self, txt): global _explained if not _explained: print(''' INTERACTIVE TEST -- PLEASE FOLLOW INSTRUCTIONS This test checks our ability to user input correctly. It depends on you typing some simple responses. It is not particularly sensitive to typos, but you should NOT just press Enter to get through the test, or you may see spurious failures. ''') _explained = True else: print('') print(txt.strip() + '\n') def test_prompt(self): self.explain(''' Answer the following question with at least a few chars. If the prompt() function is working, we should see a non-empty answer. ''') self.stuff('to seek the holy grail\n') answer = prompt('What is your quest?') self.assertTrue(answer) # Answer should never include trailing \n self.assertEquals(answer.rstrip(), answer) def test_prompt_bool_word_true(self): self.explain(''' Answer the following question accurately with a FULL WORD, not a single char. In other words, type "yes" or "no" as your answer. Case doesn't matter. ''') self.stuff('YeS\n') answer = prompt_bool('Does this line end with a "(y/n)" prompt?') self.assertTrue(isinstance(answer, bool)) self.assertTrue(answer) self.assertStdout(_text_has, '? (y/n)') def test_prompt_bool_char_true(self): self.explain(''' Answer the following question with the THE "Y" CHAR, not a full word. Case doesn't matter. ''') self.stuff('Y\n') answer = prompt_bool('Are you sure?') self.assertTrue(isinstance(answer, bool)) self.assertTrue(answer) def test_prompt_bool_word_false(self): self.explain(''' Answer the following question accurately with THE WORD "NO", not a single char. Case doesn't matter. ''') self.stuff('nO\n') answer = prompt_bool('Do chickens have lips?', False) self.assertTrue(isinstance(answer, bool)) self.assertFalse(answer) self.assertStdout(_text_has, '? (y/N)') def test_prompt_bool_char_false(self): self.explain(''' Answer the following question accurately with THE "N" CHAR, not a full word. Case doesn't matter. ''') self.stuff('n\n') answer = prompt_bool('Can pigs fly?') self.assertTrue(isinstance(answer, bool)) self.assertFalse(answer) def test_prompt_bool_repeats(self): self.explain(''' This test checks to see whether we require a genuine boolean response from someone instead of letting them type garbage. Answer the question ONCE WITH THE WORD "pickle". You should get reprompted. Answer THE SECOND TIME WITH "N"/"NO". ''') self.stuff('pickle\nNo\n') answer = prompt_bool('Do frogs have fur?') self.assertTrue(isinstance(answer, bool)) self.assertStdout(_text_repeats, 'have fur') def test_prompt_masked(self): self.explain(''' This test checks to see whether we can prompt for a password without displaying what you type. ''') answer = prompt('Type an imaginary password:', readline=readline_masked) self.assertTrue(prompt_bool('Were your keystrokes masked out?')) def test_prompt_enter(self): self.stuff('\n') answer = prompt('\nPress Enter:', default="blue") self.assertEqual('blue', answer) self.assertStdout(_text_has, '( =blue)') def test_prompt_enter_again(self): self.stuff('\n') answer = prompt('\nPress Enter again:') self.assertEqual('', answer) def test_prompt_enter_require_answer(self): self.explain(''' This test checks to see whether we can force the user to give an answer. THE FIRST TIME you are prompted, PRESS ENTER. The second time, give a real answer. ''') self.stuff('\nFred\ny\n') answer = prompt('What is your name?', default=None) self.assertTrue(prompt_bool('Were you re-prompted?')) self.assertStdout(_text_repeats, 'your name') class AutomatedPromptTest(InteractivePromptTest): def assertStdout(self, func, arg): self.assertTrue(func(sys.stdout.getvalue(), arg)) def stuff(self, txt_for_stdin): sys.stdin.write(txt_for_stdin) sys.stdin.seek(0) def explain(self, txt): pass def setUp(self): self.stdout = sys.stdout sys.stdout = StringIO.StringIO() self.stdin = sys.stdin sys.stdin = StringIO.StringIO() def tearDown(self): sys.stdout = self.stdout sys.stdin = self.stdin def test_prompt_masked(self): # getch can't be automatically overridden without side effects pass if __name__ == '__main__': tl = unittest.TestLoader() if '--interactive' in sys.argv: suite = tl.loadTestsFromTestCase(InteractivePromptTest) else: suite = tl.loadTestsFromTestCase(AutomatedPromptTest) tr = unittest.TextTestRunner() result = tr.run(suite) sys.exit(int(not result.wasSuccessful()))
perfectsearch/sandman
test/buildscripts/textui_prompt_test.py
Python
mit
6,007
import sys; import os sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) from flask import Flask, render_template, request, redirect import subprocess from Utils import subprocess_helpers from Utils.DataSource import * app = Flask(__name__) dataSource = DataSource() def launch_preprocessors(): process = subprocess.Popen( subprocess_helpers.python_path + " Daemons/QueryProcessorDaemon.py && " + subprocess_helpers.python_path + " Daemons/ArticleProcessorDaemon.py", executable=subprocess_helpers.executable, shell=True, universal_newlines=True) @app.route("/", methods=["GET"]) def queries(): # Get lists of query from database with counts of associated articles all_queries = dataSource.queries_route() queries_formatted = [{"id": q[0], "subject": q[1], "verb": q[2], "direct_obj": q[3], "indirect_obj": q[4], "loc": q[5], "article_count": q[6]} for q in all_queries] return render_template("queries.html", queries=queries_formatted) @app.route("/query", methods=["POST"]) def new_query(): # TODO: server side validation subject = request.form["subject"] verb = request.form["verb"] direct_obj = request.form["direct-object"] indirect_obj = request.form["indirect-object"] loc = request.form["location"] email = request.form["user-email"] phone = request.form["user-phone"] # Put into database dataSource.new_query(email, phone, subject, verb, direct_obj, indirect_obj, loc) return redirect("/") @app.route("/query/<query_id>", methods=["GET"]) def query(query_id): # find query by id # if we don't find a query with that id, 404 articles, db_query = dataSource.query_route(query_id) if db_query is not None: articles_formatted = [{"title": a[0], "source": a[1], "url": a[2]} for a in articles] query_formatted = {"id": db_query[0], "subject": db_query[1], "verb": db_query[2], "direct_obj": db_query[3], "indirect_obj": db_query[4], "loc": db_query[5]} return render_template("query.html", query=query_formatted, articles=articles_formatted) return render_template("404.html"), 404 @app.route("/articles", methods=["GET"]) def articles(): articles = dataSource.articles_route() articles_formatted = [{"title": a[0], "source": a[1], "url": a[2]} for a in articles] return render_template("articles.html", articles=articles_formatted) @app.errorhandler(404) def page_not_found(e): return render_template("404.html"), 404 if __name__ == "__main__": app.run(debug=True)
beallej/event-detection
WebApp/EventDetectionWeb.py
Python
mit
2,619
import pygame from pygame.locals import * import constants as c class Enemy: def __init__(self, x, y, health, movement_pattern, direction, img): self.x = x self.y = y self.health = health self.movement_pattern = movement_pattern self.direction = direction self.img = img def update(self, platforms_list, WORLD, avatar): # do updates based on movement_pattern if self.movement_pattern == "vertical": if self.direction == "up": self.y -= 2 elif self.direction == "down": self.y += 2 else: self.y = self.y if self.y > avatar.y + 30: self.direction = "up" elif self.y < avatar.y - 30: self.direction = "down" else: self.direction = "stay" self.display(WORLD) def display(self, WORLD): WORLD.blit(self.img, (self.x, self.y))
naomi-/exploration
Enemy.py
Python
mit
1,023
import os from angular_flask import app from flask.ext.restless import APIManager from flask.ext.mongoengine import MongoEngine app.config["MONGODB_SETTINGS"] = {'DB':os.environ.get('MONGODB_DB'),"host":os.environ.get('MONGODB_URI')} mongo_db = MongoEngine(app) api_manager = APIManager(app)
ascension/angular-flask-mongo
angular_flask/core.py
Python
mit
298
import asyncio try: from unittest.mock import Mock, create_autospec except ImportError: from mock import Mock, create_autospec from uuid import uuid4 from functools import wraps from copy import copy from unittest import TestCase as unittestTestCase from zeroservices.exceptions import ServiceUnavailable from zeroservices.resources import (ResourceCollection, Resource, is_callable, ResourceService) from zeroservices.medium import BaseMedium from zeroservices.medium.memory import MemoryMedium from zeroservices.discovery.memory import MemoryDiscoveryMedium from zeroservices.memory import MemoryCollection, MemoryResource from zeroservices import BaseService from zeroservices.query import match class TestCase(unittestTestCase): def assertItemsEqual(self, *args): if hasattr(self, 'assertCountEqual'): return self.assertCountEqual(*args) return super(TestCase, self).assertItemsEqual(*args) def assertDictIsSubset(self, subset, superset): for item in subset.items(): self.assertIn(item, superset.items()) def test_medium(): return Mock(spec_set=BaseMedium) class TestResource(MemoryResource): @is_callable def custom_action(self, *arhs, **kwargs): return 42 class TestCollection(MemoryCollection): resource_class = TestResource @is_callable def custom_action(self, *args, **kwargs): return 42 def sample_collection(sample_resource_name): return TestCollection(sample_resource_name) class TestService(BaseService): def __init__(self, *args, node_infos=None, **kwargs): super().__init__(*args, **kwargs) self.on_message_mock = Mock() self.on_event_mock = Mock() self.node_infos = node_infos or {} def service_info(self): base_infos = copy(self.node_infos) base_infos.update(super().service_info()) return base_infos @asyncio.coroutine def on_message(self, *args, **kwargs): return self.on_message_mock(*args, **kwargs) @asyncio.coroutine def on_event(self, *args, **kwargs): return self.on_event_mock(*args, **kwargs) def _create_test_service(name, node_infos, loop): medium = MemoryMedium(loop, MemoryDiscoveryMedium) service = TestService(name, medium, node_infos=node_infos) return service class TestResourceService(ResourceService): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.on_event_mock = Mock() @asyncio.coroutine def on_event(self, *args, **kwargs): return self.on_event_mock(*args, **kwargs) def _create_test_resource_service(name, loop): medium = MemoryMedium(loop, MemoryDiscoveryMedium) service = TestResourceService(name, medium) return service def _async_test(f): @wraps(f) def wrapper(self, *args, **kwargs): if not self.loop.is_running(): coro = asyncio.coroutine(f) future = coro(self, *args, **kwargs) self.loop.run_until_complete(asyncio.wait_for(future, 2, loop=self.loop)) else: return f(self, *args, **kwargs) return wrapper
Lothiraldan/ZeroServices
tests/utils.py
Python
mit
3,193
""" The classes `Token` and `Nonterm` can be subclassed and enriched with docstrings indicating the intended grammar, and will then be used in the parsing as part of the abstract syntax tree that is constructed in the process. """ from __future__ import annotations class Symbol: pass class Nonterm(Symbol): """ Non-terminal symbols have sets of productions associated with them. The productions induce a parse forest on an input token stream. There is one special non-terminal, which is denoted via the %start directive, whereas all other non-terminals are denoted via the %nonterm directive. In addition to productions (%reduce directives associated with class methods), the merge() method may be called during resolution of ambiguous parses. See the merge() documentation for further details. Following are examples of how to specify non-terminal classes and their associated productions: class E(Parsing.Nonterm): "%start E" def __init__(self): Parsing.Nonterm.__init__(self) # ... # Productions. def reduceA(self, E, plus, T): "%reduce E plus T [split]" print "%r ::= %r %r %r." % (self, E, plus, T) def reduceB(self, T): "%reduce T" class T(Parsing.Nonterm): "%nonterm" # Name implicitly same as class name. def reduceA(self, T, star, F): "%reduce T star F" def reduceB(self, F): "%reduce F [p1]" class F(Parsing.Nonterm): "%nonterm F [p2]" def reduceA(self, lparen, E, rparen): "%reduce lparen E rparen" def reduceB(self, id): "%reduce id" """ def merge(self, other: Nonterm) -> Nonterm: """ Merging happens when there is an ambiguity in the input that allows non-terminals to be part of multiple overlapping series of reductions. If no merge() method is specified, the parser will throw a syntax error upon encountering an ambiguity that confounds reduction processing. However, it may be useful to either discard one of the possible parses, or to explicitly record the ambiguity in the data structures being created during parsing. In both of these cases, the non-terminal-specific merge() is the place to do the work; merge() returns an object that is stored by the parser onto the parse stack. In the case where merge() discards one of the possible parses, it need only return the parse that is to be preserved (self or other). If multiple merges are necessary, they cause a series of merge() calls. The first alternative (self) may be the result of a previous merge() call, whereas other will not have not been merged yet (unless as the result of merging further down in the parse forest). The alternative that is discarded is never touched by the parser again, so if any immediate cleanup is necessary, it should be done in merge(). """ raise SyntaxError( "No merge() for %r; merging %r <--> %r" % (type(self), self, other) ) class Token(Symbol): """ Tokens are terminal symbols. The parser is fed Token instances, which is what drives parsing. Typically, the user will define a class that subclasses Parsing.Token and implement parser-specific machinery there, then derive all actual token types from that class. class Token(Parsing.Token): def __init__(self, parser): Parsing.Token.__init__(self, parser) # ... class Plus(Token): "%token plus [p1]" class star(Token): "%token star [p2]" # Name implicitly same as class name. class lparen(Token): "%token [split]" class rparen(Token): "%token [none]" # [none] not necessary, since it's the default. class id(Token): "%token" """ class Precedence: """ Precedences can be associated with tokens, non-terminals, and productions. Precedence isn't as important for GLR parsers as for LR parsers, since GLR parsing allows for parse-time resolution of ambiguity. Still, precedence can be useful for reducing the volume of ambiguities that must be dealt with at run-time. There are five precedence types: %fail, %nonassoc, %left, %right, and %split. Each precedence can have relationships with other precedences: <, >, or =. These relationships specify a directed acyclic graph (DAG), which is used to compute the transitive closures of relationships among precedences. If no path exists between two precedences that are compared during conflict resolution, parser generation fails. < and > are reflexive; it does not matter which is used. Conceptually, the = relationship causes precedences to share a node in the DAG. During conflict resolution, an error results if no path exists in the DAG between the precedences under consideration. When such a path exists, the highest precedence non-terminal or production takes precedence. Associativity only comes into play for shift/reduce conflicts, where the terminal and the production have equivalent precedences (= relationship). In this case, the non-terminal's associativity determines how the conflict is resolved. The %fail and %split associativities are special because they can be mixed with other associativities. During conflict resolution, if another action has non-%fail associativity, then the %fail (lack of) associativity is overridden. Similarly, %split associativity overrides any other associativity. In contrast, any mixture of associativity between %nonassoc/%left/%right causes an unresolvable conflict. %fail : Any conflict is a parser-generation-time error. A pre-defined precedence, [none], is provided. It has %fail associativity, and has no pre-defined precedence relationships. %nonassoc : Resolve shift/reduce conflicts by removing both possibilities, thus making conflicts a parse-time error. %left : Resolve shift/reduce conflicts by reducing. %right : Resolve shift/reduce conflicts by shifting. %split : Do not resolve conflicts; the GLR algorithm will split the parse stack when necessary. A pre-defined precedence, [split], is provided. It has %split associativity, and has no pre-defined precedence relationships. By default, all symbols have [none] precedence. Each production inherits the precedence of its left-hand-side nonterminal's precedence unless a precedence is manually specified for the production. Following are some examples of how to specify precedence classes: class P1(Parsing.Precedence): "%split p1" class p2(Parsing.Precedence): "%left" # Name implicitly same as class name. class P3(Parsing.Precedence): "%left p3 >p2" # No whitespace is allowed between > and p2. class P4(Parsing.Precedence): "%left p4 =p3" # No whitespace is allowed between = and p3. """
sprymix/parsing
parsing/ast.py
Python
mit
7,301
from distutils.dir_util import copy_tree, remove_tree import os import shutil def _copy_function(source, destination): print('Bootstrapping project at %s' % destination) copy_tree(source, destination) def create_app(): cwd = os.getcwd() game_logic_path = os.path.join(cwd, 'game_logic') game_app_interface = os.path.join(cwd, 'game_app.py') app_template = os.path.join(cwd, 'engine', 'app_template') _game_logic_path_exists = os.path.exists(game_logic_path) _game_app_interface_exists = os.path.exists(game_app_interface) if _game_logic_path_exists or _game_app_interface_exists: answer = input( 'game_app.py or game_logic module already exists. Continue? (y/n). ' + '\nWARNING: This will remove all contents of game_logic module, use at your own risk:'.upper() ) if answer == 'y': if _game_app_interface_exists: os.remove(game_app_interface) if _game_logic_path_exists: remove_tree(game_logic_path) _copy_function(app_template, cwd) else: _copy_function(app_template, cwd) if not os.path.exists('settings.yaml'): shutil.copy2('settings.yaml.template', 'settings.yaml') if not os.path.exists('logging.yaml'): shutil.copy2('logging.yaml.template', 'logging.yaml') if __name__ == '__main__': create_app()
kollad/turbo-ninja
tools/bootstrap.py
Python
mit
1,403
from tc_python.arule import ARule from t_core.messages import Packet from HA import HA from HAb import HAb from HTopClass2TableLHS import HTopClass2TableLHS from HTopClass2TableRHS import HTopClass2TableRHS r1 = ARule(HTopClass2TableLHS(), HTopClass2TableRHS()) p = Packet() p.graph = HA() p1 = r1.packet_in(p) print p1 print r1.is_success if r1.exception: raise r1.exception r2 = ARule(HTopClass2TableLHS(), HTopClass2TableRHS()) p = Packet() p.graph = HAb() p2 = r2.packet_in(p) print p2 print r2.is_success if r2.exception: raise r2.exception
levilucio/SyVOLT
t_core/main.py
Python
mit
589
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page class SubscribedTrackList(ListResource): """ """ def __init__(self, version, room_sid, participant_sid): """ Initialize the SubscribedTrackList :param Version version: Version that contains the resource :param room_sid: The SID of the room where the track is published :param participant_sid: The SID of the participant that subscribes to the track :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList """ super(SubscribedTrackList, self).__init__(version) # Path Solution self._solution = {'room_sid': room_sid, 'participant_sid': participant_sid, } self._uri = '/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks'.format(**self._solution) def stream(self, limit=None, page_size=None): """ Streams SubscribedTrackInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param int limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance] """ limits = self._version.read_limits(limit, page_size) page = self.page(page_size=limits['page_size'], ) return self._version.stream(page, limits['limit'], limits['page_limit']) def list(self, limit=None, page_size=None): """ Lists SubscribedTrackInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance] """ return list(self.stream(limit=limit, page_size=page_size, )) def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of SubscribedTrackInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage """ params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page( 'GET', self._uri, params=params, ) return SubscribedTrackPage(self._version, response, self._solution) def get_page(self, target_url): """ Retrieve a specific page of SubscribedTrackInstance records from the API. Request is executed immediately :param str target_url: API-generated URL for the requested results page :returns: Page of SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage """ response = self._version.domain.twilio.request( 'GET', target_url, ) return SubscribedTrackPage(self._version, response, self._solution) def get(self, sid): """ Constructs a SubscribedTrackContext :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext """ return SubscribedTrackContext( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['participant_sid'], sid=sid, ) def __call__(self, sid): """ Constructs a SubscribedTrackContext :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext """ return SubscribedTrackContext( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['participant_sid'], sid=sid, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.SubscribedTrackList>' class SubscribedTrackPage(Page): """ """ def __init__(self, version, response, solution): """ Initialize the SubscribedTrackPage :param Version version: Version that contains the resource :param Response response: Response from the API :param room_sid: The SID of the room where the track is published :param participant_sid: The SID of the participant that subscribes to the track :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage """ super(SubscribedTrackPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of SubscribedTrackInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance """ return SubscribedTrackInstance( self._version, payload, room_sid=self._solution['room_sid'], participant_sid=self._solution['participant_sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.SubscribedTrackPage>' class SubscribedTrackContext(InstanceContext): """ """ def __init__(self, version, room_sid, participant_sid, sid): """ Initialize the SubscribedTrackContext :param Version version: Version that contains the resource :param room_sid: The SID of the Room where the Track resource to fetch is subscribed :param participant_sid: The SID of the participant that subscribes to the Track resource to fetch :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext """ super(SubscribedTrackContext, self).__init__(version) # Path Solution self._solution = {'room_sid': room_sid, 'participant_sid': participant_sid, 'sid': sid, } self._uri = '/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks/{sid}'.format(**self._solution) def fetch(self): """ Fetch a SubscribedTrackInstance :returns: Fetched SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return SubscribedTrackInstance( self._version, payload, room_sid=self._solution['room_sid'], participant_sid=self._solution['participant_sid'], sid=self._solution['sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.SubscribedTrackContext {}>'.format(context) class SubscribedTrackInstance(InstanceResource): """ """ class Kind(object): AUDIO = "audio" VIDEO = "video" DATA = "data" def __init__(self, version, payload, room_sid, participant_sid, sid=None): """ Initialize the SubscribedTrackInstance :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance """ super(SubscribedTrackInstance, self).__init__(version) # Marshaled Properties self._properties = { 'sid': payload.get('sid'), 'participant_sid': payload.get('participant_sid'), 'publisher_sid': payload.get('publisher_sid'), 'room_sid': payload.get('room_sid'), 'name': payload.get('name'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'enabled': payload.get('enabled'), 'kind': payload.get('kind'), 'url': payload.get('url'), } # Context self._context = None self._solution = { 'room_sid': room_sid, 'participant_sid': participant_sid, 'sid': sid or self._properties['sid'], } @property def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SubscribedTrackContext for this SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext """ if self._context is None: self._context = SubscribedTrackContext( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['participant_sid'], sid=self._solution['sid'], ) return self._context @property def sid(self): """ :returns: The unique string that identifies the resource :rtype: unicode """ return self._properties['sid'] @property def participant_sid(self): """ :returns: The SID of the participant that subscribes to the track :rtype: unicode """ return self._properties['participant_sid'] @property def publisher_sid(self): """ :returns: The SID of the participant that publishes the track :rtype: unicode """ return self._properties['publisher_sid'] @property def room_sid(self): """ :returns: The SID of the room where the track is published :rtype: unicode """ return self._properties['room_sid'] @property def name(self): """ :returns: The track name :rtype: unicode """ return self._properties['name'] @property def date_created(self): """ :returns: The ISO 8601 date and time in GMT when the resource was created :rtype: datetime """ return self._properties['date_created'] @property def date_updated(self): """ :returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime """ return self._properties['date_updated'] @property def enabled(self): """ :returns: Whether the track is enabled :rtype: bool """ return self._properties['enabled'] @property def kind(self): """ :returns: The track type :rtype: SubscribedTrackInstance.Kind """ return self._properties['kind'] @property def url(self): """ :returns: The absolute URL of the resource :rtype: unicode """ return self._properties['url'] def fetch(self): """ Fetch a SubscribedTrackInstance :returns: Fetched SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance """ return self._proxy.fetch() def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.SubscribedTrackInstance {}>'.format(context)
tysonholub/twilio-python
twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py
Python
mit
15,072
############################################################################### # Name: __init__.py # # Purpose: Put the src package in the Editra packages namespace # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2007 Cody Precord <staff@editra.org> # # Licence: wxWindows Licence # ############################################################################### """Main package initializer""" __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: __init__.py 49807 2007-11-10 07:08:33Z CJP $" __revision__ = "$Revision: 49807 $"
ktan2020/legacy-automation
win/Lib/site-packages/wx-3.0-msw/wx/tools/Editra/__init__.py
Python
mit
756
"""Interface to rpy2.glm Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ import rpy2.robjects as robjects r = robjects.r def linear_model(model, print_flag=True): """Submits model to r.lm and returns the result.""" model = r(model) res = r.lm(model) if print_flag: print_summary(res) return res def logit_model(model, family=robjects.r.binomial(), weights=None, print_flag=True): """Submits model to r.glm and returns the result.""" model = r(model) if weights is None: res = r.glm(model, family=family) else: weight_vector = robjects.FloatVector(weights) res = r.glm(model, family=family, weights=weight_vector) if print_flag: print_summary(res) return res def print_summary(res): """Prints results from r.lm (just the parts we want).""" flag = False lines = r.summary(res) lines = str(lines) for line in lines.split('\n'): # skip everything until we get to coefficients if line.startswith('Coefficients'): flag = True if line.startswith('Signif'): continue if flag: print line print def get_coeffs(res): """Gets just the lines that contain the estimates. res: R glm result object Returns: list of (name, estimate, error, z-value) tuples and AIC """ flag = False lines = r.summary(res) lines = str(lines) res = [] aic = None for line in lines.split('\n'): #print "line: " + str(line) line = line.strip() #print "lineStrip: " + str(line) if line.startswith('---') or line == "": #print "startswith('---')" flag = False if line.startswith('AIC'): #print "startswith('AIC')" t = line.split() aic = float(t[1]) if flag: #print "flag" t = line.split() #print "t: " + str(t) var = t[0] est = float(t[1]) error = float(t[2]) z = float(t[3]) res.append((var, est, error, z)) if line.startswith('Estimate'): #print "startswith('Estimate')" flag = True return res, aic def inject_col_dict(col_dict, prefix=''): """Copies data columns into the R global environment. col_dict: map from attribute name to column of data prefix: string prepended to the attribute names """ for name, col in col_dict.iteritems(): robjects.globalenv[prefix+name] = robjects.FloatVector(col)
MaciCrowell/TCGA_DataScience
glm.py
Python
mit
2,658
""" General functions for HTML manipulation, backported from Py3. Note that this uses Python 2.7 code with the corresponding Python 3 module names and locations. """ from __future__ import unicode_literals _escape_map = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;'} _escape_map_full = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;', ord('"'): '&quot;', ord('\''): '&#x27;'} # NB: this is a candidate for a bytes/string polymorphic interface def escape(s, quote=True): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ assert not isinstance(s, bytes), 'Pass a unicode string' if quote: return s.translate(_escape_map_full) return s.translate(_escape_map)
thonkify/thonkify
src/lib/future/backports/html/__init__.py
Python
mit
924
# ============================================================================= # Federal University of Rio Grande do Sul (UFRGS) # Connectionist Artificial Intelligence Laboratory (LIAC) # Renato de Pontes Pereira - renato.ppontes@gmail.com # ============================================================================= # Copyright (c) 2011 Renato de Pontes Pereira, renato.ppontes at gmail dot com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ============================================================================= from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import psi from psi.calc import clip from psi.euclid import Vector2 __all__ = ['Camera'] class Camera(object): def __init__(self, pos=Vector2(0, 0)): self.pos = pos self.half_size = Vector2(300, 300) self.zoom = 1.0 self._zoom_step = 0.5 self._scale_rate = 1/self.zoom def adjust(self, old_scale, new_scale): pass def zoom_out(self): self.zoom = clip(self.zoom+self._zoom_step, self._zoom_step, 10.5) old = self._scale_rate self._scale_rate = 1/self.zoom self.adjust(old, self._scale_rate) def zoom_in(self): self.zoom = clip(self.zoom-self._zoom_step, self._zoom_step, 10.5) old = self._scale_rate self._scale_rate = 1/self.zoom self.adjust(old, self._scale_rate) def reset_zoom(self): self.zoom = 1. self._scale_rate = 1/self.zoom def pan(self, delta): self.pos += delta def locate(self): glTranslatef(-self.pos.x+self.half_size.x, -self.pos.y+self.half_size.y, 0) glScalef(self._scale_rate, self._scale_rate, 0) def on_window_resize(self, size): half_size = size/2. diff = self.half_size - half_size # print self.half_size, '=>', half_size, '=', diff self.half_size = half_size # self.pan(-diff/4.)
renatopp/psi-robotics
psi/engine/camera.py
Python
mit
2,961
#! /usr/bin/python # Joe Deller 2014 # Using for loops # Level : Beginner # Uses : Libraries, variables, operators, loops # Loops are a very important part of programming # The for loop is a very common loop # It counts from a starting number to a finishing number # It normally counts up in ones, but you can count up # in any number you want, or count downwards # # The wool block in minecraft can be any one of 16 different colours # from 0, a white block, to 15, a black block # This program uses a for loop to draw wool blocks # of all 16 different colours # It also uses the for loop to set where the block is drawn # so we can see all 16 colours import mcpi.minecraft as minecraft import mcpi.block as block import time # Setup the connection and clear a space # set us down in the middle of the world mc = minecraft.Minecraft.create() x, y, z = mc.player.getPos() mc.setBlocks(x - 20, y, z - 20, x + 20, y + 20, z + 20, block.AIR) mc.setBlocks(z - 20, y - 1, z - 20, y, z + 20, block.GRASS.id) for colour in range(0, 15): # draw upwards mc.setBlock(x + 15, y + 2 + colour, z + 2, block.WOOL.id, colour) # draw across mc.setBlock(x + colour, y + 2, z + 2, block.WOOL.id, colour) time.sleep(.5) # Counting backwards, using a negative number to say how quickly to count backwards # Try changing this to -2 and see what happens for colour in range(15, 0, -1): mc.setBlock(x, 1 + colour, z + 2, block.WOOL.id, colour) mc.setBlock(colour, y + 16, z + 2, block.WOOL.id, colour) time.sleep(.1)
joedeller/pymine
forloop.py
Python
mit
1,535
# import .1dslicefrom3d import artistools.makemodel.botyanski2017
lukeshingles/artistools
artistools/makemodel/__init__.py
Python
mit
65
from .Confusion_MI import* from .Cov_Mat import * from .SaveLoadModel import *
L-F-A/Machine-Learning
General/__init__.py
Python
mit
79
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) -> MSSBase """ Factory returning a proper MSS class instance. It detects the platform we are running on and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darwin.MSS(**kwargs) if os_ == "linux": from . import linux return linux.MSS(**kwargs) if os_ == "windows": from . import windows return windows.MSS(**kwargs) raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
BoboTiG/python-mss
mss/factory.py
Python
mit
1,032
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from functools import reduce # noqa except Exception: pass try: from .tornado_handler import TornadoHandler # noqa except ImportError: pass from .environmentdump import EnvironmentDump # noqa from .healthcheck import HealthCheck # noqa
ateliedocodigo/py-healthcheck
healthcheck/__init__.py
Python
mit
310
#!/usr/bin/env python3 import threading def worker(): print('new worker') for i in range(8): threading.Thread(target = worker).start()
dubrayn/dubrayn.github.io
examples/threading/example0.py
Python
mit
143
class Solution: def decodeString(self, s: str) -> str: St = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '[': St.append([num, curr]) num = 0 curr = '' elif c == ']': count, prev = St.pop() curr = prev + count*curr else: curr += c return curr class Solution2: def decodeString(self, s: str) -> str: i = 0 def decode(s): nonlocal i result = [] while i < len(s) and s[i] != ']': if s[i].isdigit(): num = 0 while i < len(s) and s[i].isdigit(): num = num*10 + int(s[i]) i += 1 i += 1 temp = decode(s) i += 1 result += temp*num else: result.append(s[i]) i += 1 return result return ''.join(decode(s))
jiadaizhao/LeetCode
0301-0400/0394-Decode String/0394-Decode String.py
Python
mit
1,173
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Data, and to # permit persons to whom the Data 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 Data. # THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. # ======================= # This version of the META tools is a fork of an original version produced # by Vanderbilt University's Institute for Software Integrated Systems (ISIS). # Their license statement: # Copyright (C) 2011-2014 Vanderbilt University # Developed with the sponsorship of the Defense Advanced Research Projects # Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights # as defined in DFARS 252.227-7013. # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Data, and to # permit persons to whom the Data 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 Data. # THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. import os import datetime import logging from py_modelica.exception_classes import ModelicaInstantiationError from abc import ABCMeta, abstractmethod class ToolBase: __metaclass__ = ABCMeta tool_name = '' tool_version = '' tool_version_nbr = '' model_config = None date_time = '' ## instance variables tool_path = '' # path to the bin folder of the tool model_file_name = '' # file that needs to be loaded model_name = '' # name of the model in the loaded packages msl_version = '' # version of Modelica Standard Library mos_file_name = '' # modelica script files for compiling the model result_mat = '' # contains the latest simulation results base_result_mat = '' # contains the expected simulation results working_dir = '' # contains the temporary files and executables root_dir = '' mo_dir = '' # contains the modelica file, (package or model) output_dir = '' # relative or absolute variable_filter = [] # list of names of variables to save/load to/from mat-file experiment = {} # dictionary with StartTime, StopTime, Tolerance, # NumberOfIntervals, Interval and Algorithm. model_is_compiled = False # flag for telling if the model was compiled model_did_simulate = False # flag for telling if the model has been simulated lib_package_paths = [] # paths to additional packages lib_package_names = [] # names of additional packages max_simulation_time = 43200 # (=12h) time threshold before simulation is aborted ## Variables with execution statistics compilation_time = -1 translation_time = -1 make_time = -1 simulation_time = -1 total_time = -1 def _initialize(self, model_config): """ Creates a new instance of a modelica simulation. dictionary : model_config Mandatory Keys : 'model_name' (str), 'model_file_name' (str) Optional Keys : 'MSL_version' (str), 'variable_filter' ([str]), 'result_file' (str), 'experiment' ({str}) """ print ' --- ===== See debug.log for error/debug messages ===== --- \n' print ' in {0}'.format(os.getcwd()) # create a logger, (will only be written to if no other logger defined 'higher' up) logging.basicConfig(filename="debug.log", format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S") log = logging.getLogger() # always use highest level of debugging log.setLevel(logging.DEBUG) log.debug(" --- ==== ******************************* ==== ---") log.info(" --- ==== ******* New Run Started ******* ==== ---") self.date_time = '{0}'.format(datetime.datetime.today()) log.debug(" --- ==== * {0} ** ==== ---".format(self.date_time)) log.debug(" --- ==== ******************************* ==== ---") log.debug("Entered _initialize") log.info("tool_name : {0}".format(self.tool_name)) log.info("tool_path : {0}".format(self.tool_path)) self.root_dir = os.getcwd() self.model_config = model_config # Mandatory keys in dictionary try: model_file_name = self.model_config['model_file_name'] if model_file_name == "": self.model_file_name = "" log.info("No model_file name given, assumes model is in Modelica Standard Library") else: self.model_file_name = os.path.normpath(os.path.join(os.getcwd(), model_file_name)) self.mo_dir = os.path.dirname(self.model_file_name) log.info("mo_dir : {}".format(self.mo_dir)) log.info("model_file_name : {0}".format(self.model_file_name)) model_name = self.model_config['model_name'] if model_name == "": base_name = os.path.basename(model_file_name) self.model_name = os.path.splitext(base_name)[0] log.info("No model_name given, uses model_file_name without .mo") else: self.model_name = model_name log.info("model_name : {0}".format(self.model_name)) except KeyError as err: raise ModelicaInstantiationError("Mandatory key missing in model_config : {0}".format(err.message)) # optional keys in dictionary if 'MSL_version' in model_config: self.msl_version = self.model_config['MSL_version'] else: self.msl_version = "3.2" log.info("msl_version : {0}".format(self.msl_version)) if 'experiment' in model_config: self.experiment = dict( StartTime=model_config['experiment']['StartTime'], StopTime=model_config['experiment']['StopTime'], NumberOfIntervals=model_config['experiment']['NumberOfIntervals'], Tolerance=model_config['experiment']['Tolerance']) # Algorithm if 'Algorithm' in model_config['experiment']: if self.tool_name.startswith('Dymola'): self.experiment.update({'Algorithm': self.model_config['experiment']['Algorithm']['Dymola']}) elif self.tool_name == 'OpenModelica': self.experiment.update({'Algorithm': self.model_config['experiment']['Algorithm']['OpenModelica']}) elif self.tool_name == 'JModelica': self.experiment.update({'Algorithm': self.model_config['experiment']['Algorithm']['JModelica']}) else: # py_modelica 12.09 self.experiment.update({'Algorithm': 'dassl'}) # Interval if 'IntervalMethod' in model_config['experiment']: if model_config['experiment']['IntervalMethod'] == 'Interval': self.experiment.update({"NumberOfIntervals": "0"}) self.experiment.update({"Interval": model_config['experiment']['Interval']}) else: self.experiment.update({"NumberOfIntervals": model_config['experiment']['NumberOfIntervals']}) self.experiment.update({"Interval": "0"}) else: # py_modelica 12.09 self.experiment.update({"NumberOfIntervals": model_config['experiment']['NumberOfIntervals']}) self.experiment.update({"Interval": "0"}) else: self.experiment = dict(StartTime='0', StopTime='1', NumberOfIntervals='500', Interval='0', Tolerance='1e-5', Algorithm='dassl') log.info("No experiment data given, default values will be used...") log.info("Experiment settings : {0}".format(self.experiment)) if 'lib_package_paths' in model_config: for lib_path in self.model_config['lib_package_paths']: if lib_path: self.lib_package_paths.append(str(lib_path)) if 'lib_package_names' in model_config: for lib_name in self.model_config['lib_package_names']: if lib_name: self.lib_package_names.append(lib_name) if os.name == 'nt': try: import _winreg as wr key = wr.OpenKey(wr.HKEY_LOCAL_MACHINE, r'software\meta', 0, wr.KEY_READ) try: self.max_simulation_time = wr.QueryValueEx(key, 'MAX_SIMULATION_TIME')[0] print 'Found MAX_SIMULATION_TIME in registry, value was {0} (={1:.1f} h).'\ .format(self.max_simulation_time, float(self.max_simulation_time)/3600) except WindowsError: print 'MAX_SIMULATION_TIME not set in registry, using default {0} (={1:.1f} h).'\ .format(self.max_simulation_time, float(self.max_simulation_time)/3600) except WindowsError: print 'META-Tools not installed, using default max_simulation_time at {0} (={1:.1f} h).'\ .format(self.max_simulation_time, float(self.max_simulation_time)/3600) # end of __initialize__ @abstractmethod def compile_model(self): return bool @abstractmethod def simulate_model(self): return bool @abstractmethod def change_experiment(self, start_time='0', stop_time='1', increment='', n_interval='500', tolerance='1e-5', max_fixed_step='', solver='dassl', output_format='', variable_filter=''): return bool @abstractmethod def change_parameter(self, change_dict): return bool
pombredanne/metamorphosys-desktop
metamorphosys/META/src/Python27Packages/py_modelica/py_modelica/modelica_simulation_tools/tool_base.py
Python
mit
12,494
# -*- coding: utf-8 -*- """ formlayout ========== Module creating Qt form dialogs/layouts to edit various type of parameters formlayout License Agreement (MIT License) ------------------------------------------ Copyright (c) 2009 Pierre Raybaut 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. """ # History: # 1.0.10: added float validator (disable "Ok" and "Apply" button when not valid) # 1.0.7: added support for "Apply" button # 1.0.6: code cleaning from __future__ import (absolute_import, division, print_function, unicode_literals) __version__ = '1.0.10' __license__ = __doc__ DEBUG = False import copy import datetime import warnings import six from matplotlib import colors as mcolors from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore BLACKLIST = set(["title", "label"]) class ColorButton(QtWidgets.QPushButton): """ Color choosing push button """ colorChanged = QtCore.Signal(QtGui.QColor) def __init__(self, parent=None): QtWidgets.QPushButton.__init__(self, parent) self.setFixedSize(20, 20) self.setIconSize(QtCore.QSize(12, 12)) self.clicked.connect(self.choose_color) self._color = QtGui.QColor() def choose_color(self): color = QtWidgets.QColorDialog.getColor( self._color, self.parentWidget(), "", QtWidgets.QColorDialog.ShowAlphaChannel) if color.isValid(): self.set_color(color) def get_color(self): return self._color @QtCore.Slot(QtGui.QColor) def set_color(self, color): if color != self._color: self._color = color self.colorChanged.emit(self._color) pixmap = QtGui.QPixmap(self.iconSize()) pixmap.fill(color) self.setIcon(QtGui.QIcon(pixmap)) color = QtCore.Property(QtGui.QColor, get_color, set_color) def to_qcolor(color): """Create a QColor from a matplotlib color""" qcolor = QtGui.QColor() try: rgba = mcolors.to_rgba(color) except ValueError: warnings.warn('Ignoring invalid color %r' % color) return qcolor # return invalid QColor qcolor.setRgbF(*rgba) return qcolor class ColorLayout(QtWidgets.QHBoxLayout): """Color-specialized QLineEdit layout""" def __init__(self, color, parent=None): QtWidgets.QHBoxLayout.__init__(self) assert isinstance(color, QtGui.QColor) self.lineedit = QtWidgets.QLineEdit( mcolors.to_hex(color.getRgbF(), keep_alpha=True), parent) self.lineedit.editingFinished.connect(self.update_color) self.addWidget(self.lineedit) self.colorbtn = ColorButton(parent) self.colorbtn.color = color self.colorbtn.colorChanged.connect(self.update_text) self.addWidget(self.colorbtn) def update_color(self): color = self.text() qcolor = to_qcolor(color) self.colorbtn.color = qcolor # defaults to black if not qcolor.isValid() def update_text(self, color): self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True)) def text(self): return self.lineedit.text() def font_is_installed(font): """Check if font is installed""" return [fam for fam in QtGui.QFontDatabase().families() if six.text_type(fam) == font] def tuple_to_qfont(tup): """ Create a QFont from tuple: (family [string], size [int], italic [bool], bold [bool]) """ if not (isinstance(tup, tuple) and len(tup) == 4 and font_is_installed(tup[0]) and isinstance(tup[1], int) and isinstance(tup[2], bool) and isinstance(tup[3], bool)): return None font = QtGui.QFont() family, size, italic, bold = tup font.setFamily(family) font.setPointSize(size) font.setItalic(italic) font.setBold(bold) return font def qfont_to_tuple(font): return (six.text_type(font.family()), int(font.pointSize()), font.italic(), font.bold()) class FontLayout(QtWidgets.QGridLayout): """Font selection""" def __init__(self, value, parent=None): QtWidgets.QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QtWidgets.QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QtWidgets.QComboBox(parent) self.size.setEditable(True) sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.size.setCurrentIndex(sizelist.index(size)) self.addWidget(self.size, 1, 0) # Italic or not self.italic = QtWidgets.QCheckBox(self.tr("Italic"), parent) self.italic.setChecked(font.italic()) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QtWidgets.QCheckBox(self.tr("Bold"), parent) self.bold.setChecked(font.bold()) self.addWidget(self.bold, 1, 2) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font) def is_edit_valid(edit): text = edit.text() state = edit.validator().validate(text, 0)[0] return state == QtGui.QDoubleValidator.Acceptable class FormWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, data, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) self.data = copy.deepcopy(data) self.widgets = [] self.formlayout = QtWidgets.QFormLayout(self) if comment: self.formlayout.addRow(QtWidgets.QLabel(comment)) self.formlayout.addRow(QtWidgets.QLabel(" ")) if DEBUG: print("\n"+("*"*80)) print("DATA:", self.data) print("*"*80) print("COMMENT:", comment) print("*"*80) def get_dialog(self): """Return FormDialog instance""" dialog = self.parent() while not isinstance(dialog, QtWidgets.QDialog): dialog = dialog.parent() return dialog def setup(self): # self.formlayout.setFieldGrowthPolicy(1) for label, value in self.data: if DEBUG: print("value:", value) if label is None and value is None: # Separator: (None, None) self.formlayout.addRow(QtWidgets.QLabel(" "), QtWidgets.QLabel(" ")) self.widgets.append(None) continue elif label is None: # Comment self.formlayout.addRow(QtWidgets.QLabel(value)) self.widgets.append(None) continue elif tuple_to_qfont(value) is not None: field = FontLayout(value, self) elif (label.lower() not in BLACKLIST and mcolors.is_color_like(value)): field = ColorLayout(to_qcolor(value), self) elif isinstance(value, six.string_types): field = QtWidgets.QLineEdit(value, self) field.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)) elif isinstance(value, (list, tuple)): if isinstance(value, tuple): value = list(value) selindex = value.pop(0) field = QtWidgets.QComboBox(self) if isinstance(value[0], (list, tuple)): keys = [key for key, _val in value] value = [val for _key, val in value] else: keys = value field.addItems(value) if selindex in value: selindex = value.index(selindex) elif selindex in keys: selindex = keys.index(selindex) elif not isinstance(selindex, int): warnings.warn( "index '%s' is invalid (label: %s, value: %s)" % (selindex, label, value)) selindex = 0 field.setCurrentIndex(selindex) elif isinstance(value, bool): field = QtWidgets.QCheckBox(self) if value: field.setCheckState(QtCore.Qt.Checked) else: field.setCheckState(QtCore.Qt.Unchecked) elif isinstance(value, float): field = QtWidgets.QLineEdit(repr(value), self) field.setCursorPosition(0) field.setValidator(QtGui.QDoubleValidator(field)) field.validator().setLocale(QtCore.QLocale("C")) dialog = self.get_dialog() dialog.register_float_field(field) field.textChanged.connect(lambda text: dialog.update_buttons()) elif isinstance(value, int): field = QtWidgets.QSpinBox(self) field.setRange(-1e9, 1e9) field.setValue(value) elif isinstance(value, datetime.datetime): field = QtWidgets.QDateTimeEdit(self) field.setDateTime(value) elif isinstance(value, datetime.date): field = QtWidgets.QDateEdit(self) field.setDate(value) else: field = QtWidgets.QLineEdit(repr(value), self) self.formlayout.addRow(label, field) # print(self.formlayout.fieldGrowthPolicy()) self.widgets.append(field) def get(self): valuelist = [] for index, (label, value) in enumerate(self.data): field = self.widgets[index] if label is None: # Separator / Comment continue elif tuple_to_qfont(value) is not None: value = field.get_font() elif (isinstance(value, six.string_types) or mcolors.is_color_like(value)): value = six.text_type(field.text()) elif isinstance(value, (list, tuple)): index = int(field.currentIndex()) if isinstance(value[0], (list, tuple)): value = value[index][0] else: value = value[index] elif isinstance(value, bool): value = field.checkState() == QtCore.Qt.Checked elif isinstance(value, float): value = float(str(field.text())) elif isinstance(value, int): value = int(field.value()) elif isinstance(value, datetime.datetime): value = field.dateTime().toPyDateTime() elif isinstance(value, datetime.date): value = field.date().toPyDate() else: value = eval(str(field.text())) valuelist.append(value) return valuelist class FormComboWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.combobox = QtWidgets.QComboBox() layout.addWidget(self.combobox) self.stackwidget = QtWidgets.QStackedWidget(self) layout.addWidget(self.stackwidget) self.combobox.currentIndexChanged.connect(self.stackwidget.setCurrentIndex) self.widgetlist = [] for data, title, comment in datalist: self.combobox.addItem(title) widget = FormWidget(data, comment=comment, parent=self) self.stackwidget.addWidget(widget) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [widget.get() for widget in self.widgetlist] class FormTabWidget(QtWidgets.QWidget): update_buttons = QtCore.Signal() def __init__(self, datalist, comment="", parent=None): QtWidgets.QWidget.__init__(self, parent) layout = QtWidgets.QVBoxLayout() self.tabwidget = QtWidgets.QTabWidget() layout.addWidget(self.tabwidget) self.setLayout(layout) self.widgetlist = [] for data, title, comment in datalist: if len(data[0]) == 3: widget = FormComboWidget(data, comment=comment, parent=self) else: widget = FormWidget(data, comment=comment, parent=self) index = self.tabwidget.addTab(widget, title) self.tabwidget.setTabToolTip(index, comment) self.widgetlist.append(widget) def setup(self): for widget in self.widgetlist: widget.setup() def get(self): return [widget.get() for widget in self.widgetlist] class FormDialog(QtWidgets.QDialog): """Form Dialog""" def __init__(self, data, title="", comment="", icon=None, parent=None, apply=None): QtWidgets.QDialog.__init__(self, parent) self.apply_callback = apply # Form if isinstance(data[0][0], (list, tuple)): self.formwidget = FormTabWidget(data, comment=comment, parent=self) elif len(data[0]) == 3: self.formwidget = FormComboWidget(data, comment=comment, parent=self) else: self.formwidget = FormWidget(data, comment=comment, parent=self) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.formwidget) self.float_fields = [] self.formwidget.setup() # Button box self.bbox = bbox = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) self.formwidget.update_buttons.connect(self.update_buttons) if self.apply_callback is not None: apply_btn = bbox.addButton(QtWidgets.QDialogButtonBox.Apply) apply_btn.clicked.connect(self.apply) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) layout.addWidget(bbox) self.setLayout(layout) self.setWindowTitle(title) if not isinstance(icon, QtGui.QIcon): icon = QtWidgets.QWidget().style().standardIcon(QtWidgets.QStyle.SP_MessageBoxQuestion) self.setWindowIcon(icon) def register_float_field(self, field): self.float_fields.append(field) def update_buttons(self): valid = True for field in self.float_fields: if not is_edit_valid(field): valid = False for btn_type in (QtWidgets.QDialogButtonBox.Ok, QtWidgets.QDialogButtonBox.Apply): btn = self.bbox.button(btn_type) if btn is not None: btn.setEnabled(valid) def accept(self): self.data = self.formwidget.get() QtWidgets.QDialog.accept(self) def reject(self): self.data = None QtWidgets.QDialog.reject(self) def apply(self): self.apply_callback(self.formwidget.get()) def get(self): """Return form result""" return self.data def fedit(data, title="", comment="", icon=None, parent=None, apply=None): """ Create form dialog and return result (if Cancel button is pressed, return None) data: datalist, datagroup title: string comment: string icon: QIcon instance parent: parent QWidget apply: apply callback (function) datalist: list/tuple of (field_name, field_value) datagroup: list/tuple of (datalist *or* datagroup, title, comment) -> one field for each member of a datalist -> one tab for each member of a top-level datagroup -> one page (of a multipage widget, each page can be selected with a combo box) for each member of a datagroup inside a datagroup Supported types for field_value: - int, float, str, unicode, bool - colors: in Qt-compatible text form, i.e. in hex format or name (red,...) (automatically detected from a string) - list/tuple: * the first element will be the selected index (or value) * the other elements can be couples (key, value) or only values """ # Create a QApplication instance if no instance currently exists # (e.g., if the module is used directly from the interpreter) if QtWidgets.QApplication.startingUp(): _app = QtWidgets.QApplication([]) dialog = FormDialog(data, title, comment, icon, parent, apply) if dialog.exec_(): return dialog.get() if __name__ == "__main__": # def create_datalist_example(): # return [('str', 'this is a string'), # ('list', [0, '1', '3', '4']), # ('list2', ['--', ('none', 'None'), ('--', 'Dashed'), # ('-.', 'DashDot'), ('-', 'Solid'), # ('steps', 'Steps'), (':', 'Dotted')]), # ('float', 1.2), # (None, 'Other:'), # ('int', 12), # ('font', ('Arial', 10, False, True)), # ('color', '#123409'), # ('bool', True), # ('date', datetime.date(2010, 10, 10)), # ('datetime', datetime.datetime(2010, 10, 10)), # ] # # def create_datagroup_example(): # datalist = create_datalist_example() # return ((datalist, "Category 1", "Category 1 comment"), # (datalist, "Category 2", "Category 2 comment"), # (datalist, "Category 3", "Category 3 comment")) # # #--------- datalist example # datalist = create_datalist_example() # # def apply_test(data): # print("data:", data) # print("result:", fedit(datalist, title="Example", # comment="This is just an <b>example</b>.", # apply=apply_test)) # --------- datagroup example # datagroup = create_datagroup_example() # print("result:", fedit(datagroup, "Global title")) #--------- datagroup inside a datagroup example # datalist = create_datalist_example() # datagroup = create_datagroup_example() # print("result:", fedit(((datagroup, "Title 1", "Tab 1 comment"), # (datalist, "Title 2", "Tab 2 comment"), # (datalist, "Title 3", "Tab 3 comment")), # "Global title")) # MY TEST data = [('str', 'this is a string'), ('str', 'this is a string'), ('str', 'this is a string'), ('list', [0, '1', '3', '4']), ('list', [2, '1', '3', '4']), ('list2', ['--', ('none', 'None'), ('--', 'Dashed'), ('-.', 'DashDot'), ('-', 'Solid'), ('steps', 'Steps'), (':', 'Dotted')]), ('float', 1.2), (None, 'Other:'), ('int', 12), ('font', ('Arial', 10, False, True)), ('color', '#123409'), ('bool', True), ('date', datetime.date(2010, 10, 10)), ('datetime', datetime.datetime(2010, 10, 10)), ] def apply_test(a): print(a) fedit(data, title='henlo', comment='haahha', apply=apply_test)
chilleo/ALPHA
raxmlOutputWindows/matplotlibCustomBackend/customFormlayout.py
Python
mit
20,667
"""A parser for axfs file system images""" from stat import * import zlib from . import * from ..io import * from ..util import * AxfsHeader = Struct('AxfsHeader', [ ('magic', Struct.STR % 4), ('signature', Struct.STR % 16), ('digest', Struct.STR % 40), ('blockSize', Struct.INT32), ('files', Struct.INT64), ('size', Struct.INT64), ('blocks', Struct.INT64), ('mmapSize', Struct.INT64), ('regions', Struct.STR % 144), ('...', 13), ], Struct.BIG_ENDIAN) axfsHeaderMagic = b'\x48\xA0\xE4\xCD' axfsHeaderSignature = b'Advanced XIP FS\0' AxfsRegionDesc = Struct('AxfsRegionDesc', [ ('offset', Struct.INT64), ('size', Struct.INT64), ('compressedSize', Struct.INT64), ('maxIndex', Struct.INT64), ('tableByteDepth', Struct.INT8), ('incore', Struct.INT8), ], Struct.BIG_ENDIAN) axfsRegions = [ 'strings', 'xip', 'byteAligned', 'compressed', # tableRegions: 'nodeType', 'nodeIndex', 'cnodeOffset', 'cnodeIndex', 'banodeOffset', 'cblockOffset', 'fileSize', 'nameOffset', 'numEntries', 'modeIndex', 'arrayIndex', 'modes', 'uids', 'gids', ] def isAxfs(file): header = AxfsHeader.unpack(file) return header and header.magic == axfsHeaderMagic and header.signature == axfsHeaderSignature def readAxfs(file): header = AxfsHeader.unpack(file) if header.magic != axfsHeaderMagic or header.signature != axfsHeaderSignature: raise Exception('Wrong magic') regions = {} tables = {} for i, k in enumerate(axfsRegions): region = AxfsRegionDesc.unpack(file, parse64be(header.regions[i*8:(i+1)*8])) regions[k] = FilePart(file, region.offset, region.size) if i >= 4: regionData = regions[k].read() tables[k] = [sum([ord(regionData[j*region.maxIndex+i:j*region.maxIndex+i+1]) << (8*j) for j in range(region.tableByteDepth)]) for i in range(region.maxIndex)] def readInode(id, path=''): size = tables['fileSize'][id] nameOffset = tables['nameOffset'][id] mode = tables['modes'][tables['modeIndex'][id]] uid = tables['uids'][tables['modeIndex'][id]] gid = tables['gids'][tables['modeIndex'][id]] numEntries = tables['numEntries'][id] arrayIndex = tables['arrayIndex'][id] name = b'' regions['strings'].seek(nameOffset) while b'\0' not in name: name += regions['strings'].read(1024) name = name.partition(b'\0')[0].decode('ascii') path += name if id != 0 else '' isDir = S_ISDIR(mode) def generateChunks(arrayIndex=arrayIndex, numEntries=numEntries, size=size): read = 0 for i in range(numEntries): nodeType = tables['nodeType'][arrayIndex + i] nodeIndex = tables['nodeIndex'][arrayIndex + i] if nodeType == 0: regions['xip'].seek(nodeIndex << 12) contents = regions['xip'].read(4096) elif nodeType == 1: cnodeIndex = tables['cnodeIndex'][nodeIndex] regions['compressed'].seek(tables['cblockOffset'][cnodeIndex]) contents = zlib.decompress(regions['compressed'].read(tables['cblockOffset'][cnodeIndex+1] - tables['cblockOffset'][cnodeIndex])) elif nodeType == 2: regions['byteAligned'].seek(tables['banodeOffset'][nodeIndex]) contents = regions['byteAligned'].read(size - read) else: raise Exception('Unknown type') yield contents read += len(contents) yield UnixFile( path = path, size = size if not isDir else 0, mtime = 0, mode = mode, uid = uid, gid = gid, contents = ChunkedFile(generateChunks, size) if S_ISREG(mode) or S_ISLNK(mode) else None, ) if isDir: for i in range(numEntries): for f in readInode(arrayIndex + i, path + '/'): yield f for f in readInode(0): yield f
ma1co/fwtool.py
fwtool/archive/axfs.py
Python
mit
3,572
#from django.contrib import admin
wapcaplet/vittles
nutrition/admin.py
Python
mit
35
from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase from restapi.models.web_radio import WebRadio class TestGetDetails(APITestCase): def setUp(self): super(TestGetDetails, self).setUp() self.webradio = WebRadio.objects.create(name="test", url="http://test.com") self.url = reverse('api:webradios:retrieve_update_destroy', args=[self.webradio.id]) def test_get_details(self): response = self.client.get(self.url, format='json') expected_response = {'id': self.webradio.id, 'is_default': False, 'name': 'test', 'url': 'http://test.com'} self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(expected_response, response.json())
Sispheor/piclodio3
back/tests/test_views/test_web_radio_views/test_get_details.py
Python
mit
785
# python3 import queue class Edge: def __init__(self, u, v, capacity): self.u = u self.v = v self.capacity = capacity self.flow = 0 # This class implements a bit unusual scheme for storing edges of the graph, # in order to retrieve the backward edge for a given edge quickly. class FlowGraph: def __init__(self, n): # List of all - forward and backward - edges self.edges = [] # These adjacency lists store only indices of edges in the edges list self.graph = [[] for _ in range(n)] def add_edge(self, from_, to, capacity): # Note that we first append a forward edge and then a backward edge, # so all forward edges are stored at even indices (starting from 0), # whereas backward edges are stored at odd indices. forward_edge = Edge(from_, to, capacity) backward_edge = Edge(to, from_, 0) self.graph[from_].append(len(self.edges)) self.edges.append(forward_edge) self.graph[to].append(len(self.edges)) self.edges.append(backward_edge) def size(self): return len(self.graph) def get_ids(self, from_): return self.graph[from_] def get_edge(self, id): return self.edges[id] def add_flow(self, id, flow): # To get a backward edge for a true forward edge (i.e id is even), we should get id + 1 # due to the described above scheme. On the other hand, when we have to get a "backward" # edge for a backward edge (i.e. get a forward edge for backward - id is odd), id - 1 # should be taken. # # It turns out that id ^ 1 works for both cases. Think this through! self.edges[id].flow += flow self.edges[id ^ 1].flow -= flow def read_data(): vertex_count, edge_count = map(int, input().split()) graph = FlowGraph(vertex_count) for _ in range(edge_count): u, v, capacity = map(int, input().split()) graph.add_edge(u - 1, v - 1, capacity) return graph def BFS(graph, s): dist = [-1] * graph.size() path_edge_ids = [None] * graph.size() dist[s] = 0 q = queue.Queue() q.put(s) while not q.empty(): u = q.get() edge_ids = graph.graph[u] for edge, edge_id in [(graph.get_edge(e_id), e_id) for e_id in edge_ids]: if dist[edge.v] == -1 and (edge.capacity - edge.flow) > 0: q.put(edge.v) dist[edge.v] = dist[u] + 1 path_edge_ids[edge.v] = edge_id return dist, path_edge_ids def ReconstructPath(s, u, path_edge_ids, graph): result = [] while u != s: e_to_u_id = path_edge_ids[u] result.append(e_to_u_id) u = graph.get_edge(e_to_u_id).u return result def max_flow(graph, from_, to): flow = 0 while True: (dist, path_edge_ids) = BFS(graph, from_) if path_edge_ids[to] is None: return flow path_to_sink_edge_ids = ReconstructPath(from_, to, path_edge_ids, graph) X = min([(graph.get_edge(e_id).capacity - graph.get_edge(e_id).flow) for e_id in path_to_sink_edge_ids]) for e_id in path_to_sink_edge_ids: graph.add_flow(e_id, X) flow += X if __name__ == "__main__": graph = read_data() print(max_flow(graph, 0, graph.size() - 1))
oy-vey/algorithms-and-data-structures
5-AdvancedAlgorithmsAndComplexity/Week1/evacuation/evacuation.py
Python
mit
3,343
''' David Rodriguez Goal: Continuously looping while to perform valve actions at specified times, introduce substance at a specific ratio based on flow data, recording and saving flow data, and actuating a flush at a specified time. Inputs: A schedule of events based on entered times. Outputs: Sequence of events to a screen as they happen. daily flow rate data ''' #logic testing Below is the functional portion import datetime import time import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.PWM as PWM class Flow: GPIO.setup("P8_7", GPIO.OUT) #stepper direction GPIO.setup("P9_16", GPIO.OUT) #step GPIO.setup("P8_11", GPIO.OUT) #(0: enabled, 1: disabled) GPIO.setup("P8_15", GPIO.OUT) #Direction for actuator 1 GPIO.setup("P8_17", GPIO.OUT) #PWM for actuator 1 GPIO.setup("P8_16", GPIO.OUT) #Direction for actuator 2 GPIO.setup("P8_18", GPIO.OUT) #PWM for actuator 2 GPIO.output("P8_7", GPIO.LOW) #set stepper motor direction tag = "" def enableStepper(self): GPIO.output("P8_11", GPIO.LOW) def disableStepper(self): GPIO.output("P8_11", GPIO.HIGH) def triggerStepper(self): time.sleep(0.5) PWM.start("P9_16", 25, 100, 1) time.sleep(2) PWM.set_frequency("P9_16", 250) time.sleep(90) PWM.stop("P9_16") PWM.cleanup() def toiletTrigger(self, flushType): if flushType == "Full": self.toiletFull() else: self.toiletUrine() def toiletUrine(self): print "Toilet Urine Triggered" self.enableStepper() self.triggerStepper() GPIO.output("P8_17", GPIO.HIGH) #pwm on GPIO.output("P8_15", GPIO.LOW) #extend actuator time.sleep(.65) GPIO.output("P8_15", GPIO.HIGH) #retract actuator time.sleep(2) GPIO.output("P8_17", GPIO.LOW) #pwn off self.disableStepper() def toiletFull(self): print "Toilet Full Triggered" self.enableStepper() self.triggerStepper() GPIO.output("P8_18", GPIO.HIGH) #pwm on GPIO.output("P8_16", GPIO.LOW) #extend actuator time.sleep(.65) GPIO.output("P8_16", GPIO.HIGH) #retract actuator time.sleep(1) GPIO.output("P8_18", GPIO.LOW) #pwm on self.disableStepper()
dotsonlab/AWSC-Toilet
flow.py
Python
mit
2,391
from .company import Company from .contact import Contact from .deal import Deal from .note import Note from .requester import Requester class AgileCRM: def __init__(self, domain, email, api_key): requester = Requester(domain, email, api_key) self.contact = Contact(requester=requester) self.company = Company(requester=requester) self.deal = Deal(requester=requester) self.note = Note(requester=requester)
rahmonov/agile-crm-python
agilecrm/client.py
Python
mit
454
import re import datetime import logging log = logging.getLogger(__name__) class Marker(object): __slots__ = ['line_start', 'line_end', 'expires'] def __init__(self, lineno): self.line_start = lineno self.line_end = lineno self.expires = None def __str__(self): if self.line_start == self.line_end: line = str(self.line_start) else: line = '{0}-{1}'.format(self.line_start, self.line_end) return 'Marker(line={0}, expires={1})'.format(line, self.expires) def __repr__(self): return str(self) class Parser(object): re_sunset_begin = re.compile( r'>>SUNSET' r'\s+(?P<date>([1-9][0-9]{3})-(1[1-2]|0?[1-9])-([1-2][0-9]|3[0-1]|0?[1-9]))\s*' r'(?P<end><<)?\s*$') re_sunset_end = re.compile(r'<<SUNSET') def __init__(self): self.markers = [] self._open_marker = None def parse_begin(self, lineno, comment): match = self.re_sunset_begin.search(comment) if match: if self._open_marker: log.warn('Unmatched marker start at line %d', self._open_marker.line_start) self.markers.append(self._open_marker) groupdict = match.groupdict() self._open_marker = Marker(lineno) self._open_marker.expires = datetime.date(*map(int, groupdict['date'].split('-'))) if groupdict['end']: self.markers.append(self._open_marker) self._open_marker = None return True return False def parse_end(self, lineno, comment): match = self.re_sunset_end.search(comment) if match: if self._open_marker: self._open_marker.line_end = lineno self.markers.append(self._open_marker) self._open_marker = None else: log.warn('Dangling marker end at line %d', lineno) def parse(self, lineno, comment): if not self.parse_begin(lineno, comment): self.parse_end(lineno, comment)
jimmyshen/sunset
sunset/parser.py
Python
mit
2,091
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * import qurawl.zoo as zoo #### __all__ = ['Qurawl', 'Commenter'] #### NO_DBG = [] MONSTERS = [6] dbg = debugit.Debugit(__name__, NO_DBG) #MONSTERS) #### OBSTACLES = ('#',) #### Word Categories names = set(['yip', 'otto', 'xenia']) verbs = set(['move', 'attack', 'use', 'push']) obverbs = set(['drop']) objects = set(['health', 'armor', 'strength', 'mine', 'silver_key', 'gold_key']) directs = set(['up', 'left', 'right', 'down']) # Lookup table (word -> Category) LEXICON = rp.make_lexicon((names, verbs, obverbs, objects, directs), 'NVWOD') #### class Qurawl(object): """Main Game Class""" def __init__(self, conf, lexicon=LEXICON): seed = conf['seed'] if seed > 0: rand.seed(seed) self.conf = conf self.lexicon = lexicon self.commenter = Commenter() def init_all(self): level_map = LevelMap(zoo.make_level(20, 30)) actors = zoo.make_actors() self.act_level = Level(level_map, self.commenter, self.conf, actors=actors, monsters=zoo.make_monsters(), things=zoo.make_things(), obstacles=OBSTACLES) self.name_actors = dict(zip((actor.name for actor in actors), actors)) def start(self): self.init_all() @property def level(self): return self.act_level def input_action(self, tokens): scan_info = fuzzy_scan(tokens, self.lexicon) dbg(4, scan_info, 'scan info', self.input_action) if 'err' in scan_info: self.commenter(1, "Don't know {0}.".format(scan_info['err'])) return parse_info = rp.parse_nvod(scan_info['match'], self.lexicon) dbg(4, parse_info, 'parse info', self.input_action) if 'err' in parse_info: self.commenter(1, "Don't know what to do: {0}".\ format(show_parse_errors(parse_info['err']))) return cmd = make_command(parse_info) verb, args = cmd[0], cmd[1:] try: action_method = getattr(self.level, verb) except AttributeError: self.commenter(1, "Don't know how to '{0}'!".format(verb)) return for name in parse_info['name']: action_method(self.name_actors[name], *args) def action(self, meta_info): self.level.action() if 'quit' == meta_info: self.fin() def get_actor_stats(self): dbg(6, [m.stat for m in self.level.monsters]) return [actor.stat for actor in self.level.actors if not actor.is_dead] def get_comments(self): return self.commenter.show(100) def loop_reset(self): self.commenter.reset() def fin(self): self.commenter(1, "Bye") #### class Commenter(object): """Collect and return state and action comments""" def __init__(self): self.reset() def reset(self): self.buf = [] def __call__(self, level, msg): self.buf.append((level, msg)) def __iter__(self): return iter(self.buf) def pick(self, result, actor, thing): if isinstance(thing, Corpse): com = "{0} plunders the corpse of {1}." name = thing.name.rsplit("_", 1)[0] self.buf.append((2, com.format(actor.name, name))) return if result < 2: com = "{0} picked up {1}({2})." else: com = "{0} is hurt by {1}({2})." self.buf.append((3, com.format(actor.name, thing.name, thing.value))) def dead(self, actor): com = "{0} is dead, sigh!".format(actor.name) self.buf.append((2, com)) def fight(self, attacker, defender): com = "{0} attacks {1}!".format(attacker.name, defender.name) self.buf.append((2, com)) def show(self, level): return (msg for i, msg in self if i <= level) #### def show_parse_errors(pairs): """Gather invalid command infos.""" return " ".join(word if categ != "?" else categ for categ, word in pairs) #### def make_command(parse_info, phrases=('verb', 'obverb', 'object', 'direct')): """Reconstruct a valid command.""" # use verb 'move' as default # check if (ob)verb is already existent use_move = bool(set(('verb', 'obverb')) & set(parse_info)) info = dict(parse_info, **({'verb': 'move'}, {})[use_move]) return [info[key] for key in phrases if key in info] #### def fuzzy_scan(words, lexicon): """Check if words have a resonable similarity to lexicon words.""" matches = [diff.get_close_matches(word, lexicon, n=1) for word in words] if not all(matches): return {'err': " ".join(w for w, m in zip(words, matches) if not m)} else: return {'match': list(it.chain(*matches))} ####
yipyip/Qurawl
qurawl/qurawl.py
Python
mit
5,127
import _plotly_utils.basevalidators class NticksValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="nticks", parent_name="funnel.marker.colorbar", **kwargs ): super(NticksValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), **kwargs )
plotly/plotly.py
packages/python/plotly/plotly/validators/funnel/marker/colorbar/_nticks.py
Python
mit
466
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- import msvcrt titulo="Empresa Rubben Rc Corporation\n".capitalize() print titulo.center(50," ") print("Telefono: 6948209") class modelo_presupuesto: titulo="presupuesto" inicio_nombre="Empresa Rubben Rc Corporation" inicio_web= "www.rubbenrc.com" inicio_email= "rubbenrc@hotmail.com" cuota_iva= 7 div= "="*80 def set_cliente(self): self.empresa= raw_input("Empresa: ") self.cliente= raw_input("Nombre del cliente: ") def set_datos_basicos(self): self.fecha= raw_input(" Fecha: ") self.servicio= raw_input("Descripcion del servicio: ") importe= raw_input("importe bruto: $") self.importe= float(importe) self.vencimiento= raw_input("fecha de expiracion: ") def iva(self): self.monto_iva= self.importe*self.cuota_iva/100 def monto_neto(self): self.neto= self.importe+self.monto_iva def armar_presupuesto(self): """ Esta funcion se encarga de armar todo el presupuesto """ txt = '\n'+self.div+'\n' txt += '\t'+self.inicio_nombre+'\n' txt += '\tWeb Site: '+self.inicio_web+' | ' txt += 'E-mail: '+self.inicio_email+'\n' txt += self.div+'\n' txt += '\t'+self.titulo+'\n' txt += self.div+'\n\n' txt += '\tFecha: '+self.fecha+'\n' txt += '\tEmpresa: '+self.empresa+'\n' txt += '\tCliente: '+self.cliente+'\n' txt += self.div+'\n\n' txt += '\tDetalle del servicio:' txt += '\t'+self.servicio+'\n\n' txt += '\tImporte: $%0.2f | IVA: $%0.2f\n' % ( self.importe, self.monto_iva) txt += '-'*80 txt += '\n\tMONTO TOTAL: $%0.2f\n' % (self.neto) txt += self.div+'\n' print txt # Metodo constructor def __init__(self): print self.div print "\tPRESUPUESTO A OFRECER" print self.div self.set_cliente() self.set_datos_basicos() self.iva() self.monto_neto() self.armar_presupuesto() # Instanciar clase presupuesto = modelo_presupuesto() msvcrt.getch()
rubbenrc/uip-prog3
parcial/presupuesto_parcial.py
Python
mit
2,452
# -*- coding: utf-8 -*- # # fmap documentation build configuration file, created by # sphinx-quickstart on Mon Apr 11 21:30:39 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex DIR = os.path.dirname(os.path.abspath(__file__)) def read(fpath): with open(fpath, 'rt') as f: return f.read().strip() # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'fmap' copyright = u'2016, Matt Bodenhamer' author = u'Matt Bodenhamer' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = read(os.path.join(DIR, '../version.txt')) # The short X.Y version. version = release # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'fmapdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'fmap.tex', u'fmap Documentation', u'Matt Bodenhamer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'fmap', u'fmap Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'fmap', u'fmap Documentation', author, 'fmap', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
mbodenhamer/fmap
docs/conf.py
Python
mit
9,309
""" niascape.usecase.postcount 投稿件数ユースケース """ import niascape from niascape.repository import postcount from niascape.utility.database import get_db def day(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.day(db, **option) def month(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.month(db, **option) def hour(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.hour(db, **option) def week(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.week(db, **option) def tag(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.tag(db, **option)
ayziao/niascape
niascape/usecase/postcount.py
Python
mit
1,264
# Refer to the following link for help: # http://docs.gunicorn.org/en/latest/settings.html command = '/home/lucas/www/reddit.lucasou.com/reddit-env/bin/gunicorn' pythonpath = '/home/lucas/www/reddit.lucasou.com/reddit-env/flask_reddit' bind = '127.0.0.1:8040' workers = 1 user = 'lucas' accesslog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-access.log' errorlog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-error.log'
codelucas/flask_reddit
server/gunicorn_config.py
Python
mit
425
import sys, getopt import errno import os.path import epub import lxml from bs4 import BeautifulSoup class EPubToTxtParser: # Epub parsing specific code def get_linear_items_data( self, in_file_name ): book_items = [] book = epub.open_epub( in_file_name ) for item_id, linear in book.opf.spine.itemrefs: item = book.get_item( item_id ) if linear: data = book.read_item( item ) book_items.append( data ) return book_items def get_narrative( self, linear_items_data ): avg_len = 0 count = 0 for data in linear_items_data: count += 1 avg_len = ( ( avg_len * ( count - 1 ) ) + len( data ) ) / count book_narrative = [ data for data in linear_items_data if len(data) >= avg_len ] return book_narrative def extract_paragraph_text( self, book_narrative ): paragraph_text = '' for data in book_narrative: soup = BeautifulSoup( data, "lxml" ) paragraphs = soup.find_all( 'p' ) # Thanks to Eric Storms for finding the solution # to some 0kB parse results… if paragraphs == []: paragraphs = soup.find_all( 'div' ) for paragraph in paragraphs: paragraph_text += ( paragraph.get_text() + '\n' ) return paragraph_text def narrative_from_epub_to_txt( self, in_file_name ): if os.path.isfile( in_file_name ): book_items = self.get_linear_items_data( in_file_name ) book_narrative = self.get_narrative( book_items ) paragraph_text = self.extract_paragraph_text( book_narrative ) return( paragraph_text ) else: raise FileNotFoundError( errno.ENOENT, os.strerror( errno.ENOENT ), in_file_name ) # Command line usage stuff def print_usage_and_exit(): print( "Usage: %s -i epub_file_in -o txt_file_out" % sys.argv[ 0 ] ) sys.exit( 2 ) def parse_opts( opts ): in_file_name, out_file_name = None, None for o, a in opts: if o == '-i': in_file_name = a elif o == '-o': out_file_name = a return ( in_file_name, out_file_name ) # Main if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "i:o:") assert( len(opts) != 0 ) in_file_name, out_file_name = parse_opts( opts ) except getopt.GetoptError as e: print( str( e ) ) print_usage_and_exit() except AssertionError: print_usage_and_exit() try: parser = EPubToTxtParser() narrative_text = parser.narrative_from_epub_to_txt( in_file_name ) if( out_file_name != None ): with open( out_file_name, "w" ) as out_file: out_file.write( narrative_text ) out_file.close() else: print( narrative_text ) except FileNotFoundError: print( "File not found: {file_name}".format( file_name = in_file_name ) )
jorisvanzundert/sfsf
sfsf/epub_to_txt_parser.py
Python
mit
3,042
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # from sympy import * from src import jeffery_model as jm DoubleletStrength = np.array((1, 0, 0)) alpha = 1 B = np.array((0, 1, 0)) lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1) x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100)) problem = jm.SingleDoubleletJefferyProblem(B=B, DoubleletStrength=DoubleletStrength) length = 200 def fun(zi): location = np.vstack((x.flatten(), y.flatten(), np.ones_like(y.flatten()) * zi)) Jij = problem.J_matrix(location) JijT = Jij.transpose(1, 0, 2) Sij = 1 / 2 * (Jij + JijT) Oij = 1 / 2 * (Jij - JijT) Bij = Sij + lbd * Oij TrB2 = (Bij[0, 0, :] ** 2 + Bij[1, 1, :] ** 2 + Bij[2, 2, :] ** 2).reshape(x.shape) TrB3 = (Bij[0, 0, :] ** 3 + Bij[1, 1, :] ** 3 + Bij[2, 2, :] ** 3).reshape(x.shape) DtLine = TrB2 ** 3 - 6 * TrB3 ** 2 return DtLine fig, ax = plt.subplots() p = [ax.contourf(x, y, np.log10(fun(1 / length)))] def update(i): zi = (1 + i) / length * 2 for tp in p[0].collections: tp.remove() p[0] = ax.contourf(x, y, np.log10(fun(zi))) return p[0].collections ani = animation.FuncAnimation(fig, update, frames=length, interval=5, blit=True, repeat=True) # plt.show() Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=600) ani.save('t2.mp4', writer=writer) print('111')
pcmagic/stokes_flow
try_code/contourAnimation.py
Python
mit
1,468
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. For example: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true Note: You may assume that all words are consist of lowercase letters a-z. You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first. """ class WordDictionary(object): class TrieNode(object): def __init__(self): self.leaves = {} self.nil = False def __init__(self): """ initialize your data structure here. """ self.root = self.TrieNode() def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ loc = self.root for c in word: if c not in loc.leaves: loc.leaves[c] = self.TrieNode() loc = loc.leaves[c] loc.nil = True def searchTail(self, tail, loc): if tail == '': return loc.nil for i, c in enumerate(tail): if c == '.': if loc.leaves == {}: return False else: for leaf in loc.leaves: if self.searchTail(tail[i + 1:], loc.leaves[leaf]): return True return False elif c in loc.leaves: loc = loc.leaves[c] else: return False return loc.nil def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ return self.searchTail(word, self.root) # Your WordDictionary object will be instantiated and called as such: # wordDictionary = WordDictionary() # wordDictionary.addWord("word") # wordDictionary.search("pattern") a = WordDictionary() a.addWord('bad') a.addWord('dad') a.addWord('mad') print(a.search("pad")) print(a.search("bad")) print(a.search(".ad")) print(a.search("b.."))
ufjfeng/leetcode-jf-soln
python/211_add_and_search_word-data_structure_design.py
Python
mit
2,445
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Qcloud COS SDK for Python 3 documentation build configuration file, created by # cookiecutter pipproject # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Qcloud COS SDK for Python 3' copyright = '2016, Dan Su' author = 'Dan Su' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.0' # The full version, including alpha/beta/rc tags. release = '0.1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. #html_title = 'Qcloud COS SDK for Python 3 v0.1.0' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'Qcloud COS SDK for Python 3doc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Qcloud COS SDK for Python 3.tex', 'Qcloud COS SDK for Python 3 Documentation', 'Dan Su', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'Qcloud COS SDK for Python 3', 'Qcloud COS SDK for Python 3 Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Qcloud COS SDK for Python 3', 'Qcloud COS SDK for Python 3 Documentation', author, 'Qcloud COS SDK for Python 3', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
su27/qcloud_cos_py3
docs/source/conf.py
Python
mit
9,669
import feedparser import logging from rss import sources from util import date, dict_tool, tags log = logging.getLogger('app') def parse_feed_by_name(name): feed_params = sources.get_source(name) if not feed_params: raise ValueError('There is no feed with name %s' % name) source_name = feed_params['name'] feed = feedparser.parse(feed_params['url']) data = [] for entry in feed['entries']: data.append( create_doc( source_name, feed, entry, feed_params.get('tags', ()), feed_params.get('author_name'), feed_params.get('author_link'), feed_params.get('dressing_params'), ) ) log.info('%s: got %d documents', source_name, len(data)) return data def create_doc(source_name, feed, entry, additional_tags, default_author_name, default_author_link, dressing_params): link = dict_tool.get_alternative(entry, 'feedburner_origlink', 'link', assert_val=True) published = date.utc_format( dict_tool.get_alternative(entry, 'published', 'updated', assert_val=True) ) description = dict_tool.get_alternative(entry, 'summary', 'description', 'title', assert_val=True) picture = dict_tool.get_deep(entry, 'gd_image', 'src') text = dict_tool.get_deep(entry, 'content', 0, 'value') author_name = handle_default_param( entry, dict_tool.get_deep(entry, 'authors', 0, 'name'), default_author_name ) author_link = handle_default_param( entry, dict_tool.get_deep(entry, 'authors', 0, 'href'), default_author_link ) entry_tags = [] for tag in entry.get('tags', []): tag_text = dict_tool.get_alternative(tag, 'term', 'label') if tag_text: entry_tags.append(tag_text.lower()) additional_tags += tuple(entry_tags) comments_count = entry.get('slash_comments') if comments_count is not None: comments_count = int(comments_count) return { 'link': link, 'title': entry['title'], 'published': published, 'picture': picture, 'author_name': author_name, 'author_link': author_link, 'description': description, 'text': text, 'source_name': source_name, 'source_type': 'rss', 'source_title': feed['feed']['title'], 'source_link': feed['feed']['link'], 'comments_count': comments_count, 'tags': tags.create_tags_list(*additional_tags), '__dressing_params': dressing_params, } def handle_default_param(entry, val, default_val): if callable(default_val): return default_val(entry, val) return val or default_val
andre487/news487
collector/rss/reader.py
Python
mit
2,757
from setuptools import setup setup(name='pyyaxml', version='0.6.7', description='Python API to Yandex.XML', url='https://github.com/dbf256/py-ya-xml', author='Alexey Moskvin', author_email='dbf256@gmail.com', license='MIT', packages=['pyyaxml'], install_requires=[ 'six', ], zip_safe=False)
dbf256/py-ya-xml
setup.py
Python
mit
362
#! /usr/bin/python3 """ Broadcast a message, with or without a price. Multiple messages per block are allowed. Bets are be made on the 'timestamp' field, and not the block index. An address is a feed of broadcasts. Feeds may be locked with a broadcast whose text field is identical to ‘lock’ (case insensitive). Bets on a feed reference the address that is the source of the feed in an output which includes the (latest) required fee. Broadcasts without a price may not be used for betting. Broadcasts about events with a small number of possible outcomes (e.g. sports games), should be written, for example, such that a price of 1 XBJ means one outcome, 2 XBJ means another, etc., which schema should be described in the 'text' field. fee_fraction: .05 XBJ means 5%. It may be greater than 1, however; but because it is stored as a four‐byte integer, it may not be greater than about 42. """ import struct import decimal D = decimal.Decimal from fractions import Fraction import logging from . import (util, exceptions, config, worldcoin) from . import (bet) FORMAT = '>IdI' LENGTH = 4 + 8 + 4 ID = 30 # NOTE: Pascal strings are used for storing texts for backwards‐compatibility. def validate (db, source, timestamp, value, fee_fraction_int, text, block_index): problems = [] if fee_fraction_int > 4294967295: problems.append('fee fraction greater than 42.94967295') if timestamp < 0: problems.append('negative timestamp') if not source: problems.append('null source address') # Check previous broadcast in this feed. cursor = db.cursor() broadcasts = list(cursor.execute('''SELECT * FROM broadcasts WHERE (status = ? AND source = ?) ORDER BY tx_index ASC''', ('valid', source))) cursor.close() if broadcasts: last_broadcast = broadcasts[-1] if last_broadcast['locked']: problems.append('locked feed') elif timestamp <= last_broadcast['timestamp']: problems.append('feed timestamps not monotonically increasing') if not (block_index >= 317500 or config.TESTNET): # Protocol change. if len(text) > 52: problems.append('text too long') return problems def compose (db, source, timestamp, value, fee_fraction, text): # Store the fee fraction as an integer. fee_fraction_int = int(fee_fraction * 1e8) problems = validate(db, source, timestamp, value, fee_fraction_int, text, util.last_block(db)['block_index']) if problems: raise exceptions.BroadcastError(problems) data = struct.pack(config.TXTYPE_FORMAT, ID) if len(text) <= 52: curr_format = FORMAT + '{}p'.format(len(text) + 1) else: curr_format = FORMAT + '{}s'.format(len(text)) data += struct.pack(curr_format, timestamp, value, fee_fraction_int, text.encode('utf-8')) return (source, [], data) def parse (db, tx, message): cursor = db.cursor() # Unpack message. try: if len(message) - LENGTH <= 52: curr_format = FORMAT + '{}p'.format(len(message) - LENGTH) else: curr_format = FORMAT + '{}s'.format(len(message) - LENGTH) timestamp, value, fee_fraction_int, text = struct.unpack(curr_format, message) try: text = text.decode('utf-8') except UnicodeDecodeError: text = '' status = 'valid' except (struct.error) as e: timestamp, value, fee_fraction_int, text = 0, None, 0, None status = 'invalid: could not unpack' if status == 'valid': # For SQLite3 timestamp = min(timestamp, config.MAX_INT) value = min(value, config.MAX_INT) problems = validate(db, tx['source'], timestamp, value, fee_fraction_int, text, tx['block_index']) if problems: status = 'invalid: ' + '; '.join(problems) # Lock? lock = False if text and text.lower() == 'lock': lock = True timestamp, value, fee_fraction_int, text = 0, None, None, None else: lock = False # Add parsed transaction to message-type–specific table. bindings = { 'tx_index': tx['tx_index'], 'tx_hash': tx['tx_hash'], 'block_index': tx['block_index'], 'source': tx['source'], 'timestamp': timestamp, 'value': value, 'fee_fraction_int': fee_fraction_int, 'text': text, 'locked': lock, 'status': status, } sql='insert into broadcasts values(:tx_index, :tx_hash, :block_index, :source, :timestamp, :value, :fee_fraction_int, :text, :locked, :status)' cursor.execute(sql, bindings) # Negative values (default to ignore). if value == None or value < 0: # Cancel Open Bets? if value == -2: cursor.execute('''SELECT * FROM bets \ WHERE (status = ? AND feed_address = ?)''', ('open', tx['source'])) for i in list(cursor): bet.cancel_bet(db, i, 'dropped', tx['block_index']) # Cancel Pending Bet Matches? if value == -3: cursor.execute('''SELECT * FROM bet_matches \ WHERE (status = ? AND feed_address = ?)''', ('pending', tx['source'])) for bet_match in list(cursor): bet.cancel_bet_match(db, bet_match, 'dropped', tx['block_index']) cursor.close() return # Handle bet matches that use this feed. cursor.execute('''SELECT * FROM bet_matches \ WHERE (status=? AND feed_address=?) ORDER BY tx1_index ASC, tx0_index ASC''', ('pending', tx['source'])) for bet_match in cursor.fetchall(): broadcast_bet_match_cursor = db.cursor() bet_match_id = bet_match['tx0_hash'] + bet_match['tx1_hash'] bet_match_status = None # Calculate total funds held in escrow and total fee to be paid if # the bet match is settled. Escrow less fee is amount to be paid back # to betters. total_escrow = bet_match['forward_quantity'] + bet_match['backward_quantity'] fee_fraction = fee_fraction_int / config.UNIT fee = int(fee_fraction * total_escrow) # Truncate. escrow_less_fee = total_escrow - fee # Get known bet match type IDs. cfd_type_id = util.BET_TYPE_ID['BullCFD'] + util.BET_TYPE_ID['BearCFD'] equal_type_id = util.BET_TYPE_ID['Equal'] + util.BET_TYPE_ID['NotEqual'] # Get the bet match type ID of this bet match. bet_match_type_id = bet_match['tx0_bet_type'] + bet_match['tx1_bet_type'] # Contract for difference, with determinate settlement date. if bet_match_type_id == cfd_type_id: # Recognise tx0, tx1 as the bull, bear (in the right direction). if bet_match['tx0_bet_type'] < bet_match['tx1_bet_type']: bull_address = bet_match['tx0_address'] bear_address = bet_match['tx1_address'] bull_escrow = bet_match['forward_quantity'] bear_escrow = bet_match['backward_quantity'] else: bull_address = bet_match['tx1_address'] bear_address = bet_match['tx0_address'] bull_escrow = bet_match['backward_quantity'] bear_escrow = bet_match['forward_quantity'] leverage = Fraction(bet_match['leverage'], 5040) initial_value = bet_match['initial_value'] bear_credit = bear_escrow - (value - initial_value) * leverage * config.UNIT bull_credit = escrow_less_fee - bear_credit bear_credit = round(bear_credit) bull_credit = round(bull_credit) # Liquidate, as necessary. if bull_credit >= escrow_less_fee or bull_credit <= 0: if bull_credit >= escrow_less_fee: bull_credit = escrow_less_fee bear_credit = 0 bet_match_status = 'settled: liquidated for bull' util.credit(db, tx['block_index'], bull_address, config.XBJ, bull_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) elif bull_credit <= 0: bull_credit = 0 bear_credit = escrow_less_fee bet_match_status = 'settled: liquidated for bear' util.credit(db, tx['block_index'], bear_address, config.XBJ, bear_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) # Pay fee to feed. util.credit(db, tx['block_index'], bet_match['feed_address'], config.XBJ, fee, action='feed fee', event=tx['tx_hash']) # For logging purposes. bindings = { 'bet_match_id': bet_match_id, 'bet_match_type_id': bet_match_type_id, 'block_index': tx['block_index'], 'settled': False, 'bull_credit': bull_credit, 'bear_credit': bear_credit, 'winner': None, 'escrow_less_fee': None, 'fee': fee } sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)' cursor.execute(sql, bindings) # Settle (if not liquidated). elif timestamp >= bet_match['deadline']: bet_match_status = 'settled' util.credit(db, tx['block_index'], bull_address, config.XBJ, bull_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) util.credit(db, tx['block_index'], bear_address, config.XBJ, bear_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) # Pay fee to feed. util.credit(db, tx['block_index'], bet_match['feed_address'], config.XBJ, fee, action='feed fee', event=tx['tx_hash']) # For logging purposes. bindings = { 'bet_match_id': bet_match_id, 'bet_match_type_id': bet_match_type_id, 'block_index': tx['block_index'], 'settled': True, 'bull_credit': bull_credit, 'bear_credit': bear_credit, 'winner': None, 'escrow_less_fee': None, 'fee': fee } sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)' cursor.execute(sql, bindings) # Equal[/NotEqual] bet. elif bet_match_type_id == equal_type_id and timestamp >= bet_match['deadline']: # Recognise tx0, tx1 as the bull, bear (in the right direction). if bet_match['tx0_bet_type'] < bet_match['tx1_bet_type']: equal_address = bet_match['tx0_address'] notequal_address = bet_match['tx1_address'] else: equal_address = bet_match['tx1_address'] notequal_address = bet_match['tx0_address'] # Decide who won, and credit appropriately. if value == bet_match['target_value']: winner = 'Equal' bet_match_status = 'settled: for equal' util.credit(db, tx['block_index'], equal_address, config.XBJ, escrow_less_fee, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) else: winner = 'NotEqual' bet_match_status = 'settled: for notequal' util.credit(db, tx['block_index'], notequal_address, config.XBJ, escrow_less_fee, action='bet {}'.format(bet_match_status), event=tx['tx_hash']) # Pay fee to feed. util.credit(db, tx['block_index'], bet_match['feed_address'], config.XBJ, fee, action='feed fee', event=tx['tx_hash']) # For logging purposes. bindings = { 'bet_match_id': bet_match_id, 'bet_match_type_id': bet_match_type_id, 'block_index': tx['block_index'], 'settled': None, 'bull_credit': None, 'bear_credit': None, 'winner': winner, 'escrow_less_fee': escrow_less_fee, 'fee': fee } sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)' cursor.execute(sql, bindings) # Update the bet match’s status. if bet_match_status: bindings = { 'status': bet_match_status, 'bet_match_id': bet_match['tx0_hash'] + bet_match['tx1_hash'] } sql='update bet_matches set status = :status where id = :bet_match_id' cursor.execute(sql, bindings) util.message(db, tx['block_index'], 'update', 'bet_matches', bindings) broadcast_bet_match_cursor.close() cursor.close() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Bluejudy/bluejudyd
lib/broadcast.py
Python
mit
13,387
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase, RequestFactory from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.models import AnonymousUser import json import status from tiny_rest.views import APIView from tiny_rest.authorization import ( IsAuthenticatedMixin, IsAuthenticatedOrReadOnlyMixin ) User = get_user_model() class IsAuthenticatedAPIView(IsAuthenticatedMixin, APIView): def list(self, request, *args, **kwargs): return self.response( data={'is_authenticated': request.user.is_authenticated()} ) class IsAuthenticatedOrReadOnlyAPIView(IsAuthenticatedOrReadOnlyMixin, APIView): def list(self, request, *args, **kwargs): return self.response( data={'is_authenticated': request.user.is_authenticated()} ) def create(self, request, *args, **kwargs): return self.response( data={'is_authenticated': request.user.is_authenticated()} ) class BaseTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( 'user', 'user@email.com', '123456' ) class TestIsAuthenticatedAPIView(BaseTestCase): def test_authenticate(self): request = self.factory.get('/') request.user = authenticate(username='user', password='123456') response = IsAuthenticatedAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertTrue(data['is_authenticated']) request.user = AnonymousUser() response = IsAuthenticatedAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertEqual(data['error'], 'Not Authorized') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) class TestIsAuthenticatedOrReadOnlyAPIView(BaseTestCase): def test_authenticate(self): request = self.factory.get('/') request.user = AnonymousUser() response = IsAuthenticatedOrReadOnlyAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertFalse(data['is_authenticated']) self.assertEqual(response.status_code, status.HTTP_200_OK) request = self.factory.post('/') request.user = AnonymousUser() response = IsAuthenticatedOrReadOnlyAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertEqual(data['error'], 'Not Authorized') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) request = self.factory.get('/') request.user = authenticate(username='user', password='123456') response = IsAuthenticatedOrReadOnlyAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertTrue(data['is_authenticated']) self.assertEqual(response.status_code, status.HTTP_200_OK) request = self.factory.post('/') request.user = authenticate(username='user', password='123456') response = IsAuthenticatedOrReadOnlyAPIView.as_view()(request) data = json.loads(response.content.decode()) self.assertTrue(data['is_authenticated']) self.assertEqual(response.status_code, status.HTTP_200_OK)
allisson/django-tiny-rest
tiny_rest/tests/test_authorization.py
Python
mit
3,377
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class AvailabilitySetsOperations(object): """AvailabilitySetsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: Client Api Version. Constant value: "2017-03-30". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-03-30" self.config = config def create_or_update( self, resource_group_name, availability_set_name, parameters, custom_headers=None, raw=False, **operation_config): """Create or update an availability set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param availability_set_name: The name of the availability set. :type availability_set_name: str :param parameters: Parameters supplied to the Create Availability Set operation. :type parameters: ~azure.mgmt.compute.v2017_03_30.models.AvailabilitySet :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: AvailabilitySet or ClientRawResponse if raw=true :rtype: ~azure.mgmt.compute.v2017_03_30.models.AvailabilitySet or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'availabilitySetName': self._serialize.url("availability_set_name", availability_set_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'AvailabilitySet') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('AvailabilitySet', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def delete( self, resource_group_name, availability_set_name, custom_headers=None, raw=False, **operation_config): """Delete an availability set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param availability_set_name: The name of the availability set. :type availability_set_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: OperationStatusResponse or ClientRawResponse if raw=true :rtype: ~azure.mgmt.compute.v2017_03_30.models.OperationStatusResponse or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'availabilitySetName': self._serialize.url("availability_set_name", availability_set_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('OperationStatusResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def get( self, resource_group_name, availability_set_name, custom_headers=None, raw=False, **operation_config): """Retrieves information about an availability set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param availability_set_name: The name of the availability set. :type availability_set_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: AvailabilitySet or ClientRawResponse if raw=true :rtype: ~azure.mgmt.compute.v2017_03_30.models.AvailabilitySet or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'availabilitySetName': self._serialize.url("availability_set_name", availability_set_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('AvailabilitySet', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def list( self, resource_group_name, custom_headers=None, raw=False, **operation_config): """Lists all availability sets in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of AvailabilitySet :rtype: ~azure.mgmt.compute.v2017_03_30.models.AvailabilitySetPaged[~azure.mgmt.compute.v2017_03_30.models.AvailabilitySet] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.AvailabilitySetPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.AvailabilitySetPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def list_available_sizes( self, resource_group_name, availability_set_name, custom_headers=None, raw=False, **operation_config): """Lists all available virtual machine sizes that can be used to create a new virtual machine in an existing availability set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param availability_set_name: The name of the availability set. :type availability_set_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of VirtualMachineSize :rtype: ~azure.mgmt.compute.v2017_03_30.models.VirtualMachineSizePaged[~azure.mgmt.compute.v2017_03_30.models.VirtualMachineSize] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'availabilitySetName': self._serialize.url("availability_set_name", availability_set_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.VirtualMachineSizePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.VirtualMachineSizePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
AutorestCI/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/operations/availability_sets_operations.py
Python
mit
17,248
# NOTE: This example uses the next generation Twilio helper library - for more # information on how to download and install this version, visit # https://www.twilio.com/docs/libraries/python import os from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure account = os.environ['TWILIO_ACCOUNT_SID'] token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account, token) credential = client.notify \ .credentials("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .update(friendly_name="MyCredential", sandbox=True) print(credential.friendly_name)
TwilioDevEd/api-snippets
notifications/rest/credentials/update-credential/update-credential.7.x.py
Python
mit
707
print 'abc' + '123' print 'Hi' * 5
rahulbohra/Python-Basic
7_first-string-operators.py
Python
mit
35
import numpy as np import tensorflow as tf import os def get_inputs(split, config): split_dir = config['split_dir'] data_dir = config['data_dir'] dataset = config['dataset'] split_file = os.path.join(split_dir, dataset, split + '.lst') filename_queue = get_filename_queue(split_file, os.path.join(data_dir, dataset)) if dataset == 'mnist': image = get_inputs_mnist(filename_queue, config) config['output_size'] = 28 config['c_dim'] = 1 elif dataset == "cifar-10": image = get_inputs_cifar10(filename_queue, config) config['output_size'] = 32 config['c_dim'] = 3 else: image = get_inputs_image(filename_queue, config) image_batch = create_batch([image], config['batch_size']) return image_batch def get_inputs_image(filename_queue, config): output_size = config['output_size'] image_size = config['image_size'] c_dim = config['c_dim'] # Read a record, getting filenames from the filename_queue. reader = tf.WholeFileReader() key, value = reader.read(filename_queue) image = tf.image.decode_image(value, channels=c_dim) image = tf.cast(image, tf.float32)/255. image_shape = tf.shape(image) image_height, image_width = image_shape[0], image_shape[1] offset_height = tf.cast((image_height - image_size)/2, tf.int32) offset_width = tf.cast((image_width - image_size)/2, tf.int32) image = tf.image.crop_to_bounding_box(image, offset_height, offset_width, image_size, image_size) image = tf.image.resize_images(image, [output_size, output_size]) image.set_shape([output_size, output_size, c_dim]) return image def get_inputs_mnist(filename_queue, config): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since all keys are required. features={ 'height': tf.FixedLenFeature([], tf.int64), 'width': tf.FixedLenFeature([], tf.int64), 'depth': tf.FixedLenFeature([], tf.int64), 'label': tf.FixedLenFeature([], tf.int64), 'image_raw': tf.FixedLenFeature([], tf.string), }) image = tf.decode_raw(features['image_raw'], tf.uint8) image.set_shape([784]) image = tf.reshape(image, [28, 28, 1]) image = tf.cast(image, tf.float32) / 255. # Convert label from a scalar uint8 tensor to an int32 scalar. label = tf.cast(features['label'], tf.int32) binary_image = (tf.random_uniform(image.get_shape()) <= image) binary_image = tf.cast(binary_image, tf.float32) return binary_image def get_inputs_cifar10(filename_queue, config): output_size = config['output_size'] image_size = config['image_size'] c_dim = config['c_dim'] # Dimensions of the images in the CIFAR-10 dataset. # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the # input format. label_bytes = 1 # 2 for CIFAR-100 image_bytes = 32 * 32 * 3 # Every record consists of a label followed by the image, with a # fixed number of bytes for each. record_bytes = label_bytes + image_bytes # Read a record, getting filenames from the filename_queue. reader = tf.FixedLengthRecordReader(record_bytes=record_bytes) key, value = reader.read(filename_queue) record = tf.decode_raw(value, tf.uint8) # The first bytes represent the label, which we convert from uint8->int32. label = tf.cast(record[0], tf.int32) # The remaining bytes after the label represent the image, which we reshape # from [depth * height * width] to [depth, height, width]. #tf.strided_slice(record, [label_bytes], [label_bytes + image_bytes]) image = tf.reshape(record[label_bytes:label_bytes+image_bytes], [3, 32, 32]) image = tf.cast(image, tf.float32)/255. # Convert from [depth, height, width] to [height, width, depth]. image = tf.transpose(image, [1, 2, 0]) return image def get_filename_queue(split_file, data_dir): with open(split_file, 'r') as f: filenames = f.readlines() filenames = [os.path.join(data_dir, f.strip()) for f in filenames] for f in filenames: if not os.path.exists(f): raise ValueError('Failed to find file: ' + f) filename_queue = tf.train.string_input_producer(filenames) return filename_queue def create_batch(inputs, batch_size=64, min_queue_examples=1000, num_preprocess_threads=12, enqueue_many=False): # Generate a batch of images and labels by building up a queue of examples. batch = tf.train.shuffle_batch( inputs, batch_size=batch_size, num_threads=num_preprocess_threads, capacity=min_queue_examples + 3 * batch_size, min_after_dequeue=min_queue_examples, enqueue_many=enqueue_many, ) return batch
LMescheder/AdversarialVariationalBayes
avb/inputs.py
Python
mit
4,913
# GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO # Michael Vendivel - vendivel@gmail.com import subprocess import datetime from pymongo import MongoClient # where's the log file filename = '/path/to/php/logs.log' # set up mongo client client = MongoClient('mongo.server.address', 27017) # which DB db = client.logs # which Collection php_logs = db.php_logs # open a subprocess to tail (and follow) the log file f = subprocess.Popen(['tail','-f',filename],\ stdout=subprocess.PIPE,stderr=subprocess.PIPE) # continue to read the file and record lines into mongo while True: # read line by line line = f.stdout.readline() # compose the document to be inserted post = {"line": line, "created": datetime.datetime.utcnow() } # insert the document into the Collection post_id = php_logs.insert(post) # output the line for visual debugging (optional) print line
mven/gonzo.py
gonzo.py
Python
mit
888
import os import pickle import numpy as np from tqdm import tqdm class SumTree: def __init__(self, capacity): self.capacity = capacity self.tree = np.zeros(2 * capacity - 1, dtype=np.float32) self.data = np.empty(capacity, dtype=object) self.head = 0 @property def total_priority(self): return self.tree[0] @property def max_priority(self): return np.max(self.tree[-self.capacity:]) @property def min_priority(self): return np.min(self.tree[-self.capacity:]) def _tree_to_data_index(self, i): return i - self.capacity + 1 def _data_to_tree_index(self, i): return i + self.capacity - 1 def add(self, priority, data): tree_index = self._data_to_tree_index(self.head) self.update_priority(tree_index, priority) self.data[self.head] = data self.head += 1 if self.head >= self.capacity: self.head = 0 def update_priority(self, tree_index, priority): delta = priority - self.tree[tree_index] self.tree[tree_index] = priority while tree_index != 0: tree_index = (tree_index - 1) // 2 self.tree[tree_index] += delta def get_leaf(self, value): parent = 0 while True: left = 2 * parent + 1 right = left + 1 if left >= len(self.tree): leaf = parent break else: if value <= self.tree[left]: parent = left else: value -= self.tree[left] parent = right data_index = self._tree_to_data_index(leaf) return leaf, self.tree[leaf], self.data[data_index] class PrioritizedExperienceReplay: def __init__(self, capacity, initial_size, epsilon, alpha, beta, beta_annealing_rate, max_td_error, ckpt_dir): self.tree = SumTree(capacity) self.capacity = capacity self.epsilon = epsilon self.initial_size = initial_size self.alpha = alpha self.beta = beta self.beta_annealing_rate = beta_annealing_rate self.max_td_error = max_td_error self.ckpt_dir = ckpt_dir def add(self, transition): max_priority = self.tree.max_priority if max_priority == 0: max_priority = self.max_td_error self.tree.add(max_priority, transition) def sample(self, batch_size): self.beta = np.min([1., self.beta + self.beta_annealing_rate]) priority_segment = self.tree.total_priority / batch_size min_probability = self.tree.min_priority / self.tree.total_priority max_weight = (min_probability * batch_size) ** (-self.beta) samples, sample_indices, importance_sampling_weights = [], [], [] for i in range(batch_size): value = np.random.uniform(priority_segment * i, priority_segment * (i + 1)) index, priority, transition = self.tree.get_leaf(value) sample_probability = priority / self.tree.total_priority importance_sampling_weights.append(((batch_size * sample_probability) ** -self.beta) / max_weight) sample_indices.append(index) samples.append(transition) return sample_indices, samples, importance_sampling_weights def update_priorities(self, tree_indices, td_errors): td_errors += self.epsilon clipped_errors = np.minimum(td_errors, self.max_td_error) priorities = clipped_errors ** self.alpha for tree_index, priority in zip(tree_indices, priorities): self.tree.update_priority(tree_index, priority) def load_or_instantiate(self, env): if os.path.exists(os.path.join(self.ckpt_dir, "memory.pkl")): self.load() return state = env.reset() for _ in tqdm(range(self.initial_size), desc="Initializing replay memory", unit="transition"): action = env.action_space.sample() next_state, reward, done, info = env.step(action) transition = (state, action, reward, next_state, done) self.add(transition) state = next_state if done: state = env.reset() def load(self): with open(os.path.join(self.ckpt_dir, "memory.pkl"), "rb") as f: self.tree = pickle.load(f) def save(self): with open(os.path.join(self.ckpt_dir, "memory.pkl"), "wb") as f: pickle.dump(self.tree, f)
akshaykurmi/reinforcement-learning
atari_breakout/per.py
Python
mit
4,539
import sys import os import csv from datetime import datetime, timedelta import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import drange from matplotlib.patches import Rectangle import scenario_factory # http://www.javascripter.net/faq/hextorgb.htm PRIMA = (148/256, 164/256, 182/256) PRIMB = (101/256, 129/256, 164/256) PRIM = ( 31/256, 74/256, 125/256) PRIMC = ( 41/256, 65/256, 94/256) PRIMD = ( 10/256, 42/256, 81/256) EC = (1, 1, 1, 0) GRAY = (0.5, 0.5, 0.5) WHITE = (1, 1, 1) def plot_each_device(sc, unctrl, cntrl): t = drange(sc.t_start, sc.t_end, timedelta(minutes=1)) for d_unctrl, d_ctrl in zip(unctrl, ctrl): fig, ax = plt.subplots(2, sharex=True) ax[0].set_ylabel('P$_{el}$ [kW]') ymax = max(d_unctrl[0].max(), d_ctrl[0].max()) / 1000.0 ax[0].set_ylim(-0.01, ymax + (ymax * 0.1)) ax[0].plot_date(t, d_unctrl[0] / 1000.0, fmt='-', lw=1, label='unctrl') ax[0].plot_date(t, d_ctrl[0] / 1000.0, fmt='-', lw=1, label='ctrl') leg0 = ax[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, borderaxespad=0.0, fancybox=False) ax[1].set_ylabel('T$_{storage}$ [\\textdegree C]') ax[1].plot_date(t, d_unctrl[2] - 273.0, fmt='-', lw=1, label='unctrl') ax[1].plot_date(t, d_ctrl[2] - 273.0, fmt='-', lw=1, label='ctrl') fig.autofmt_xdate() for label in leg0.get_texts(): label.set_fontsize('x-small') fig.subplots_adjust(left=0.1, right=0.95, top=0.88, bottom=0.2) def plot_aggregated(sc, bd, unctrl, ctrl, ctrl_sched, res=1): t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour, minutes=sc.t_block_start.minute) t = drange(t_day_start, sc.t_end, timedelta(minutes=res)) skip = (t_day_start - sc.t_start).total_seconds() / 60 / res i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res P_el_unctrl = unctrl[:,0,skip:].sum(0) P_el_ctrl = ctrl[:,0,skip:].sum(0) P_el_sched = ctrl_sched[:,skip:].sum(0) T_storage_ctrl = ctrl[:,2,skip:] ft = np.array([t[0]] + list(np.repeat(t[1:-1], 2)) + [t[-1]]) P_el_ctrl_fill = np.repeat(P_el_ctrl[:-1], 2) fig, ax = plt.subplots(2, sharex=True) fig.subplots_adjust(left=0.11, right=0.95, hspace=0.3, top=0.98, bottom=0.2) ax[0].set_ylabel('P$_{\mathrm{el}}$ [kW]') ymax = max(P_el_unctrl.max(), P_el_ctrl_fill.max(), P_el_sched.max(), 0) / 1000.0 ymin = min(P_el_unctrl.min(), P_el_ctrl_fill.min(), P_el_sched.min(), 0) / 1000.0 ax[0].set_ylim(ymin - abs(ymin * 0.1), ymax + abs(ymax * 0.1)) xspace = (t[-1] - t[-2]) ax[0].set_xlim(t[0], t[-1] + xspace) # ax[0].axvline(t[i_block_start], ls='--', color='0.5') # ax[0].axvline(t[i_block_end], ls='--', color='0.5') ax[0].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC) ax[0].axvline(t[0], ls='-', color=GRAY, lw=0.5) ax[0].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5) l_unctrl, = ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75) l_unctrl.set_dashes([1.0, 1.0]) # add lw=0.0 due to bug in mpl (will show as hairline in pdf though...) l_ctrl = ax[0].fill_between(ft, P_el_ctrl_fill / 1000.0, facecolors=PRIM+(0.5,), edgecolors=EC, lw=0.0) # Create proxy artist as l_ctrl legend handle l_ctrl_proxy = Rectangle((0, 0), 1, 1, fc=PRIM, ec=WHITE, lw=0.0, alpha=0.5) l_sched, = ax[0].plot_date(t, P_el_sched / 1000.0, fmt='-', color=PRIM, drawstyle='steps-post', lw=0.75) # colors = [ # '#348ABD', # blue # '#7A68A6', # purple # '#A60628', # red # '#467821', # green # '#CF4457', # pink # '#188487', # turqoise # '#E24A33', # orange # '#1F4A7D', # primary # '#BF9D23', # secondary # '#BF5B23', # complementary # '#94A4B6', # primaryA # '#6581A4', # primaryB # '#29415E', # primaryC # '#0A2A51', # primaryD # ][:len(unctrl)] # for (c, P_el_unctrl, P_el_ctrl, P_el_sched) in zip(colors, unctrl[:,0,:], ctrl[:,0,:], ctrl_sched): # ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt='-', color=c, lw=1, label='unctrl') # ax[0].plot_date(t, P_el_ctrl / 1000.0, fmt=':', color=c, lw=1, label='ctrl') # ax[0].plot_date(t, P_el_sched / 1000.0, fmt='--x', color=c, lw=1, label='sched') ymax = T_storage_ctrl.max() - 273 ymin = T_storage_ctrl.min() - 273 ax[1].set_ylim(ymin - abs(ymin * 0.01), ymax + abs(ymax * 0.01)) ax[1].set_ylabel('T$_{\mathrm{storage}}\;[^{\circ}\mathrm{C}]$', labelpad=9) ax[1].axvspan(t[i_block_start], t[i_block_end], fc=GRAY+(0.1,), ec=EC) ax[1].axvline(t[0], ls='-', color=GRAY, lw=0.5) ax[1].axvline(t[len(t)/2], ls='-', color=GRAY, lw=0.5) for v in T_storage_ctrl: ax[1].plot_date(t, v - 273.0, fmt='-', color=PRIMA, alpha=0.25, lw=0.5) l_T_med, = ax[1].plot_date(t, T_storage_ctrl.mean(0) - 273.0, fmt='-', color=PRIMA, alpha=0.75, lw=1.5) ax[0].xaxis.get_major_formatter().scaled[1/24.] = '%H:%M' ax[-1].set_xlabel('Tageszeit') fig.autofmt_xdate() ax[1].legend([l_sched, l_unctrl, l_ctrl_proxy, l_T_med], ['Verbundfahrplan', 'ungesteuert', 'gesteuert', 'Speichertemperaturen (Median)'], bbox_to_anchor=(0., 1.03, 1., .103), loc=8, ncol=4, handletextpad=0.2, mode='expand', handlelength=3, borderaxespad=0.25, fancybox=False, fontsize='x-small') # import pdb # pdb.set_trace() return fig def plot_aggregated_SLP(sc, bd, unctrl, ctrl, ctrl_sched, res=1): assert hasattr(sc, 'slp_file') t_day_start = sc.t_block_start - timedelta(hours=sc.t_block_start.hour, minutes=sc.t_block_start.minute) skip = (t_day_start - sc.t_start).total_seconds() / 60 / res i_block_start = (sc.t_block_start - t_day_start).total_seconds() / 60 / res i_block_end = (sc.t_block_end - t_day_start).total_seconds() / 60 / res t = drange(sc.t_block_start, sc.t_block_end, timedelta(minutes=res)) P_el_unctrl = unctrl[:,0,skip + i_block_start:skip + i_block_end].sum(0) P_el_ctrl = ctrl[:,0,skip + i_block_start:skip + i_block_end].sum(0) # ctrl correction P_el_ctrl = np.roll(P_el_ctrl, -1, axis=0) P_el_sched = ctrl_sched[:,skip + i_block_start:skip + i_block_end].sum(0) T_storage_ctrl = ctrl[:,2,skip + i_block_start:skip + i_block_end] slp = _read_slp(sc, bd)[skip + i_block_start:skip + i_block_end] diff_ctrl = (P_el_ctrl - P_el_unctrl) / 1000.0 diff_ctrl_fill = np.repeat((slp + diff_ctrl)[:-1], 2) slp_fill = np.repeat(slp[:-1], 2) ft = np.array([t[0]] + list(np.repeat(t[1:-1], 2)) + [t[-1]]) P_el_ctrl_fill = np.repeat(P_el_ctrl[:-1], 2) fig = plt.figure(figsize=(6.39, 4.25)) ax0 = fig.add_subplot(311) ax1 = fig.add_subplot(312, sharex=ax0) ax2 = fig.add_subplot(313, sharex=ax0) ax = [ax0, ax1, ax2] # bottom=0.1 doesn't work here... :( fig.subplots_adjust(left=0.11, right=0.95, hspace=0.2, top=0.93) ax[0].set_ylabel('P$_{\mathrm{el}}$ [kW]') ymax = max(P_el_unctrl.max(), P_el_ctrl_fill.max(), P_el_sched.max(), 0) / 1000.0 ymin = min(P_el_unctrl.min(), P_el_ctrl_fill.min(), P_el_sched.min(), 0) / 1000.0 ax[0].set_ylim(ymin - abs(ymin * 0.1), ymax + abs(ymax * 0.1)) xspace = (t[-1] - t[-2]) ax[0].set_xlim(t[0], t[-1] + xspace) l_unctrl, = ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt=':', color=PRIMB, drawstyle='steps-post', lw=0.75) l_unctrl.set_dashes([1.0, 1.0]) # add lw=0.0 due to bug in mpl (will show as hairline in pdf though...) l_ctrl = ax[0].fill_between(ft, P_el_ctrl_fill / 1000.0, facecolors=PRIM+(0.5,), edgecolors=EC, lw=0.0) # Create proxy artist as l_ctrl legend handle l_ctrl_proxy = Rectangle((0, 0), 1, 1, fc=PRIM, ec=WHITE, lw=0.0, alpha=0.5) l_sched, = ax[0].plot_date(t, P_el_sched / 1000.0, fmt='-', color=PRIM, drawstyle='steps-post', lw=0.75) # colors = [ # '#348ABD', # blue # '#7A68A6', # purple # '#A60628', # red # '#467821', # green # '#CF4457', # pink # '#188487', # turqoise # '#E24A33', # orange # '#1F4A7D', # primary # '#BF9D23', # secondary # '#BF5B23', # complementary # '#94A4B6', # primaryA # '#6581A4', # primaryB # '#29415E', # primaryC # '#0A2A51', # primaryD # ][:len(unctrl)] # for (c, P_el_unctrl, P_el_ctrl, P_el_sched) in zip(colors, unctrl[:,0,:], ctrl[:,0,:], ctrl_sched): # ax[0].plot_date(t, P_el_unctrl / 1000.0, fmt='-', color=c, lw=1, label='unctrl') # ax[0].plot_date(t, P_el_ctrl / 1000.0, fmt=':', color=c, lw=1, label='ctrl') # ax[0].plot_date(t, P_el_sched / 1000.0, fmt='--x', color=c, lw=1, label='sched') ymax = T_storage_ctrl.max() - 273 ymin = T_storage_ctrl.min() - 273 ax[1].set_ylim(ymin - abs(ymin * 0.01), ymax + abs(ymax * 0.01)) ax[1].set_ylabel('T$_{\mathrm{storage}}\;[^{\circ}\mathrm{C}]$', labelpad=9) for v in T_storage_ctrl: ax[1].plot_date(t, v - 273.0, fmt='-', color=PRIMA, alpha=0.25, lw=0.5) l_T_med, = ax[1].plot_date(t, T_storage_ctrl.mean(0) - 273.0, fmt='-', color=PRIMA, alpha=0.75, lw=1.5) ax[2].set_ylabel('P$_{el}$ [kW]') ax[2].set_xlabel('Tageszeit') ymin = min(slp.min(), (slp + diff_ctrl).min()) ax[2].set_ylim(ymin + (ymin * 0.1), 0) ax[2].plot_date(t, slp, fmt='-', color=PRIMB, drawstyle='steps-post', lw=0.75, label='Tageslastprofil') ax[2].fill_between(ft, diff_ctrl_fill, slp_fill, where=diff_ctrl_fill>=slp_fill, facecolors=PRIM+(0.5,), edgecolors=EC, lw=0.0) ax[2].fill_between(ft, diff_ctrl_fill, slp_fill, where=diff_ctrl_fill<slp_fill, facecolors=PRIMB+(0.5,), edgecolors=EC, lw=0.0) ax[0].legend([l_sched, l_unctrl, l_ctrl_proxy, l_T_med], ['Verbundfahrplan', 'ungesteuert', 'gesteuert', 'Speichertemperaturen (Median)'], bbox_to_anchor=(0., 1.05, 1., .105), loc=8, ncol=4, handletextpad=0.2, mode='expand', handlelength=3, borderaxespad=0.25, fancybox=False, fontsize='x-small') ax[2].legend(loc=1, fancybox=False, fontsize='x-small') fig.autofmt_xdate() ax[0].xaxis.get_major_formatter().scaled[1/24.] = '%H:%M' return fig def plot_samples(sc, basedir, idx=None): sample_data = np.load(p(basedir, sc.run_pre_samplesfile)) if idx is not None: sample_data = sample_data[idx].reshape((1,) + sample_data.shape[1:]) fig, ax = plt.subplots(len(sample_data)) if len(sample_data) == 1: ax = [ax] for i, samples in enumerate(sample_data): t = np.arange(samples.shape[-1]) for s in samples: ax[i].plot(t, s) def norm(minimum, maximum, value): # return value if maximum == minimum: return maximum return (value - minimum) / (maximum - minimum) def _read_slp(sc, bd): # Read csv data slp = [] found = False with open(sc.slp_file, 'r', encoding='latin-1') as f: reader = csv.reader(f, delimiter=';') for row in reader: if not row: continue if not found and row[0] == 'Datum': found = True elif found: date = datetime.strptime('_'.join(row[:2]), '%d.%m.%Y_%H:%M:%S') if date < sc.t_start: continue elif date >= sc.t_end: break # This is a demand, so negate the values slp.append(-1.0 * float(row[2].replace(',', '.'))) slp = np.array(slp) # Scale values # if hasattr(sc, 'run_unctrl_datafile'): # slp_norm = norm(slp.min(), slp.max(), slp) # unctrl = np.load(p(bd, sc.run_unctrl_datafile)).sum(0) / 1000 # slp = slp_norm * (unctrl.max() - unctrl.min()) + unctrl.min() MS_day_mean = 13600 # kWh, derived from SmartNord Scenario document MS_15_mean = MS_day_mean / 96 slp = slp / np.abs(slp.mean()) * MS_15_mean return slp # return np.array(np.roll(slp, 224, axis=0)) def plot_slp(sc, bd): slp = _read_slp(sc, bd) res = 1 if (sc.t_end - sc.t_start).total_seconds() / 60 == slp.shape[-1] * 15: res = 15 t = drange(sc.t_start, sc.t_end, timedelta(minutes=res)) fig, ax = plt.subplots() ax.set_ylabel('P$_{el}$ [kW]') ymax = max(slp.max(), slp.max()) ymin = min(slp.min(), slp.min()) ax.set_ylim(ymin - (ymin * 0.1), ymax + (ymax * 0.1)) ax.plot_date(t, slp, fmt='-', lw=1, label='H0') leg0 = ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, borderaxespad=0.0, fancybox=False) fig.autofmt_xdate() for label in leg0.get_texts(): label.set_fontsize('x-small') fig.subplots_adjust(left=0.1, right=0.95, top=0.88, bottom=0.2) return fig def p(basedir, fn): return os.path.join(basedir, fn) def resample(d, resolution): # resample the innermost axis to 'resolution' shape = tuple(d.shape[:-1]) + (int(d.shape[-1]/resolution), resolution) return d.reshape(shape).sum(-1)/resolution def run(sc_file): print() bd = os.path.dirname(sc_file) sc = scenario_factory.Scenario() sc.load_JSON(sc_file) print(sc.title) # plot_samples(sc, bd) # plt.show() unctrl = np.load(p(bd, sc.run_unctrl_datafile)) pre = np.load(p(bd, sc.run_pre_datafile)) block = np.load(p(bd, sc.run_ctrl_datafile)) post = np.load(p(bd, sc.run_post_datafile)) sched = np.load(p(bd, sc.sched_file)) ctrl = np.zeros(unctrl.shape) idx = 0 for l in (pre, block, post): ctrl[:,:,idx:idx + l.shape[-1]] = l idx += l.shape[-1] if sched.shape[-1] == unctrl.shape[-1] / 15: print('Extending schedules shape by factor 15') sched = sched.repeat(15, axis=1) ctrl_sched = np.zeros((unctrl.shape[0], unctrl.shape[-1])) ctrl_sched = np.ma.array(ctrl_sched) ctrl_sched[:,:pre.shape[-1]] = np.ma.masked ctrl_sched[:,pre.shape[-1]:pre.shape[-1] + sched.shape[-1]] = sched ctrl_sched[:,pre.shape[-1] + sched.shape[-1]:] = np.ma.masked # plot_each_device(sc, unctrl, ctrl, sched) minutes = (sc.t_end - sc.t_start).total_seconds() / 60 assert unctrl.shape[-1] == ctrl.shape[-1] == ctrl_sched.shape[-1] shape = unctrl.shape[-1] if hasattr(sc, 'slp_file'): if minutes == shape: print('data is 1-minute resolution, will be resampled by 15') res = 15 elif minutes == shape * 15: print('data is 15-minute resolution, all fine') res = 1 else: raise RuntimeError('unsupported data resolution: %.2f' % (minutes / shape)) unctrl = resample(unctrl, res) ctrl = resample(ctrl, res) ctrl_sched = resample(ctrl_sched, res) fig = plot_aggregated_SLP(sc, bd, unctrl, ctrl, ctrl_sched, res=15) else: if minutes == shape: print('data is 1-minute resolution, will be resampled by 60') res = 60 elif minutes == shape * 15: print('data is 15-minute resolution, will be resampled by 4') res = 4 elif minutes == shape * 60: print('data is 60-minute resolution, all fine') res = 1 else: raise RuntimeError('unsupported data resolution: %.2f' % (minutes / shape)) unctrl = resample(unctrl, res) ctrl = resample(ctrl, res) ctrl_sched = resample(ctrl_sched, res) fig = plot_aggregated(sc, bd, unctrl, ctrl, ctrl_sched, res=60) fig.savefig(p(bd, sc.title) + '.pdf') fig.savefig(p(bd, sc.title) + '.png', dpi=300) # plt.show() if __name__ == '__main__': for n in sys.argv[1:]: if os.path.isdir(n): run(p(n, '0.json')) else: run(n)
ambimanus/appsim
analyze-headless.py
Python
mit
16,543
#!/usr/bin/env python """ The MIT License (MIT) Copyright (c) 2017 LeanIX GmbH 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. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ class ServiceHasResource: """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): self.swaggerTypes = { 'ID': 'str', 'resourceID': 'str', 'serviceID': 'str', 'comment': 'str', 'technicalSuitabilityID': 'str', 'costTotalAnnual': 'float', 'serviceLevelID': 'str', 'primaryTypeID': 'str' } self.ID = None # str self.resourceID = None # str self.serviceID = None # str self.comment = None # str self.technicalSuitabilityID = None # str self.costTotalAnnual = None # float self.serviceLevelID = None # str self.primaryTypeID = None # str
leanix/leanix-sdk-python
src/leanix/models/ServiceHasResource.py
Python
mit
2,033
# Generated by Django 2.1.8 on 2019-04-05 07:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainapp', '0022_auto_20190404_1605'), ] operations = [ migrations.AlterField( model_name='historicalpaper', name='reference_number', field=models.CharField(blank=True, max_length=50, null=True), ), migrations.AlterField( model_name='paper', name='reference_number', field=models.CharField(blank=True, max_length=50, null=True), ), ]
meine-stadt-transparent/meine-stadt-transparent
mainapp/migrations/0023_auto_20190405_0911.py
Python
mit
612
import sklearn.cross_validation as cv import sklearn.dummy as dummy from sklearn.mixture import GMM from sklearn.hmm import GMMHMM from sklearn import linear_model, naive_bayes import collections import itertools import pandas as pd from testResults import TestResults from counters import * import utils as utils class Model(): __metaclass__ = ABCMeta params = {} isSklearn = True def __init__(self, params, verbose=False): self.params = params self.verbose = verbose def printv(self, arg, title=None): if self.verbose: if title is not None: print title print arg @property def name(self): return self._name @abstractmethod def _train(self, data): """Returns a trained model.""" pass def _test(self, model, testData, resultObj): """Compares predictions made by specified model against test data. Returns a TestResults object. """ # restrict test data to principal component features features = self.params['features'] test = np.array(testData[features]) # predict a dialog sequence using test data # sklearn counts from 0 so add 1... if self.isSklearn: pred = [int(r) + 1 for r in list(model.predict(test))] else: pred = [int(r) for r in list(model.predict(test))] # extract true ratings from test data true = [int(rating) for rating in testData['rating'].values.tolist()] resultObj.compare(true, pred) return resultObj def loocv(self, data): """Leave-one-out cross validation using given data. Returns a TestResults objects, where results are averages from the cross validation steps. """ mask = cv.LeaveOneLabelOut(data['label'].values) results = TestResults(self.name, verbose=self.verbose) for trainMask, testMask in mask: # training trainingData = data.loc[trainMask] self.printv(trainingData, "training data:") model = self._train(trainingData) # testing testData = data.loc[testMask] self.printv(testData, "test data:") # leave p labels out for label, testGroup in testData.groupby("label"): results = self._test(model, testGroup, results) return results def kfoldscv(self, data, folds): """K-folds cross validation using given data and number of folds. Returns a TestResults objects, where results are averages from the cross validation steps. """ results = TestResults(self.name, verbose=self.verbose) labels = list(np.unique(data['label'].values)) for tr, te in cv.KFold(len(labels), n_folds=folds): trainD = data[data['label'].isin([labels[i] for i in tr])] testD = data[data['label'].isin([labels[i] for i in te])] self.printv(trainD, "training data:") self.printv(testD, "test data:") model = self._train(trainD) for label, testGroup in testD.groupby("label"): results = self._test(model, testGroup, results) return results def setFeatures(self, features): self.params['features'] = features class Dummy(Model): _name = "dummy" def _train(self, data): if 'constant' in self.params.keys(): model = dummy.DummyClassifier(strategy=self.params['strategy'], constant=self.params['constant']) else: model = dummy.DummyClassifier(strategy=self.params['strategy']) d = np.array(zip(*[data[f].values for f in self.params['features']])) y = np.array(data['rating'].values) model.fit(d, y) return model class Gmm(Model): """A Gaussian mixture model. Parameters are number of mixture components (num_mixc) and covariance type (cov_type). Example: model = Gmm(params = {num_mixc: 3, cov_type:'diag'}) """ _name = "GMM" def _train(self, data): """Trains a Gaussian mixture model, using the sklearn implementation.""" # parameters features = self.params['features'] num_mixc = self.params['num_mixc'] cov_type = self.params['cov_type'] # prepare data shape d = np.array(zip(*[data[f].values for f in features])) # choose high number of EM-iterations to get constant results gmm = GMM(num_mixc, cov_type, n_iter=300) gmm.fit(d) return gmm class Gmmhmm(Model): """A hidden Markov model with Gaussian mixture emissions. Parameters are number of mixture components (num_mixc), covariance type (cov_type) and states (states). One Gaussian mixture model is created for each state. Example: model = Gmmhmm(params = {'num_mixc': 3, 'cov_type': 'diag', 'states': [1,2,3,4,5]}) """ _name = "GMM-HMM" def _train(self, data): """Trains a GMMHMM model, using the sklearn implementation and maximum- likelihood estimates as HMM parameters (Hmm.mle(...)). """ # parameters features = self.params['features'] num_mixc = self.params['num_mixc'] cov_type = self.params['cov_type'] states = self.params['states'] # train one GMM for each state mixes = list() for state in states: # select data with current state label d = data[data.rating == state] # prepare data shape d = np.array(zip(*[d[f].values for f in features])) # init GMM gmm = GMM(num_mixc, cov_type) # train gmm.fit(d) mixes.append(gmm) # train HMM with init, trans, GMMs=mixes mle = Hmm.mle(MatrixCounterNoEmissions, data, states) model = GMMHMM(n_components=len(states), init_params='', gmms=mixes) model.transmat_ = mle.transition model.startprob_ = mle.initial return model class Ols(Model): """ Ordinary least squares regression """ _name = "OLS" isSklearn = True def _train(self, data): features = self.params['features'] X = np.array(zip(*[data[f].values for f in features])) y = np.array(data['rating']) model = linear_model.LinearRegression() model.fit(X, y) return model class LogisticRegression(Model): """ Logistic Regression """ _name = "Logit" isSklearn = True def _train(self, data): features = self.params['features'] X = np.array(zip(*[data[f].values for f in features])) y = np.array(data['rating']) model = linear_model.LogisticRegression(class_weight=self.params['class_weight']) model.fit(X, y) return model class GaussianNaiveBayes(Model): """ Gaussian Naive Bayes... """ _name = "G-NB" isSklearn = True def _train(self, data): features = self.params['features'] X = np.array(zip(*[data[f].values for f in features])) y = np.array(data['rating']) model = naive_bayes.GaussianNB() model.fit(X, y) return model class MultinomialNaiveBayes(Model): """ Multinomial Naive Bayes... """ _name = "M-NB" isSklearn = True def _train(self, data): features = self.params['features'] X = np.array(zip(*[data[f].values for f in features])) y = np.array(data['rating']) model = naive_bayes.MultinomialNB(alpha=self.params['alpha'], fit_prior=self.params['fit_prior']) model.fit(X, y) return model class Hmm(Model): """A hidden Markov model, using the Nltk implementation and maximum- likelihood parameter estimates. """ _name = "HMM" isSklearn = False Parameters = collections.namedtuple( 'Parameters', 'initial transition emission emissionAlph') class NltkWrapper(): def __init__(self, states, mle): self.model = nltk.HiddenMarkovModelTagger(mle.emissionAlph, states, mle.transition, mle.emission, mle.initial) def predict(self, obs): tagged = self.model.tag([tuple(o) for o in obs]) return [val[1] for val in tagged] def _train(self, data): features = self.params['features'] states = self.params['states'] # calculate maximum-likelihood parameter estimates mle = Hmm.mle_multipleFeatures(NltkCounter, data, states, features, self.verbose) # create nltk HMM model = Hmm.NltkWrapper(states, mle) return model @staticmethod def mle(counterClass, data, stateAlphabet, feature=False): """ Calculate maximum likelihood estimates for the HMM parameters transitions probabilites, emission probabilites, and initial state probabilites. """ f = feature is not False states = utils.dfToSequences(data, ['rating']) if f: emissionAlphabet = pd.unique(data[feature].values.ravel()) emissions = utils.dfToSequences(data, [feature]) else: emissionAlphabet = None counter = counterClass(stateAlphabet, emissionAlphabet, states) # count for each state sequence for k, seq in enumerate(states): if f: emi = emissions[k] # for each state transition for i, current in enumerate(seq): # count(current, next, first, emission) if f: emission = emi[i] else: emission = False next = seq[i + 1] if i < len(seq) - 1 else False counter.count(i, current, next, emission) return Hmm.Parameters( initial=counter.getInitialProb(), transition=counter.getTransitionProb(), emission=counter.getEmissionProb(), emissionAlph=emissionAlphabet ) @staticmethod def mle_multipleFeatures(counterClass, data, stateAlphabet, features, verbose=False): """ Calculate maximum likelihood estimates of HMM parameters. Parameters are transition probabilites, emission probabilites and initial sta<te probabilites. This method allows specifing multiple features and combines multiple emission features assuming conditional independence: P(feat1=a & feat2=b|state) = P(feat1=a|state) * P(feat2=b|state) """ p = lambda feat: Hmm.mle(DictCounter, data, stateAlphabet, feat) counter = counterClass(stateAlphabet, [], False) # calculate conditional probabilites for each feature & corresponding # emission alphabet entry.. # P(feat_i=emm_ij|state_k) forall: I features, J_i emissions, K states # ps = {feature:emmission distribution} emission_probs = [p(f).emission for f in features] # calculate inital state probabilites, transition probabilites using # first/any feature mle_single = Hmm.mle(counterClass, data, stateAlphabet, features[0]) initial_probs = mle_single.initial transition_probs = mle_single.transition # combine the emission alphabets of all given features emissionAlphabet = list() for f in features: emissionAlphabet.append(pd.unique(data[f].values.ravel())) # calculate all emission combinations # and according probabilities per state for comb in list(itertools.product(*emissionAlphabet)): counter.addEmissionCombination(tuple(comb)) for state in stateAlphabet: # for each individual prob of each feature for emission, featNum in zip(comb, xrange(0, len(emission_probs))): prob = emission_probs[featNum][state][emission] counter.addCombinedEmissionProb(state, tuple(comb), prob) if verbose: print("Initial Probabilities") printDictProbDist(initial_probs) print("Transition Probabilities") printCondDictProbDist(transition_probs) print("Emission Probabilities") printCondDictProbDist(counter.getCombinedEmissionProb()) return Hmm.Parameters( initial=initial_probs, transition=transition_probs, emission=counter.getCombinedEmissionProb(), emissionAlph=counter.getEmissionCombinations() )
phihes/sds-models
sdsModels/models.py
Python
mit
12,892
# -*- coding: utf-8 -*- from f6a_tw_crawler.constants import * import unittest import logging def setup(): pass def teardown(): pass
chhsiao1981/f6a_tw_crawler
tests/__init__.py
Python
mit
147
# 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
# -*- coding: utf-8 -*- """ Plugins related to folders and paths """ from hyde.plugin import Plugin from hyde.fs import Folder class FlattenerPlugin(Plugin): """ The plugin class for flattening nested folders. """ def __init__(self, site): super(FlattenerPlugin, self).__init__(site) def begin_site(self): """ Finds all the folders that need flattening and changes the relative deploy path of all resources in those folders. """ items = [] try: items = self.site.config.flattener.items except AttributeError: pass for item in items: node = None target = '' try: node = self.site.content.node_from_relative_path(item.source) target = Folder(item.target) except AttributeError: continue if node: for resource in node.walk_resources(): target_path = target.child(resource.name) self.logger.debug( 'Flattening resource path [%s] to [%s]' % (resource, target_path)) resource.relative_deploy_path = target_path
stiell/hyde
hyde/ext/plugins/folders.py
Python
mit
1,263
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() user = models.ForeignKey(User)
erkarl/browl-api
apps/posts/models.py
Python
mit
211
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('builds', '0010_merge'), ] operations = [ migrations.AlterField( model_name='project', name='approved', field=models.BooleanField(default=False, db_index=True), preserve_default=True, ), ]
frigg/frigg-hq
frigg/builds/migrations/0011_auto_20150223_0442.py
Python
mit
444
from kazoo.exceptions import NoNodeError from sys import maxsize from .mutex import Mutex from .internals import LockDriver from .utils import lazyproperty READ_LOCK_NAME = "__READ__" WRITE_LOCK_NAME = "__WRIT__" class _LockDriver(LockDriver): def sort_key(self, string, _lock_name): string = super(_LockDriver, self).sort_key(string, READ_LOCK_NAME) string = super(_LockDriver, self).sort_key(string, WRITE_LOCK_NAME) return string class _ReadLockDriver(_LockDriver): def __init__(self, predicate): super(_ReadLockDriver, self).__init__() self._predicate = predicate def is_acquirable(self, children, sequence_node_name, max_leases): return self._predicate(children, sequence_node_name) class _Mutex(Mutex): def __init__(self, client, path, name, max_leases, driver, timeout): super(_Mutex, self).__init__( client, path, max_leases, name=name, driver=driver, timeout=timeout ) def get_participant_nodes(self): nodes = super(_Mutex, self).get_participant_nodes() return list(filter(lambda node: self.name in node, nodes)) class ReadWriteLock(object): def __init__(self, client, path, timeout=None): self._client = client self._path = path self._timeout = timeout @property def path(self): return self._path @property def timeout(self): return self._timeout @timeout.setter def timeout(self, value): self._timeout = value self.read_lock.timeout = value self.write_lock.timeout = value @lazyproperty def read_lock(self): def predicate(children, sequence_node_name): return self._read_is_acquirable_predicate( children, sequence_node_name ) return _Mutex( self._client, self.path, READ_LOCK_NAME, maxsize, _ReadLockDriver(predicate), self.timeout ) @lazyproperty def write_lock(self): return _Mutex( self._client, self.path, WRITE_LOCK_NAME, 1, _LockDriver(), self.timeout ) def get_participant_nodes(self): nodes = self.read_lock.get_participant_nodes() nodes.extend(self.write_lock.get_participant_nodes()) return nodes def _read_is_acquirable_predicate(self, children, sequence_node_name): if self.write_lock.is_owned_by_current_thread: return (None, True) index = 0 write_index = maxsize our_index = -1 for node in children: if WRITE_LOCK_NAME in node: write_index = min(index, write_index) elif node.startswith(sequence_node_name): our_index = index break index += 1 if our_index < 0: raise NoNodeError acquirable = our_index < write_index path = None if acquirable else children[write_index] return (path, acquirable)
pseudomuto/kazurator
kazurator/read_write_lock.py
Python
mit
3,177
""" You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet. Return an array of names that will be given to the files. Example For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]. Input/Output [execution time limit] 4 seconds (py) [input] array.string names Guaranteed constraints: 5 <= names.length <= 15, 1 <= names[i].length <= 15. [output] array.string """ def fileNaming(names): new_names = [] for name in names: if name not in new_names: new_names.append(name) else: for x in range(1, 16): if "{}({})".format(name, x) not in new_names: new_names.append("{}({})".format(name, x)) break return new_names if __name__ == '__main__': print fileNaming(["doc", "doc", "image", "doc(1)", "doc"])
coingraham/codefights
python/fileNaming/fileNaming.py
Python
mit
1,136
from distutils.core import setup setup( name = "nip", version = "0.1a1", py_modules = [ "nip", ], scripts = [ "bin/nip", ], author = "Brian Rosner", author_email = "brosner@gmail.com", description = "nip is environment isolation and installation for Node.js", long_description = open("README.rst").read(), license = "MIT", classifiers = [ "Development Status :: 2 - Pre-Alpha", ], )
brosner/nip
setup.py
Python
mit
461
import unittest from allergies import Allergies # Python 2/3 compatibility if not hasattr(unittest.TestCase, 'assertCountEqual'): unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class AllergiesTests(unittest.TestCase): def test_no_allergies_means_not_allergic(self): allergies = Allergies(0) self.assertIs(allergies.is_allergic_to('peanuts'), False) self.assertIs(allergies.is_allergic_to('cats'), False) self.assertIs(allergies.is_allergic_to('strawberries'), False) def test_is_allergic_to_eggs(self): self.assertIs(Allergies(1).is_allergic_to('eggs'), True) def test_allergic_to_eggs_in_addition_to_other_stuff(self): allergies = Allergies(5) self.assertIs(allergies.is_allergic_to('eggs'), True) self.assertIs(allergies.is_allergic_to('shellfish'), True) self.assertIs(allergies.is_allergic_to('strawberries'), False) def test_no_allergies_at_all(self): self.assertEqual(Allergies(0).lst, []) def test_allergic_to_just_eggs(self): self.assertEqual(Allergies(1).lst, ['eggs']) def test_allergic_to_just_peanuts(self): self.assertEqual(Allergies(2).lst, ['peanuts']) def test_allergic_to_just_strawberries(self): self.assertEqual(Allergies(8).lst, ['strawberries']) def test_allergic_to_eggs_and_peanuts(self): self.assertCountEqual(Allergies(3).lst, ['eggs', 'peanuts']) def test_allergic_to_more_than_eggs_but_not_peanuts(self): self.assertCountEqual(Allergies(5).lst, ['eggs', 'shellfish']) def test_allergic_to_lots_of_stuff(self): self.assertCountEqual( Allergies(248).lst, ['strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats']) def test_allergic_to_everything(self): self.assertCountEqual( Allergies(255).lst, [ 'eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats' ]) def test_ignore_non_allergen_score_parts_only_eggs(self): self.assertEqual(Allergies(257).lst, ['eggs']) def test_ignore_non_allergen_score_parts(self): self.assertCountEqual( Allergies(509).lst, [ 'eggs', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats' ]) if __name__ == '__main__': unittest.main()
pheanex/xpython
exercises/allergies/allergies_test.py
Python
mit
2,509
import numpy import argparse import time import mido import colorsys import gitgrid.gridcontroller import gitgrid.utils.utils args = gitgrid.utils.utils.controller_args() tmp = gitgrid.gridcontroller.create(args.controller, args.input, args.output) def toggle(x, y, Message): curr = tmp.lights[x, y, :] / 255. hsv = list(colorsys.rgb_to_hsv(*curr)) hsv[0] += 0.1 tmp.lights[x, y, :] = numpy.array(colorsys.hsv_to_rgb(*hsv)) * 255. def foo(action, message): print action tmp.lights[:, :] = numpy.array([1, 0, 0]) tmp.buttons[:, :] = toggle tmp.actions = { 'up': foo, 'down': foo, 'left': foo, 'right': foo, 'tab1': foo, 'tab2': foo, 'tab3': foo, 'tab4': foo, 'ok': foo, 'cancel': foo, } tmp.loop()
RocketScienceAbteilung/git-grid
experiments/buttons.py
Python
mit
766
import RPi.GPIO as gpio from datetime import datetime import time import controller gpio.setmode(gpio.BOARD) # switch_pins = [10, 40, 38] switch = 10 gpio.setup(switch, gpio.OUT, initial=False) # gpio.setup(switch_pins, gpio.OUT, initial=False) def switch_on(): gpio.output(switch, True) print "Oven switched ON at " + str(datetime.now()) def switch_off(): gpio.output(switch, False) print "Oven switched OFF at " + str(datetime.now()) def status(): return gpio.input(switch) switch_on() print status() time.sleep(3) switch_off() print status() # gpio.cleanup()
emgreen33/easy_bake
oven.py
Python
mit
583
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.http import Http404 from django.shortcuts import render from django.contrib.auth.decorators import login_required from snisi_core.permissions import provider_allowed_or_denied from snisi_core.models.Projects import Cluster from snisi_core.models.Periods import MonthPeriod, Period from snisi_core.models.Entities import Entity from snisi_trachoma.models import TTBacklogMissionR from snisi_web.utils import (entity_browser_context, get_base_url_for_period, get_base_url_for_periods, ensure_entity_in_cluster, ensure_entity_at_least) logger = logging.getLogger(__name__) @login_required def trachoma_mission_browser(request, entity_slug=None, period_str=None, **kwargs): context = {} root = request.user.location cluster = Cluster.get_or_none('trachoma_backlog') entity = Entity.get_or_none(entity_slug) if entity is None: entity = root if entity is None: raise Http404("Aucune entité pour le code {}".format(entity_slug)) # make sure requested entity is in cluster ensure_entity_in_cluster(cluster, entity) # check permissions on this entity and raise 403 provider_allowed_or_denied(request.user, 'access_trachoma', entity) # mission browser is reserved to district-level and above ensure_entity_at_least(entity, 'health_district') def period_from_strid(period_str, reportcls=None): period = None if period_str: try: period = Period.from_url_str(period_str).casted() except: pass return period period = period_from_strid(period_str) if period is None: period = MonthPeriod.current() try: first_period = MonthPeriod.find_create_by_date( TTBacklogMissionR.objects.all() .order_by('period__start_on')[0].period.middle()) except IndexError: first_period = MonthPeriod.current() all_periods = MonthPeriod.all_from(first_period) context.update({ 'all_periods': [(p.strid(), p) for p in reversed(all_periods)], 'period': period, 'base_url': get_base_url_for_period( view_name='trachoma_missions', entity=entity, period_str=period_str or period.strid()) }) context.update(entity_browser_context( root=root, selected_entity=entity, full_lineage=['country', 'health_region', 'health_district'], cluster=cluster)) # retrieve list of missions for that period missions = TTBacklogMissionR.objects.filter( period=period, entity__slug__in=[e.slug for e in entity.get_health_districts()]) context.update({'missions': missions}) return render(request, kwargs.get('template_name', 'trachoma/missions_list.html'), context) @login_required def trachoma_mission_viewer(request, report_receipt, **kwargs): context = {} mission = TTBacklogMissionR.get_or_none(report_receipt) if mission is None: return Http404("Nº de reçu incorrect : {}".format(report_receipt)) context.update({'mission': mission}) return render(request, kwargs.get('template_name', 'trachoma/mission_detail.html'), context) @login_required def trachoma_dashboard(request, entity_slug=None, perioda_str=None, periodb_str=None, **kwargs): context = {} root = request.user.location cluster = Cluster.get_or_none('trachoma_backlog') entity = Entity.get_or_none(entity_slug) if entity is None: entity = root if entity is None: raise Http404("Aucune entité pour le code {}".format(entity_slug)) # make sure requested entity is in cluster ensure_entity_in_cluster(cluster, entity) # check permissions on this entity and raise 403 provider_allowed_or_denied(request.user, 'access_trachoma', entity) # mission browser is reserved to district-level and above ensure_entity_at_least(entity, 'health_district') def period_from_strid(period_str, reportcls=None): period = None if period_str: try: period = Period.from_url_str(period_str).casted() except: pass return period perioda = period_from_strid(perioda_str) periodb = period_from_strid(periodb_str) if periodb is None: periodb = MonthPeriod.current() if perioda is None: perioda = periodb if perioda is None or periodb is None: raise Http404("Période incorrecte.") if perioda > periodb: t = perioda perioda = periodb periodb = t del(t) try: first_period = MonthPeriod.find_create_by_date( TTBacklogMissionR.objects.all().order_by( 'period__start_on')[0].period.middle()) except IndexError: first_period = MonthPeriod.current() all_periods = MonthPeriod.all_from(first_period) periods = MonthPeriod.all_from(perioda, periodb) context.update({ 'all_periods': [(p.strid(), p) for p in reversed(all_periods)], 'periods': periods, 'perioda': perioda, 'periodb': periodb, 'base_url': get_base_url_for_periods( view_name='trachoma_dashboard', entity=entity, perioda_str=perioda_str or perioda.strid(), periodb_str=periodb_str or periodb.strid()) }) context.update(entity_browser_context( root=root, selected_entity=entity, full_lineage=['country', 'health_region', 'health_district'], cluster=cluster)) # retrieve Indicator Table from snisi_trachoma.indicators import (MissionDataSummary, CumulativeBacklogData) missions_followup = MissionDataSummary(entity=entity, periods=periods) cumulative_backlog = CumulativeBacklogData(entity=entity, periods=periods) context.update({ 'missions_followup': missions_followup, 'cumulative_backlog': cumulative_backlog, }) return render(request, kwargs.get('template_name', 'trachoma/dashboard.html'), context)
yeleman/snisi
snisi_trachoma/views.py
Python
mit
6,715
import os import codecs, re, time, string, logging, math from operator import itemgetter from nltk import FreqDist from nltk.corpus import stopwords import textmining from scipy import spatial from . import filehandler def most_frequent_terms(*args): tdm = textmining.TermDocumentMatrix(simple_tokenize_remove_our_stopwords) for doc in args: tdm.add_doc(doc) freqs = [] for d in tdm.sparse: f = [(freq, name) for (name, freq) in list(d.items())] f.sort(reverse=True) freqs.append(f) return freqs def doc_to_words(document): ''' Turn a document into a list of all the words in it # TODO: include word stemming ''' t1 = time.time() words = re.findall(r"[\w']+|[.,!?;]", document, re.UNICODE) t2 = time.time() words = [w.lower() for w in words] t3 = time.time() words = [w for w in words if not w in string.punctuation] t4 = time.time() logging.debug(" tokenize: %d" % (t2-t1)) logging.debug(" ignore_case: %d" % (t3-t2)) logging.debug(" remove punctuation: %d" % (t4-t3)) return words # TODO add a langauge param to remove spanish stop words too def term_frequency(words): ''' Turn a list of words into a NLTK frequency distribution object ''' t1 = time.time() fdist = FreqDist(words) # remove stopwords here rather than in corpus text for speed # http://stackoverflow.com/questions/7154312/how-do-i-remove-entries-within-a-counter-object-with-a-loop-without-invoking-a-r for w in list(fdist): if w in stopwords.words('english'): del fdist[w] t2 = time.time() logging.debug(" create term freq: %d" % (t2-t1)) return fdist def _count_incidence(lookup, term): if term in lookup: lookup[term] += 1 else: lookup[term] = 1 def inverse_document_frequency(list_of_fdist_objects): ''' Turn a list of words lists into a document frequency ''' doc_count = len(list_of_fdist_objects) term_doc_incidence = {} t1 = time.time() [_count_incidence(term_doc_incidence,term) \ for fdist in list_of_fdist_objects \ for term in list(fdist.keys()) ] t2 = time.time() idf = { term: math.log(float(doc_count)/float(incidence)) for term, incidence in term_doc_incidence.items() } t3 = time.time() logging.debug(" create df: %d" % (t2-t1)) logging.debug(" create idf: %d" % (t3-t2)) return idf def tf_idf(list_of_file_paths): ''' Compute and return tf-idf from a list of file paths (sorted by tfidf desc) ''' doc_list = [ filehandler.convert_to_txt(file_path) for file_path in list_of_file_paths ] tf_list = [ term_frequency( doc_to_words(doc) ) for doc in doc_list ] # a list of FreqDist objects idf = inverse_document_frequency(tf_list) tf_idf_list = [ [{'term':term, 'tfidf':frequency*idf[term], 'frequency': frequency} for term, frequency in tf.items()] for tf in tf_list ] tf_idf_list = [ sorted(tf_idf, key=itemgetter('tfidf'), reverse=True) for tf_idf in tf_idf_list ] return tf_idf_list def simple_tokenize_remove_our_stopwords(document): """ Clean up a document and split into a list of words, removing stopwords. Converts document (a string) to lowercase and strips out everything which is not a lowercase letter. Then removes stopwords. """ document = document.lower() document = re.sub('[^a-z\']', ' ', document) words = document.strip().split() # Remove stopwords words = [word for word in words if word not in stopwords.words('english')] return words def cosine_similarity(list_of_file_paths): # Create some very short sample documents doc_list = [ filehandler.convert_to_txt(file_path) for file_path in list_of_file_paths ] # Initialize class to create term-document matrix tdm = textmining.TermDocumentMatrix(tokenizer=simple_tokenize_remove_our_stopwords) for doc in doc_list: tdm.add_doc(doc) results = [] is_first_row1 = True for row1 in tdm.rows(cutoff=1): if is_first_row1: is_first_row1 = False continue is_first_row2 = True cols = [] for row2 in tdm.rows(cutoff=1): if is_first_row2: is_first_row2 = False continue cols.append( 1 - spatial.distance.cosine(row1,row2) ) results.append(cols) return results
c4fcm/DataBasic
databasic/logic/tfidfanalysis.py
Python
mit
4,459
#!/usr/bin/env python # Copyright (c) 2008 Aldo Cortesi # Copyright (c) 2011 Mounier Florian # Copyright (c) 2012 dmpayton # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 roger # Copyright (c) 2014 Pedro Algarvio # Copyright (c) 2014-2015 Tycho Andersen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import textwrap from setuptools import setup from setuptools.command.install import install class CheckCairoXcb(install): def cairo_xcb_check(self): try: from cairocffi import cairo cairo.cairo_xcb_surface_create return True except AttributeError: return False def finalize_options(self): if not self.cairo_xcb_check(): print(textwrap.dedent(""" It looks like your cairocffi was not built with xcffib support. To fix this: - Ensure a recent xcffib is installed (pip install 'xcffib>=0.3.2') - The pip cache is cleared (remove ~/.cache/pip, if it exists) - Reinstall cairocffi, either: pip install --no-deps --ignore-installed cairocffi or pip uninstall cairocffi && pip install cairocffi """)) sys.exit(1) install.finalize_options(self) long_description = """ A pure-Python tiling window manager. Features ======== * Simple, small and extensible. It's easy to write your own layouts, widgets and commands. * Configured in Python. * Command shell that allows all aspects of Qtile to be managed and inspected. * Complete remote scriptability - write scripts to set up workspaces, manipulate windows, update status bar widgets and more. * Qtile's remote scriptability makes it one of the most thoroughly unit-tested window mangers around. """ if '_cffi_backend' in sys.builtin_module_names: import _cffi_backend requires_cffi = "cffi==" + _cffi_backend.__version__ else: requires_cffi = "cffi>=1.1.0" # PyPy < 2.6 compatibility if requires_cffi.startswith("cffi==0."): cffi_args = dict( zip_safe=False ) else: cffi_args = dict(cffi_modules=[ 'libqtile/ffi_build.py:pango_ffi', 'libqtile/ffi_build.py:xcursors_ffi' ]) dependencies = ['xcffib>=0.3.2', 'cairocffi>=0.7', 'six>=1.4.1', requires_cffi] if sys.version_info >= (3, 4): pass elif sys.version_info >= (3, 3): dependencies.append('asyncio') else: dependencies.append('trollius') setup( name="qtile", version="0.10.6", description="A pure-Python tiling window manager.", long_description=long_description, classifiers=[ "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Operating System :: Unix", "Topic :: Desktop Environment :: Window Managers", ], keywords="qtile tiling window manager", author="Aldo Cortesi", author_email="aldo@nullcube.com", maintainer="Tycho Andersen", maintainer_email="tycho@tycho.ws", url="http://qtile.org", license="MIT", install_requires=dependencies, setup_requires=dependencies, extras_require={ 'ipython': ["ipykernel", "jupyter_console"], }, packages=['libqtile', 'libqtile.interactive', 'libqtile.layout', 'libqtile.scripts', 'libqtile.widget', 'libqtile.resources' ], package_data={'libqtile.resources': ['battery-icons/*.png']}, entry_points={ 'console_scripts': [ 'qtile = libqtile.scripts.qtile:main', 'qtile-run = libqtile.scripts.qtile_run:main', 'qtile-top = libqtile.scripts.qtile_top:main', 'qshell = libqtile.scripts.qshell:main', ] }, scripts=[ 'bin/iqshell', ], data_files=[ ('share/man/man1', ['resources/qtile.1', 'resources/qshell.1'])], cmdclass={'install': CheckCairoXcb}, **cffi_args )
de-vri-es/qtile
setup.py
Python
mit
5,466
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20150703_0836'), ] operations = [ migrations.AlterField( model_name='user', name='followers', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='followers_rel_+'), ), ]
28harishkumar/Social-website-django
user/migrations/0003_auto_20150703_0843.py
Python
mit
485
from django.db import models from django.contrib.postgres.fields.jsonb import JSONField class Supplier(models.Model): name = models.CharField(max_length=50) tax_id = models.CharField(max_length=10) def __str__(self): return self.name class Bargain(models.Model): sku = models.CharField(max_length=20) price = models.DecimalField(max_digits=7, decimal_places=2) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, db_index=True) info = JSONField(db_index=True) # This will create a btree index, not GIN def __str__(self): return self.sku @property def description(self): return self.info.get('description', '') @property def sale_price(self): return self.info.get('sale_price', '') @property def acquire_cost(self): return self.info.get('acquire_cost', '') @property def color(self): return self.info.get('color', '')
sebastian-code/jsonb-test
jsonb/emporium/models.py
Python
mit
986
# !/usr/bin python """ # # data-collect.py contain the python program to gather Metrics from vROps. Before you run this script # set-config.py should be run once to set the environment # Author Sajal Debnath <sdebnath@vmware.com> # """ # Importing the Modules import nagini import requests #import pprint import json import os, sys import base64 import time from requests.packages.urllib3.exceptions import InsecureRequestWarning # Function to get the absolute path from where the script is being run def get_script_path(): return os.path.dirname(os.path.realpath(sys.argv[0])) # Function to get the metric data def get_metric_data(resourceknd,adapter,key,sampleno ): outdata = [] # It's going to store the final JSON data # Gettting a list of resources which matches the criteria or resourceKind and adapterKind for resource in vrops.get_resources(resourceKind=resourceknd, adapterKindKey=adapter)['resourceList']: allstat = {} # This variable will hold all the statistics of all resources resourcedata = {} # This variable is going to hold value for individual resource # print (resource['identifier'], resource['resourceKey']['name']) name = resource['identifier'] # Gettting the metric values for the keys of a particular resource allvalues = vrops.get_latest_stats(resourceId=name, statKey=key,maxSamples=sampleno, id=name) # Building the components of the output JSON file resourcedata["identifier"] = resource['identifier'] resourcedata["name"] = resource['resourceKey']['name'] # Checking for any null values if not allvalues["values"]: continue else: if int(sampleno) == 1: for value in allvalues["values"][0]["stat-list"]["stat"]: allstat[value["statKey"]["key"]] = value["data"][0] else: # We have a range of values to store for singlevalue in allvalues["values"][0]["stat-list"]["stat"]: # pp.pprint(value) all_metric_data = [] sample = len(singlevalue["data"]) for i in range(sample): metric_data = {} metric_data["value"] = singlevalue["data"][i] metric_data["timestamp"] = singlevalue["timestamps"][i] all_metric_data.append(metric_data) allstat[singlevalue["statKey"]["key"]] = all_metric_data resourcedata["stats"] = allstat outdata.append(resourcedata) return outdata # Disabling the warning sign for self signed certificates. Remove the below line for CA certificates requests.packages.urllib3.disable_warnings(InsecureRequestWarning) #pp = pprint.PrettyPrinter(indent=2) # Getting the absolute path from where the script is being run path = get_script_path() fullpath = path+"/"+"config.json" # Opening the config.json file to read the parameters from with open(fullpath) as data_file: data=json.load(data_file) # Reading the parameters from config.json file key = [] adapter = data["adapterKind"] resourceknd = data["resourceKind"] servername = data["server"]["name"] passwd = base64.b64decode(data["server"]["password"]) uid = data["server"]["userid"] sampleno = data["sampleno"] # Getting the list of Keys for which to collect metrics for i in data["keys"]: key.append(i) # connecting to the vROps server #print("Connecting to vROps") vrops = nagini.Nagini(host=servername, user_pass=(uid, passwd)) """ Getting Token vrops = nagini.Nagini(host=servername, user_pass=(uid, passwd) ) serverdata={} serverdata["username"] = uid serverdata["password"] = passwd serverdata["authSource"] = "Local Users" databack = vrops.acquire_token(serverdata) token = databack["token"] validity = databack["validity"] # Making further calls """ # Creating the output variables outstat = {} alldata = [] # Getting the metric data for all the resources which match the criteria alldata = get_metric_data(resourceknd,adapter,key,sampleno ) # Creating final parameters for output JSON file outstat["allstats"] = alldata # print ("Completed") outstat["timestamp"] = time.ctime() # Getting the path to the output json file outpath = path+"/"+"metric-data.json" # Writing the data to output JSON file with open(outpath, 'w') as outfile: json.dump(outstat, outfile, sort_keys = True, indent = 2, separators=(',', ':'), ensure_ascii=False)
sajaldebnath/vrops-metric-collection
metric-collection.py
Python
mit
4,525
from mapwidgets.widgets import GooglePointFieldWidget from miot.models import PointOfInterest, Page, Profile from django import forms class PointOfInterestForm(forms.ModelForm): '''The form for a point of interest.''' class Meta: model = PointOfInterest fields = ("name", "featured_image", "position", "tags", "active", "category") widgets = { 'position': GooglePointFieldWidget, } class PageForm(forms.ModelForm): '''The form for a page.''' class Meta: model = Page fields = ("title", "content", "template") class EstimoteAppForm(forms.ModelForm): '''The form for a profile update (estimote credentials).''' class Meta: model = Profile fields = ("estimote_app_id", "estimote_app_token")
Ishydo/miot
miot/forms.py
Python
mit
791
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def publish_transaction(channel, tr_type, payload): conf_db = get_conf_db() if tr_type not in ["insert", "delete"]: raise ValueError("Unknown transaction type", tr_type) subscribed = conf_db.scard("Subscriptions:%s:ActiveAnalytics" % channel) if subscribed == 0: raise NotFound(("Channel not found", "Channel '%(channel)s' is not found or has 0 " "subscriptions" % locals())) listened = conf_db.publish( channel, '{' ' "tr_type" : "' + tr_type + '", ' ' "payload" : ' + payload + '}' ) if listened != subscribed: raise ServiceUnavailable(( "Subscription-Listened mismatch", "Listened count = %d doesn't match Subscribed count = %d" % ( listened, subscribed ) ))
practo/r5d4
r5d4/publisher.py
Python
mit
1,023
import _plotly_utils.basevalidators class TicksuffixValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="ticksuffix", parent_name="densitymapbox.colorbar", **kwargs ): super(TicksuffixValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role", "style"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/densitymapbox/colorbar/_ticksuffix.py
Python
mit
485
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import sys import locale import warnings # to deal with the possibility of sys.std* not being a stream at all def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where ``sys.std*`` might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. ``default`` is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding # Less conservative replacement for sys.getdefaultencoding, that will try # to match the environment. # Defined here as central function, so if we find better choices, we # won't need to make changes all over IPython. def getdefaultencoding(prefer_stream=True): """Return IPython's guess for the default encoding for bytes as text. If prefer_stream is True (default), asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Then fall back on locale.getpreferredencoding(), which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII on Python 2 or UTF8 on Python 3. """ enc = None if prefer_stream: enc = get_stream_enc(sys.stdin) if not enc or enc == 'ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative # here. enc = locale.getpreferredencoding() except Exception: pass enc = enc or sys.getdefaultencoding() # On windows `cp0` can be returned to indicate that there is no code page. # Since cp0 is an invalid encoding return instead cp1252 which is the # Western European default. if enc == 'cp0': warnings.warn( "Invalid code page cp0 detected - using cp1252 instead." "If cp1252 is incorrect please ensure a valid code page " "is defined for the process.", RuntimeWarning) return 'cp1252' return enc DEFAULT_ENCODING = getdefaultencoding()
mattvonrocketstein/smash
smashlib/ipy3x/utils/encoding.py
Python
mit
2,881
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d array of aperture photometry radii phot -- 1d array of aperture photometry fluxes interp_kind -- kind of interpolation; passed to scipy.interpolate.interp1d. Some options are linear, quadratic, and cubic. add_zero -- add a 0 radius and zero flux point to their respective arrays to help with interpolation at small radii; should only matter for quadratic or cubic interpolation """ assert len(radii) == len(phot) assert np.all(radii > 0) assert np.all(phot > 0) if add_zero: radii = np.insert(radii, 0, 0) phot = np.insert(phot, 0, 0) eta_vals = eta(radii, phot) if np.any(eta_vals < 0.2): eta_interp = interp.interp1d(eta_vals, radii, kind=interp_kind) eta_r = eta_radius_factor * eta_interp(eta_radius) else: warnings.warn("eta is never less than " + str(eta_radius) + ". Using lowest eta value as proxy") eta_r = eta_radius_factor * radii[np.argmin(eta_vals)] phot_interp = interp.interp1d(radii, phot, kind=interp_kind) if eta_r < np.max(radii): maxphot = phot_interp(eta_r) else: maxphot = np.max(phot) norm_phot = phot / maxphot radius_interp = interp.interp1d(norm_phot, radii, kind=interp_kind) r20 = radius_interp(0.2) r80 = radius_interp(0.8) assert r20 < r80 < np.max(radii) c = 5 * np.log10(r80 / r20) return c def eta(radii, phot): """ eta = I(r) / \bar{I}(<r) radii -- 1d array of aperture photometry radii phot -- 1d array of aperture photometry fluxes this is currently calculated quite naively, and probably could be done better """ phot_area = np.pi * radii**2 phot_area_diff = np.ediff1d(phot_area, to_begin=phot_area[0]) I_bar = phot / (phot_area) I_delta_r = np.ediff1d(phot, to_begin=phot[0]) / phot_area_diff I_r = (I_delta_r[:-1] + I_delta_r[1:]) / 2 #lost last array element here I_r = np.append(I_r, I_delta_r[-1]) #added it back in here eta = I_r / I_bar return eta def find_eta(eta_val, radii, phot): eta_interp = interp.interp1d(eta(radii, phot), radii) return eta_interp(eta_val) def snr(name): """ name before fits and apphot files """ #first calculate the image uncertainty using the MAD hdulist = fits.open(name + '_bs.fits') im_med = np.median(hdulist[0].data) im_err = np.median(np.abs(hdulist[0].data - im_med)) #now get the total flux apphot = np.loadtxt(name + ".apphot", usecols=[0,1]) radii = apphot[:,0] phot = apphot[:,1] try: eta_rad = find_eta(0.2, radii, phot) if eta_rad > np.max(radii)/1.5: eta_rad = np.max(radii)/1.5 except ValueError: eta_rad = 1.0 phot_interp = interp.interp1d(radii, phot) total_phot = phot_interp(1.5*eta_rad) return total_phot / np.sqrt(np.pi*(1.5*eta_rad)**2 * im_err**2)
astronomeralex/morphology-software
morphology.py
Python
mit
3,255
# -*- coding: 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 field 'Project.url' db.add_column(u'core_project', 'url', self.gf('django.db.models.fields.TextField')(null=True), keep_default=False) def backwards(self, orm): # Deleting field 'Project.url' db.delete_column(u'core_project', 'url') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'badges.badge': { 'Meta': {'object_name': 'Badge'}, 'icon': ('django.db.models.fields.files.ImageField', [], {'default': "''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'badges.projectbadge': { 'Meta': {'object_name': 'ProjectBadge'}, 'awardLevel': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'badge': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['badges.Badge']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'description': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'multipleAwards': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Project']"}), 'tags': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '400', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'badges'", 'symmetrical': 'False', 'through': u"orm['badges.ProjectBadgeToUser']", 'to': u"orm['auth.User']"}) }, u'badges.projectbadgetouser': { 'Meta': {'object_name': 'ProjectBadgeToUser'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'projectbadge': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['badges.ProjectBadge']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'core.points': { 'Meta': {'object_name': 'Points'}, 'date_awarded': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'projectbadge': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['badges.ProjectBadge']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'value': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, u'core.project': { 'Meta': {'ordering': "('-created_at',)", 'object_name': 'Project'}, 'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'allowed_api_hosts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'background_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'project_closing_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'properties': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 'query_token': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'supervisors': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'supervisors'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['auth.User']"}), 'teams': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['core.Team']", 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'url': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'viewing_pass_phrase': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'visual_theme': ('django.db.models.fields.CharField', [], {'default': "'none'", 'max_length': '20'}) }, u'core.team': { 'Meta': {'ordering': "['-order', '-date_created', 'id']", 'object_name': 'Team'}, 'background_color': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}) }, u'core.userprofile': { 'Meta': {'object_name': 'UserProfile'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'score': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['core']
ngageoint/gamification-server
gamification/core/migrations/0007_auto__add_field_project_url.py
Python
mit
10,068
from django.contrib import admin from courses.models import Course, Instructor, Page, Enrollment class CourseAdmin(admin.ModelAdmin): list_display = ['title', 'instructor', 'language', 'popularity', 'is_public', 'deleted'] prepopulated_fields = { 'slug': ('title', ) } def queryset(self, request): qs = self.model.all_objects.get_query_set() # the following is needed from the superclass ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs class InstructorAdmin(admin.ModelAdmin): list_display = ['user', 'popularity'] class PageAdmin(admin.ModelAdmin): pass admin.site.register(Course, CourseAdmin) admin.site.register(Instructor, InstructorAdmin) admin.site.register(Page, PageAdmin) admin.site.register(Enrollment)
Uberlearner/uberlearner
uberlearner/courses/admin.py
Python
mit
848
"""JSON implementations of relationship searches.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification from . import objects from . import queries from .. import utilities from ..osid import searches as osid_searches from ..primitives import Id from ..utilities import get_registry from dlkit.abstract_osid.osid import errors from dlkit.abstract_osid.relationship import searches as abc_relationship_searches class RelationshipSearch(abc_relationship_searches.RelationshipSearch, osid_searches.OsidSearch): """The search interface for governing relationship searches.""" def __init__(self, runtime): self._namespace = 'relationship.Relationship' self._runtime = runtime record_type_data_sets = get_registry('RESOURCE_RECORD_TYPES', runtime) self._record_type_data_sets = record_type_data_sets self._all_supported_record_type_data_sets = record_type_data_sets self._all_supported_record_type_ids = [] self._id_list = None for data_set in record_type_data_sets: self._all_supported_record_type_ids.append(str(Id(**record_type_data_sets[data_set]))) osid_searches.OsidSearch.__init__(self, runtime) @utilities.arguments_not_none def search_among_relationships(self, relationship_ids): """Execute this search among the given list of relationships. arg: relationship_ids (osid.id.IdList): list of relationships raise: NullArgument - ``relationship_ids`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ self._id_list = relationship_ids @utilities.arguments_not_none def order_relationship_results(self, relationship_search_order): """Specify an ordering to the search results. arg: relationship_search_order (osid.relationship.RelationshipSearchOrder): relationship search order raise: NullArgument - ``relationship_search_order`` is ``null`` raise: Unsupported - ``relationship_search_order`` is not of this service *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() @utilities.arguments_not_none def get_relationship_search_record(self, relationship_search_record_type): """Gets the relationship search record corresponding to the given relationship search record ``Type``. This method is used to retrieve an object implementing the requested record. arg: relationship_search_record_type (osid.type.Type): a relationship search record type return: (osid.relationship.records.RelationshipSearchRecord) - the relationship search record raise: NullArgument - ``relationship_search_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(relationship_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() class RelationshipSearchResults(abc_relationship_searches.RelationshipSearchResults, osid_searches.OsidSearchResults): """This interface provides a means to capture results of a search.""" def __init__(self, results, query_terms, runtime): # if you don't iterate, then .count() on the cursor is an inaccurate representation of limit / skip # self._results = [r for r in results] self._namespace = 'relationship.Relationship' self._results = results self._query_terms = query_terms self._runtime = runtime self.retrieved = False def get_relationships(self): """Gets the relationship list resulting from a search. return: (osid.relationship.RelationshipList) - the relationship list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.IllegalState('List has already been retrieved.') self.retrieved = True return objects.RelationshipList(self._results, runtime=self._runtime) relationships = property(fget=get_relationships) def get_relationship_query_inspector(self): """Gets the inspector for the query to examine the terms used in the search. return: (osid.relationship.RelationshipQueryInspector) - the relationship query inspector *compliance: mandatory -- This method must be implemented.* """ return queries.RelationshipQueryInspector(self._query_terms, runtime=self._runtime) relationship_query_inspector = property(fget=get_relationship_query_inspector) @utilities.arguments_not_none def get_relationship_search_results_record(self, relationship_search_record_type): """Gets the relationship search results record corresponding to the given relationship search record ``Type``. This method must be used to retrieve an object implementing the requested record interface along with all of its ancestor interfaces. arg: relationship_search_record_type (osid.type.Type): a relationship search record type return: (osid.relationship.records.RelationshipSearchResultsReco rd) - the relationship search results record raise: NullArgument - ``relationship_search_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(relationship_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() class FamilySearch(abc_relationship_searches.FamilySearch, osid_searches.OsidSearch): """The search interface for governing family searches.""" def __init__(self, runtime): self._namespace = 'relationship.Family' self._runtime = runtime record_type_data_sets = get_registry('RESOURCE_RECORD_TYPES', runtime) self._record_type_data_sets = record_type_data_sets self._all_supported_record_type_data_sets = record_type_data_sets self._all_supported_record_type_ids = [] self._id_list = None for data_set in record_type_data_sets: self._all_supported_record_type_ids.append(str(Id(**record_type_data_sets[data_set]))) osid_searches.OsidSearch.__init__(self, runtime) @utilities.arguments_not_none def search_among_families(self, family_ids): """Execute this search among the given list of families. arg: family_ids (osid.id.IdList): list of families raise: NullArgument - ``family_ids`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ self._id_list = family_ids @utilities.arguments_not_none def order_family_results(self, family_search_order): """Specify an ordering to the search results. arg: family_search_order (osid.relationship.FamilySearchOrder): family search order raise: NullArgument - ``family_search_order`` is ``null`` raise: Unsupported - ``family_search_order`` is not of this service *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() @utilities.arguments_not_none def get_family_search_record(self, family_search_record_type): """Gets the family search record corresponding to the given family search record ``Type``. This method is used to retrieve an object implementing the requested record. arg: family_search_record_type (osid.type.Type): a family search record type return: (osid.relationship.records.FamilySearchRecord) - the family search record raise: NullArgument - ``family_search_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(family_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() class FamilySearchResults(abc_relationship_searches.FamilySearchResults, osid_searches.OsidSearchResults): """This interface provides a means to capture results of a search and is used as a vehicle to perform a search within a previous result set.""" def __init__(self, results, query_terms, runtime): # if you don't iterate, then .count() on the cursor is an inaccurate representation of limit / skip # self._results = [r for r in results] self._namespace = 'relationship.Family' self._results = results self._query_terms = query_terms self._runtime = runtime self.retrieved = False def get_families(self): """Gets the family list resulting from a search. return: (osid.relationship.FamilyList) - the family list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: raise errors.IllegalState('List has already been retrieved.') self.retrieved = True return objects.FamilyList(self._results, runtime=self._runtime) families = property(fget=get_families) def get_family_query_inspector(self): """Gets the inspector for the query to examine the terms used in the search. return: (osid.relationship.FamilyQueryInspector) - the family query inspector *compliance: mandatory -- This method must be implemented.* """ return queries.FamilyQueryInspector(self._query_terms, runtime=self._runtime) family_query_inspector = property(fget=get_family_query_inspector) @utilities.arguments_not_none def get_family_search_results_record(self, family_search_record_type): """Gets the family search results record corresponding to the given family search record Type. This method is used to retrieve an object implementing the requested record. arg: family_search_record_type (osid.type.Type): a family search record type return: (osid.relationship.records.FamilySearchResultsRecord) - the family search results record raise: NullArgument - ``FamilySearchRecordType`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(family_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented()
mitsei/dlkit
dlkit/json_/relationship/searches.py
Python
mit
11,651
from staffjoy.resource import Resource class ChompTask(Resource): PATH = "internal/tasking/chomp/{schedule_id}" ENVELOPE = None ID_NAME = "schedule_id"
Staffjoy/client_python
staffjoy/resources/chomp_task.py
Python
mit
166
from ctypes import Structure, c_int16, c_uint16 class Filter(Structure): """ Represents a Fixture filter """ _fields_ = [("categoryBits", c_uint16), ("maskBits", c_uint16), ("groupIndex", c_int16)] def __init__(self, categoryBits=0x1, maskBits=0xFFFF, groupIndex=0): """ Initialize the filter with the proper defaults """ Structure.__init__(self, categoryBits=categoryBits, maskBits=maskBits, groupIndex=groupIndex)
cloew/NytramBox2D
nytram_box2d/engine/filter.py
Python
mit
503
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)), ('name', models.CharField(max_length=255, verbose_name='Category Name')), ('description', models.TextField(null=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='PropertyName', fields=[ ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)), ('name', models.CharField(max_length=255, verbose_name='Property Name')), ('description', models.TextField(null=True)), ('category', models.ForeignKey(to='category.Category')), ], options={ }, bases=(models.Model,), ), ]
sorz/isi
store/category/migrations/0001_initial.py
Python
mit
1,172
# -*- encoding: utf-8 -*- __author__ = 'ray' __date__ = '2/27/15' from flask import jsonify, abort from flask.views import MethodView from ..models import ThemeModel class ThemeView(MethodView): """ Theme View Retrieve description of a list of available themes. :param theme_model: A theme model that manages themes. :type theme_model: :class:`~stonemason.service.models.ThemeModel` """ def __init__(self, theme_model): assert isinstance(theme_model, ThemeModel) self._theme_model = theme_model def get(self, tag): """Return description of the theme. Raise :http:statuscode:`404` if not found. :param name: Name of a theme. :type name: str """ if tag is None: collection = list() for theme in self._theme_model.iter_themes(): collection.append(theme.to_dict()) return jsonify(result=collection) else: theme = self._theme_model.get_theme(tag) if theme is None: abort(404) return jsonify(result=theme.to_dict())
Kotaimen/stonemason
stonemason/service/tileserver/themes/views.py
Python
mit
1,132