hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
795a2ecd36ec112ae3ea6735548db7655f19b1bd
35,167
py
Python
poptics/gui.py
will-hossack/Poptics
4093876e158eb16421dfd4e57818210b11381429
[ "MIT" ]
null
null
null
poptics/gui.py
will-hossack/Poptics
4093876e158eb16421dfd4e57818210b11381429
[ "MIT" ]
null
null
null
poptics/gui.py
will-hossack/Poptics
4093876e158eb16421dfd4e57818210b11381429
[ "MIT" ]
null
null
null
""" Set of gui classes and methods. Warning: these GUI do not work very smoothly with Spyder / IPython because the Spyder graphics window is a PyQT widget and there is some odd interactations, in particular when you close the main window it tend to hang the Sypder IPhthon console and you have to retart the Kernel. This is know problem on StackOverflow but there is no sensible soliution that actually works ! """ from importlib.resources import path import math from poptics.wavelength import getCurrentWavelength,setCurrentWavelength,\ getDesignWavelength,setDesignWavelength,getDefaultWavelength,\ BlueLimit,RedLimit from poptics.lens import setCurrentLens,getCurrentLens from poptics.wavefront import WaveFrontAnalysis,Interferometer from poptics.analysis import KnifeTest,SpotAnalysis from poptics.ray import RayPencil,RayPath,getCurrentAngle,setCurrentAngle from poptics.psf import getReferencePointOption,setReferencePointOption,\ getPlaneShift,setPlaneShift,incrementPlaneShift from poptics.vector import Unit3d # The PyQt5 bits from PyQt5.QtWidgets import QWidget,QLabel,QDoubleSpinBox,QPushButton,QGridLayout,\ QDial,QMessageBox,QMainWindow,QAction,QVBoxLayout,QFileDialog,QRadioButton from PyQt5.QtCore import Qt # The Matplot libs bit to render Matplotlib plots in a QT5 window. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt """ Globals to control the various plots, these are set by the various buttons """ PanelSize = (800,600) IrisRatio = 1.0 ZernikeOrder = 4 CurrentWaveFront = None Xtilt = 3.0 Ytilt = 0.0 CurrentKnife = 0.0 CurrentKnifeAngle = 0.0 CurrentKnifeShift = 0.0 CurrentWire = False def getGlobals(): return ZernikeOrder class WaveLengthSetter(QWidget): """ Class to set the Current and Design wavelengths with spinners. :param parent: the calling frame of widget :param closeAction: function to be executed when panel closed. """ def __init__(self, parent = None,closeAction = None): super(WaveLengthSetter,self).__init__(parent) self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) # The default wavelength spinner currentLabel = QLabel("Current : ") self.currentSpin = QDoubleSpinBox() # Default wave spinner self.currentSpin.setValue(getCurrentWavelength()) self.currentSpin.setSingleStep(0.01) self.currentSpin.setRange(BlueLimit,RedLimit) self.currentSpin.valueChanged.connect(self.currentValueChange) # The design wavelength spinner designLabel = QLabel("Design : ") self.designSpin = QDoubleSpinBox() # Design wave spinner self.designSpin.setValue(getDesignWavelength()) self.designSpin.setSingleStep(0.01) self.designSpin.setRange(BlueLimit,RedLimit) self.designSpin.valueChanged.connect(self.designValueChange) # The close and rest buttons closeButton = QPushButton("Close") # The close button closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) # Use Grid layout layout = QGridLayout() layout.addWidget(currentLabel,0,0) # Add the 6 item in Grid layout.addWidget(self.currentSpin,0,1) layout.addWidget(designLabel,1,0) layout.addWidget(self.designSpin,1,1) layout.addWidget(resetButton,2,0) layout.addWidget(closeButton,2,1) self.setLayout(layout) self.setWindowTitle("Wavelength Setter") # Method to update the values from the spinners, close and rest buttons def currentValueChange(self): v = self.currentSpin.value() setCurrentWavelength(v) def designValueChange(self): v = self.designSpin.value() setDesignWavelength(v) def resetButtonClicked(self): # Reset both wavelengths to Green c = getDefaultWavelength() self.currentSpin.setValue(c) self.designSpin.setValue(c) setCurrentWavelength(c) setDesignWavelength(c) def closeButtonClicked(self): # Close and execute close action if given self.close() if self.closeAction != None: self.closeAction() class DirectionSetter(QWidget): """ Class to set default direction in degress with spinners, note the actual direction is help as Unit3d. :param parent: the calling frame :param closeAction: function to execute on clsoing the window """ def __init__(self, parent = None,closeAction = None): super(DirectionSetter,self).__init__(parent) self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) # Set up the lables. thetaLabel = QLabel("Theta in degress :") # The labels psiLabel = QLabel("Psi in degrees : ") self.unitLabel = QLabel(str(getCurrentAngle())) # Label in Unit3d format self.theta,self.psi = getCurrentAngle().getAngle().getDegrees() # Current Theta/Psi self.thetaSpin = QDoubleSpinBox() # Theta spinner self.thetaSpin.setRange(-90.0,90.0) self.thetaSpin.setValue(self.theta) self.thetaSpin.setSingleStep(1.0) self.thetaSpin.valueChanged.connect(self.valueChange) self.psiSpin = QDoubleSpinBox() # Psi spinner self.psiSpin.setRange(-180.0,180.0) self.psiSpin.setValue(self.psi) self.psiSpin.setSingleStep(1.0) self.psiSpin.valueChanged.connect(self.valueChange) resetButton = QPushButton("Reset") # Reset and close buttons resetButton.clicked.connect(self.resetButtonClicked) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) layout = QGridLayout() # Set up layout as grid layout.addWidget(thetaLabel,0,0) layout.addWidget(self.thetaSpin,0,1) layout.addWidget(psiLabel,1,0) layout.addWidget(self.psiSpin,1,1) layout.addWidget(self.unitLabel,2,0,2,2) layout.addWidget(resetButton,3,0) layout.addWidget(closeButton,3,1) self.setLayout(layout) self.setWindowTitle("DirectionSetter") """ Method to update the values from the spinners and close the widow """ def valueChange(self): # For either spinned self.theta = self.thetaSpin.value() self.psi = self.psiSpin.value() u = Unit3d().setPolarDegrees(self.theta,self.psi) setCurrentAngle(u) self.unitLabel.setText(str(getCurrentAngle())) def resetButtonClicked(self): self.thetaSpin.setValue(0.0) self.psiSpin.setValue(0.0) self.valueChange() def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class IrisSetter(QWidget): """ Class to set default direction in degress with spinners """ def __init__(self, parent = None,closeAction = None): super(IrisSetter,self).__init__(parent) global IrisRatio self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) self.irisRatio = IrisRatio self.irisLabel = QLabel("Iris : " + str(self.irisRatio)) self.irisDial = QDial() self.irisDial.setRange(0,100) self.irisDial.setValue(int(100*self.irisRatio)) self.irisDial.valueChanged.connect(self.valueChange) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) layout = QGridLayout() layout.addWidget(self.irisLabel,0,1) layout.addWidget(self.irisDial,1,0,1,2) layout.addWidget(resetButton,2,0) layout.addWidget(closeButton,2,1) self.setLayout(layout) def valueChange(self): global IrisRatio self.irisRatio = self.irisDial.value()/100.0 self.irisLabel.setText("Iris : " + str(self.irisRatio)) IrisRatio = self.irisRatio getCurrentLens().setIris(self.irisRatio) def resetButtonClicked(self): self.iris = 1.0 self.irisDial.setValue(100) self.valueChange() def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class PlaneSetter(QWidget): """ Class for plane setter with dial, this update using setPlaneShift and incrementPlaneShift """ def __init__(self, scale = 0.01 , parent = None,closeAction = None,changedAction = None): super(PlaneSetter,self).__init__(parent) self.closeAction = closeAction self.changedAction = changedAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) self.shift = getPlaneShift() self.scale = scale self.planeLabel = QLabel("Plane : " + "{0:5.3f}".format(self.shift)) self.planeDial = QDial() self.planeDial.setRange(-100,100) self.planeDial.setValue(int(self.shift/self.scale)) self.planeDial.valueChanged.connect(self.valueChange) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) layout = QGridLayout() layout.addWidget(self.planeLabel,0,1) layout.addWidget(self.planeDial,1,0,1,2) layout.addWidget(resetButton,2,0) layout.addWidget(closeButton,2,1) self.setLayout(layout) def valueChange(self): global PlaneShift self.shift = self.planeDial.value()*self.scale self.planeLabel.setText("Plane : " + "{0:5.3f}".format(self.shift)) setPlaneShift(self.shift) if self.changedAction != None: self.changedAction() def resetButtonClicked(self): self.shift = 0.0 self.planeDial.setValue(0) self.valueChange() def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class LensSetter(QWidget): """ Class to set the current lens with a dialogue box. """ def __init__(self, parent = None,closeAction = None): super(LensSetter,self).__init__(parent) options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog # Use importlib resourses path to get path to lens directory with path("poptics","lenses") as p: # New code dir = p dir = str(dir) fileName, _ = QFileDialog.getOpenFileName(self,"Lens Files",dir,\ "Lens Files (*.lens)", options=options) if fileName: setCurrentLens(fileName) # Set the current lens. if closeAction != None: # Do any specified action closeAction() self.close() # Clase the frame class ZernikeOrderSetter(QWidget): """ Widget to set the Zernike Expansion order. """ def __init__(self, parent = None,closeAction = None): super(ZernikeOrderSetter,self).__init__(parent) global ZernikeOrder self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) self.zernikeFourButton = QRadioButton("Fourth") if ZernikeOrder == 4: self.zernikeFourButton.setChecked(True) self.zernikeFourButton.order = 4 self.zernikeFourButton.clicked.connect(lambda: self.buttonClicked(self.zernikeFourButton)) self.zernikeSixButton = QRadioButton("Sixth") if ZernikeOrder == 6: self.zernikeSixButton.setChecked(True) self.zernikeSixButton.order = 6 self.zernikeSixButton.clicked.connect(lambda: self.buttonClicked(self.zernikeSixButton)) self.zernikeEightButton = QRadioButton("Eighth") if ZernikeOrder == 8: self.zernikeEightButton.setChecked(True) self.zernikeEightButton.order = 8 self.zernikeEightButton.clicked.connect(lambda: self.buttonClicked(self.zernikeEightButton)) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) layout = QGridLayout() layout.addWidget(self.zernikeFourButton,0,0) layout.addWidget(self.zernikeSixButton,1,0) layout.addWidget(self.zernikeEightButton,2,0) layout.addWidget(resetButton,4,0) layout.addWidget(closeButton,4,1) self.setLayout(layout) self.setWindowTitle("Zernike Order") #self.setRadioButtons() # The action buttons def buttonClicked(self,button): global ZernikeOrder ZernikeOrder = button.order print("Order " + str(ZernikeOrder)) def resetButtonClicked(self): global ZernikeOrder ZernikeOrder = 4 self.zernikeFourButton.setChecked(True) def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class ReferenceOptionSetter(QWidget): """ Widget to set the reference option with Radio bottons. """ def __init__(self, parent = None,closeAction = None): super(ReferenceOptionSetter,self).__init__(parent) refopt = getReferencePointOption() self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) # Setup the the three option buttons self.paraxialButton = QRadioButton("Paraxial") if refopt == 0: self.paraxialButton.setChecked(True) self.paraxialButton.option = 0 self.paraxialButton.clicked.connect(lambda: self.buttonClicked(self.paraxialButton)) self.inplaneButton = QRadioButton("In plane") if refopt == 1: self.inplaneButton.setChecked(True) self.inplaneButton.option = 1 self.inplaneButton.clicked.connect(lambda: self.buttonClicked(self.inplaneButton)) self.optimalButton = QRadioButton("Optimal") if refopt == 2: self.optimalButton.setChecked(True) self.optimalButton.option = 2 self.optimalButton.clicked.connect(lambda: self.buttonClicked(self.optimalButton)) # Setup the stardard reset and close buttons. closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) # Set grid layout layout = QGridLayout() layout.addWidget(self.paraxialButton,0,0) layout.addWidget(self.inplaneButton,1,0) layout.addWidget(self.optimalButton,2,0) layout.addWidget(resetButton,4,0) layout.addWidget(closeButton,4,1) self.setLayout(layout) self.setWindowTitle("Reference Option") # The action buttons def buttonClicked(self,button): setReferencePointOption(button.option) def resetButtonClicked(self): setReferencePointOption(1) self.inplaneButton.setChecked(True) def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class TiltSetter(QWidget): """ Set the interferometer tilts """ def __init__(self, parent = None,closeAction = None): super(TiltSetter,self).__init__(parent) global Xtilt, Ytilt self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) xtiltLabel = QLabel("X tilt") self.xtiltSetter = QDoubleSpinBox() self.xtiltSetter.setValue(Xtilt) self.xtiltSetter.setSingleStep(0.1) self.xtiltSetter.valueChanged.connect(self.xtiltSetterClicked) ytiltLabel = QLabel("Y tilt") self.ytiltSetter = QDoubleSpinBox() self.ytiltSetter.setValue(Ytilt) self.ytiltSetter.setSingleStep(0.1) self.ytiltSetter.valueChanged.connect(self.ytiltSetterClicked) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) layout = QGridLayout() # Vertical box layout.addWidget(xtiltLabel,0,0) layout.addWidget(self.xtiltSetter,0,1) layout.addWidget(ytiltLabel,1,0) layout.addWidget(self.ytiltSetter,1,1) layout.addWidget(resetButton,2,0) layout.addWidget(closeButton,2,1) self.setLayout(layout) def xtiltSetterClicked(self): global Xtilt x = self.xtiltSetter.value() Xtilt = float(x) def ytiltSetterClicked(self): global Ytilt y = self.ytiltSetter.value() Ytilt = float(y) def resetButtonClicked(self): global Xtilt global Ytilt Xtilt = 3.0 self.xtiltSetter.setValue(Xtilt) Ytilt = 0.0 self.ytiltSetter.setValue(Ytilt) def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class KnifeSetter(QWidget): """ Widget to set the knife paramteers """ def __init__(self, parent = None,closeAction = None): super(KnifeSetter,self).__init__(parent) # global CurrentKnife, CurrentKnifeAngle,CurrentKnifeShift self.closeAction = closeAction self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) knifeLabel = QLabel("Knife Position") self.knifeSetter = QDoubleSpinBox() self.knifeSetter.setValue(CurrentKnife) self.knifeSetter.setSingleStep(0.01) self.knifeSetter.valueChanged.connect(self.knifeSetterClicked) angleLabel = QLabel("Knife Angle") self.knifeAngleSetter = QDoubleSpinBox() self.knifeAngleSetter.setValue(math.degrees(CurrentKnifeAngle)) self.knifeAngleSetter.setSingleStep(1.0) self.knifeAngleSetter.setRange(-90.0,90.0) self.knifeAngleSetter.valueChanged.connect(self.knifeAngleSetterClicked) shiftLabel = QLabel("Axial Shift") self.shiftSetter = QDoubleSpinBox() self.shiftSetter.setSingleStep(0.1) self.shiftSetter.setRange(-20.0,20.0) self.shiftSetter.setValue(CurrentKnifeShift) self.shiftSetter.valueChanged.connect(self.shiftSetterClicked) self.wireSetter = QRadioButton("Wire") self.wireSetter.clicked.connect(self.wireSetterClicked) self.wireSetter.setChecked(CurrentWire) closeButton = QPushButton("Close") closeButton.clicked.connect(self.closeButtonClicked) resetButton = QPushButton("Reset") resetButton.clicked.connect(self.resetButtonClicked) layout = QGridLayout() # Vertical box layout.addWidget(knifeLabel,0,0) layout.addWidget(self.knifeSetter,0,1) layout.addWidget(angleLabel,1,0) layout.addWidget(self.knifeAngleSetter,1,1) layout.addWidget(shiftLabel,2,0) layout.addWidget(self.shiftSetter,2,1) layout.addWidget(self.wireSetter,3,0) layout.addWidget(resetButton,4,0) layout.addWidget(closeButton,4,1) self.setLayout(layout) # Fun to set the buttons # def knifeSetterClicked(self): global CurrentKnife v = self.knifeSetter.value() CurrentKnife = float(v) def knifeAngleSetterClicked(self): global CurrentKnifeAngle v = self.knifeAngleSetter.value() CurrentKnifeAngle = math.radians(v) def shiftSetterClicked(self): global CurrentKnifeShift v = self.shiftSetter.value() CurrentKnifeShift = float(v) def wireSetterClicked(self): global CurrentWire CurrentWire = not CurrentWire self.wireSetter.setChecked(CurrentWire) def resetButtonClicked(self): global CurrentKnife global CurrentKnifeAngle global CurrenntKnifeShift CurrentKnife = 0.0 self.knifeSetter.setValue(CurrentKnife) CurrentKnifeAngle = 0.0 self.knifeAngleSetter.setValue(CurrentKnifeAngle) CurrentKnifeShift = 0.0 self.shiftSetter.setValue(CurrentKnifeShift) def closeButtonClicked(self): # Close the frame self.close() if self.closeAction != None: self.closeAction() class MessageBox(QMessageBox): """ Class to display messages """ def __init__(self, itext = "None",dtext = "None", parent = None): super(MessageBox,self).__init__(parent) self.setIcon(QMessageBox.Information) self.setText(getCurrentLens().title) self.setInformativeText(itext) self.setWindowTitle("Message") self.setDetailedText(dtext) self.setStandardButtons(QMessageBox.Ok ) class PltMainWindow(QMainWindow): """ Class to set up a main window with the central pane being a Matplotlib pane :param lens: The lens to be shown or manipulated. (Default = None) :type lens: OpticalGroiup or extending class :param parent: the parent window if there is ine (Default = None) """ def __init__(self, lens = None, parent = None): super(PltMainWindow, self).__init__(parent) # Set size of panel self.resize(PanelSize[0],PanelSize[1]) # If lens given then set current lens, if not use default lens. if lens != None: setCurrentLens(lens) # Setup components for plt window self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) toolbar = NavigationToolbar(self.canvas, self) self.menubar = self.menuBar() self.menubar.setNativeMenuBar(False) # Set up basic menu items fileMenu = self.menubar.addMenu("File") fileAction = QAction("New Lens",self) fileAction.triggered.connect(self.fileButtonClicked) fileMenu.addAction(fileAction) plotAction = QAction("Replot",self) plotAction.triggered.connect(self.plot) fileMenu.addAction(plotAction) lensAction = QAction("Show Lens",self) lensAction.triggered.connect(self.lensPlot) fileMenu.addAction(lensAction) infoAction = QAction("Lens Info",self) infoAction.triggered.connect(self.infoButtonClicked) fileMenu.addAction(infoAction) exitAction = QAction("Exit",self) exitAction.triggered.connect(self.exitButtonClicked) fileMenu.addAction(exitAction) # Setup central panel layout = QVBoxLayout() layout.addWidget(toolbar) layout.addWidget(self.canvas) panel = QWidget() panel.setLayout(layout) self.setCentralWidget(panel) # Setup basic options menu (common to all intrefaces) optionMenu = self.menubar.addMenu("Options") waveAction = QAction("Wavelength",self) waveAction.triggered.connect(self.waveButtonClicked) optionMenu.addAction(waveAction) angleAction = QAction("Angle",self) optionMenu.addAction(angleAction) angleAction.triggered.connect(self.angleButtonClicked) irisAction = QAction("Iris",self) optionMenu.addAction(irisAction) irisAction.triggered.connect(self.irisButtonClicked) referenceAction = QAction("Reference Point",self) referenceAction.triggered.connect(self.referenceButtonClicked) optionMenu.addAction(referenceAction) # Do a default plot of the lens if one exits if getCurrentLens() == None: self.fileButtonClicked() else: self.lensPlot() # The basic buttons def exitButtonClicked(self): """ Exit buttom """ # sys.exit() self.close() def fileButtonClicked(self): """ New File button. """ fs = LensSetter(parent=self,closeAction=self.lensPlot) def infoButtonClicked(self): """ Lens Information button. """ m = MessageBox("Lens Information",getCurrentLens().getInfo(),parent = self) m.setWindowTitle("Information") m.show() def waveButtonClicked(self): """ Wavelength setter clicked """ ws = WaveLengthSetter(parent=self,closeAction=self.plot) ws.move(50,50) ws.resize(200,100) ws.show() def angleButtonClicked(self): """ Ray angle button """ aset = DirectionSetter(parent=self,closeAction=self.plot) aset.move(50,50) aset.resize(300,150) aset.show() def irisButtonClicked(self): """ Iris setter button """ ir = IrisSetter(parent=self,closeAction=self.plot) ir.move(50,50) ir.resize(200,200) ir.show() def referenceButtonClicked(self): """ Reference setter """ w = ReferenceOptionSetter(parent=self,closeAction=self.plot) w.move(50,50) w.resize(200,200) w.show() # The plot method def plot(self): """ Method to plot the actual image """ self.figure.clear() # Clear current figure # Use a subPlot() method to do the actual work self.subPlot() #refresh the canvas self.canvas.draw() def lensPlot(self): """ The default lens plot """ self.figure.clear() # Clear current figure panel = self.figure.add_subplot(111) panel.axis('equal') # plot data getCurrentLens().draw(planes = False) plt.grid() plt.xlabel("Optical Axis") plt.ylabel("Height") plt.title("Diagram of lens " + getCurrentLens().title) self.canvas.draw() class LensViewer(PltMainWindow): """ Class to plot a lens the panel with a collimated beam of rays. :param lens: the lens to plot (Default = None) :type lens: OpticalGroup or extending class. :param parent: Parent window if there is one (Default = None) """ def __init__(self, lens = None , parent=None): super(LensViewer, self).__init__(lens,parent) if getCurrentLens() != None: self.plot() def subPlot(self): """ Method to do the actual plot, automatically called """ panel = self.figure.add_subplot(111) panel.axis('equal') u = getCurrentAngle() pencil = RayPencil().addBeam(getCurrentLens(),u,"vl",\ wavelength=getCurrentWavelength()).addMonitor(RayPath()) # # Set the output plane (being the back focal plane) op = getCurrentLens().backFocalPlane() # Propagate pencil through lens and one to back plane pencil *= getCurrentLens() # Through lens pencil *= op # To plane # plot data getCurrentLens().draw(True,True) op.draw() pencil.draw() plt.grid() plt.xlabel("Optical Axis") plt.ylabel("Height") plt.title("Diagram of lens " + getCurrentLens().title) class AbberationViewer(PltMainWindow): """ Class to plot the three aberration plots for a lens at choice of angles and wavelength :param lens: the lens to plot (Default = None) :type lens: OpticalGroup or extending class. :param parent: Parent window if there is one (Default = None) """ def __init__(self, lens = None , parent=None): super(AbberationViewer, self).__init__(lens,parent) if getCurrentLens() != None: self.plot() def subPlot(self): """ Method to do the actual plot (called automatically """ wa = WaveFrontAnalysis(getCurrentLens(),getDesignWavelength()) wa.drawAberrationPlot(getCurrentAngle(),getCurrentWavelength()) class WaveFrontViewer(PltMainWindow): """ Class to plot a lens the panel with rays """ def __init__(self, lens = None , parent=None): super(WaveFrontViewer, self).__init__(lens,parent) waveMenu = self.menubar.addMenu("Wave") orderAction = QAction("Zerkike Order",self) orderAction.triggered.connect(self.orderButtonClicked) waveMenu.addAction(orderAction) zernikeInfoAction = QAction("Zernike Details",self) zernikeInfoAction.triggered.connect(self.zernikeButtonClicked) waveMenu.addAction(zernikeInfoAction) tiltAction = QAction("Tilts",self) tiltAction.triggered.connect(self.tiltButtonClicked) waveMenu.addAction(tiltAction) self.interferometer = Interferometer() def subPlot(self): global CurrentWaveFront wa = WaveFrontAnalysis(getCurrentLens(),getDesignWavelength()) CurrentWaveFront = wa.fitZernike(getCurrentAngle(),getDefaultWavelength(),ZernikeOrder,\ getReferencePointOption()) self.interferometer.setWaveFront(CurrentWaveFront) self.displayPlot() def displayPlot(self): self.interferometer.setTilt(Xtilt,Ytilt) self.interferometer.draw() # Wave button aclions def orderButtonClicked(self): """ Wavelength setter """ zs = ZernikeOrderSetter(parent=self,closeAction=self.plot) zs.move(50,50) zs.resize(200,100) zs.show() def tiltButtonClicked(self): """ The tilt button """ tb = TiltSetter(parent=self,closeAction=self.plot) tb.move(50,50) tb.resize(200,100) tb.show() def zernikeButtonClicked(self): m = MessageBox("Zernike Expansion w: {0:4.2f}".format(getDefaultWavelength()),repr(CurrentWaveFront),parent = self) m.setWindowTitle("Information") m.show() class OTFViewer(WaveFrontViewer): """ Class extending WaveFrontViewer to display OFT """ def __init__(self,lens = None, parent = None): super(OTFViewer,self).__init__(lens,parent) def displayPlot(self): CurrentWaveFront.plotOTF(128,"b") class KnifeViewer(PltMainWindow): """ Class to plot a lens the panel with rays """ def __init__(self, lens = None , parent=None): super(KnifeViewer, self).__init__(lens,parent) knifeMenu = self.menubar.addMenu("Knife") knifeAction = QAction("Knife Parameters",self) knifeAction.triggered.connect(self.knifeButtonClicked) knifeMenu.addAction(knifeAction) def subPlot(self): kt = KnifeTest(getCurrentLens(),getCurrentAngle(),getCurrentWavelength(),getDesignWavelength()) # New knife test kt.setKnife(CurrentKnife,CurrentKnifeAngle,CurrentKnifeShift) # Set knife kt.setWire(CurrentWire) kt.setReference(getReferencePointOption()) kt.getImage().draw() # make and plot image plt.title(getCurrentLens().title) # Additional buttons in menue def knifeButtonClicked(self): w = KnifeSetter(parent = self, closeAction = self.plot) w.move(50,50) w.resize(200,200) w.show() class SpotViewer(PltMainWindow): """ Class to plot spot diagrams of a lens with a collimnated beam with options to change angle, wavelength and plane of the spots. :param lens: the lens to plot (Default = None) :type lens: OpticalGroup or extending class. :param parent: Parent window if there is one (Default = None) """ def __init__(self, lens = None , parent=None): super(SpotViewer, self).__init__(lens,parent) self.delta = 0.1 # Make the additioal menu to control the position of the stop plane spotMenu = self.menubar.addMenu("Plane") plusAction = QAction("Plus",self) minusAction = QAction("Minus",self) controlAction = QAction("Variable",self) plusAction.triggered.connect(self.plusClicked) minusAction.triggered.connect(self.minusClicked) controlAction.triggered.connect(self.variableClicked) spotMenu.addAction(plusAction) spotMenu.addAction(minusAction) spotMenu.addAction(controlAction) def plusClicked(self): """ Move plane forward along optical axis """ incrementPlaneShift(self.delta) self.updatePlane() def minusClicked(self): """ Move the plane back along the optical axis """ incrementPlaneShift(-self.delta) self.updatePlane() def variableClicked(self): """ Update the plane position with the dial """ p = PlaneSetter(scale = 0.01, parent = self , closeAction = None , changedAction = self.updatePlane) p.move(50,50) p.resize(200,200) p.show() def subPlot(self): """ Method to set up the spot analysis, and trace the rays. This need to be called if any of the geometry of the sytsem changes. """ # Make a new SpotAnalysis object (which will trace the rays) self.spot = SpotAnalysis(getCurrentLens(),getCurrentAngle(),getReferencePointOption(),\ getCurrentWavelength(),getDesignWavelength()) self.updatePlane() def updatePlane(self): """ Method to update the position of the spot plane only. ((rays are not retraced)) """ self.figure.clear() self.spot.draw(getPlaneShift()) # Update plot pos = self.spot.plane.getPoint().z # Get poistion of plane plt.title(getCurrentLens().title) plt.xlabel("Shift : {0:5.4f} Plane at : {1:7.4f}".format(getPlaneShift(),pos)) self.canvas.draw()
32.927903
124
0.647425
795a2ee06136642c9c340a5300a363fc170f44d8
1,367
py
Python
snorkel/parser/corpus_parser.py
silencehero/snorkel
afe2563a91e3d292d1a1d8a1ca6a2d39e8cd09c2
[ "Apache-2.0" ]
2
2019-01-08T02:30:35.000Z
2019-03-13T07:00:34.000Z
snorkel/parser/corpus_parser.py
silencehero/snorkel
afe2563a91e3d292d1a1d8a1ca6a2d39e8cd09c2
[ "Apache-2.0" ]
null
null
null
snorkel/parser/corpus_parser.py
silencehero/snorkel
afe2563a91e3d292d1a1d8a1ca6a2d39e8cd09c2
[ "Apache-2.0" ]
2
2018-12-01T17:10:01.000Z
2018-12-28T09:16:41.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * from .corenlp import StanfordCoreNLPServer from ..models import Candidate, Context, Sentence from ..udf import UDF, UDFRunner class CorpusParser(UDFRunner): def __init__(self, parser=None, fn=None): self.parser = parser or StanfordCoreNLPServer() super(CorpusParser, self).__init__(CorpusParserUDF, parser=self.parser, fn=fn) def clear(self, session, **kwargs): session.query(Context).delete() # We cannot cascade up from child contexts to parent Candidates, # so we delete all Candidates too session.query(Candidate).delete() class CorpusParserUDF(UDF): def __init__(self, parser, fn, **kwargs): super(CorpusParserUDF, self).__init__(**kwargs) self.parser = parser self.req_handler = parser.connect() self.fn = fn def apply(self, x, **kwargs): """Given a Document object and its raw text, parse into Sentences""" doc, text = x for parts in self.req_handler.parse(doc, text): parts = self.fn(parts) if self.fn is not None else parts yield Sentence(**parts)
34.175
76
0.648135
795a2fa28fc683d242f84a51c4820ef0ee430244
4,965
py
Python
climate.py
partikus/tech-controllers
eadbc6892751e1e63f4bef5990ba72b63b294aa6
[ "MIT" ]
null
null
null
climate.py
partikus/tech-controllers
eadbc6892751e1e63f4bef5990ba72b63b294aa6
[ "MIT" ]
null
null
null
climate.py
partikus/tech-controllers
eadbc6892751e1e63f4bef5990ba72b63b294aa6
[ "MIT" ]
null
null
null
"""Support for Tech HVAC system.""" import logging import json from typing import List, Optional from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, CURRENT_HVAC_HEAT, CURRENT_HVAC_COOL, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from .const import DOMAIN logging.basicConfig(level=logging.DEBUG) _LOGGER = logging.getLogger(__name__) SUPPORT_HVAC = [HVAC_MODE_HEAT, HVAC_MODE_OFF] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up entry.""" _LOGGER.debug("Setting up entry, module udid: " + config_entry.data["udid"]) api = hass.data[DOMAIN][config_entry.entry_id] zones = await api.get_module_zones(config_entry.data["udid"]) async_add_entities( [ TechThermostat( zones[zone], api, config_entry, ) for zone in zones ], True, ) class TechThermostat(ClimateEntity): """Representation of a Tech climate.""" def __init__(self, device, api, config_entry): """Initialize the Tech device.""" _LOGGER.debug("Init TechThermostat...") self._config_entry = config_entry self._api = api self._id = device["zone"]["id"] self.update_properties(device) def update_properties(self, device): self._name = device["description"]["name"] if device["zone"]["setTemperature"] is not None: self._target_temperature = device["zone"]["setTemperature"] / 10 else: self._target_temperature = None if device["zone"]["currentTemperature"] is not None: self._temperature = device["zone"]["currentTemperature"] / 10 else: self._temperature = None state = device["zone"]["flags"]["relayState"] if state == "on": self._state = CURRENT_HVAC_HEAT elif state == "off": self._state = CURRENT_HVAC_IDLE else: self._state = CURRENT_HVAC_OFF mode = device["zone"]["zoneState"] if mode == "zoneOn" or mode == "noAlarm": self._mode = HVAC_MODE_HEAT else: self._mode = HVAC_MODE_OFF @property def unique_id(self) -> str: """Return a unique ID.""" return self._id @property def name(self): """Return the name of the device.""" return self._name @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE #| SUPPORT_PRESET_MODE @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ return self._mode @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC @property def hvac_action(self) -> Optional[str]: """Return the current running hvac operation if supported. Need to be one of CURRENT_HVAC_*. """ return self._state async def async_update(self): """Call by the Tech device callback to update state.""" _LOGGER.debug("Updating Tech zone: %s, udid: %s, id: %s", self._name, self._config_entry.data["udid"], self._id) device = await self._api.get_zone(self._config_entry.data["udid"], self._id) self.update_properties(device) @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def current_temperature(self): """Return the current temperature.""" return self._temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature async def async_set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature: _LOGGER.debug("%s: Setting temperature to %s", self._name, temperature) self._temperature = temperature await self._api.set_const_temp(self._config_entry.data["udid"], self._id, temperature) async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" _LOGGER.debug("%s: Setting hvac mode to %s", self._name, hvac_mode) if hvac_mode == HVAC_MODE_OFF: await self._api.set_zone(self._config_entry.data["udid"], self._id, False) elif hvac_mode == HVAC_MODE_HEAT: await self._api.set_zone(self._config_entry.data["udid"], self._id, True)
32.032258
120
0.633031
795a309613d3d8afdcf46f0c02f746711c589b4c
2,134
py
Python
callback.py
wtma/TripleNet
1ae35ff3c8ebab8ec85e86adb2526aa509628e94
[ "Apache-2.0" ]
27
2019-10-26T08:17:31.000Z
2021-07-12T07:54:01.000Z
callback.py
wtma/TripleNet
1ae35ff3c8ebab8ec85e86adb2526aa509628e94
[ "Apache-2.0" ]
3
2019-10-21T13:42:31.000Z
2020-05-19T16:05:28.000Z
callback.py
chatopera/triplenet
3051d4b707e964e18dd909f89c40c0e703f26683
[ "Apache-2.0" ]
6
2019-11-27T15:09:17.000Z
2021-04-15T12:43:10.000Z
from keras.callbacks import ModelCheckpoint from keras.callbacks import Callback from evaluate import evaluate_ubuntu, evaluate_douban import codecs import json import os class SaveModelCallback(Callback): def __init__(self, args, single_model): """ :param single_model: keras can only save single gpu model, not parallel model """ super().__init__() self.epoch_counter = 0 self.batch_counter = 0 self.seed = 0 self.single_model = single_model self.config = args def on_epoch_begin(self, epoch, logs={}): if self.epoch_counter == 0: # we save config file at first epoch with codecs.open(os.path.join(self.config.output_dir, 'config.json'), 'w', encoding='utf-8') as f: json.dump(self.config.__dict__, f) if self.config.task == 'ubuntu': result = evaluate_ubuntu(self.config, self.single_model) else: result = evaluate_douban(self.config, self.single_model) self.single_model.save_weights( self.config.output_dir + 'model_epoch' + str(self.epoch_counter) + '_prec' + str(result) + '.hdf5', overwrite=True ) self.epoch_counter += 1 def on_batch_begin(self, batch, logs={}): self.batch_counter += 1 if self.config.task == 'ubuntu' and self.batch_counter % 3125 == 0 and self.epoch_counter >= 3: # we will eval per 3125 steps result = evaluate_ubuntu(self.config, self.single_model) self.single_model.save_weights( self.config.output_dir + 'model_epoch' + str(self.epoch_counter) + '_prec' + str(result) + '.hdf5', overwrite=True) if self.config.task == 'douban' and self.batch_counter % 2000 == 0: result = evaluate_douban(self.config, self.single_model) self.single_model.save_weights( self.config.output_dir + 'model_epoch' + str(self.epoch_counter) + '_prec' + str(result) + '.hdf5', overwrite=True)
41.843137
103
0.606842
795a30df006d482b157e92931a25722838708355
905
py
Python
episode_8/ian.py
ChucklesJM/Three-Hundred-Lines
9c0d59eeeffcb5565175fe24d95952fb1b34ffa1
[ "MIT" ]
1
2020-08-16T05:04:41.000Z
2020-08-16T05:04:41.000Z
episode_8/ian.py
jackmitcheltree/Three-Hundred-Lines
9c0d59eeeffcb5565175fe24d95952fb1b34ffa1
[ "MIT" ]
null
null
null
episode_8/ian.py
jackmitcheltree/Three-Hundred-Lines
9c0d59eeeffcb5565175fe24d95952fb1b34ffa1
[ "MIT" ]
1
2020-08-16T05:05:28.000Z
2020-08-16T05:05:28.000Z
import time start = time.time() # #- #~ Find the value of n <= m for which n/phi(n) is maximimized ~# def sieve_of_Eratosthenes(n): # returns list of primes less than n A = [True]*n for i in range(2,int(n**(0.5))+1): if A[i] == True: j = i**2 while j < n: A[j] = False j += i return [i for i in range(len(A)) if A[i] == True][2:] def max_calc(m): primes = sieve_of_Eratosthenes(m) n = 1 while True: _n = 1 for i in primes[0:n]: _n *= i _n_1 = 1 for i in primes[0:(n+1)]: _n_1 *= i if (_n <= m) and (_n_1 > m): print(f'Ans = {_n}') break else: n += 1 max_calc(m:=1000000) #- # end = time.time() print(end-start)
21.547619
66
0.41105
795a31a770943d7cd4a032200b47019d26633134
39,293
py
Python
sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2018_01_01_preview/aio/operations/_event_hubs_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2018_01_01_preview/aio/operations/_event_hubs_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
4
2019-04-17T17:57:49.000Z
2020-04-24T21:11:22.000Z
sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2018_01_01_preview/aio/operations/_event_hubs_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
1
2019-04-05T18:17:43.000Z
2019-04-05T18:17:43.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class EventHubsOperations: """EventHubsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.eventhub.v2018_01_01_preview.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_authorization_rules( self, resource_group_name: str, namespace_name: str, event_hub_name: str, **kwargs ) -> AsyncIterable["models.AuthorizationRuleListResult"]: """Gets the authorization rules for an Event Hub. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AuthorizationRuleListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.eventhub.v2018_01_01_preview.models.AuthorizationRuleListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.AuthorizationRuleListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_authorization_rules.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('AuthorizationRuleListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_authorization_rules.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules'} # type: ignore async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, event_hub_name: str, authorization_rule_name: str, parameters: "models.AuthorizationRule", **kwargs ) -> "models.AuthorizationRule": """Creates or updates an AuthorizationRule for the specified Event Hub. Creation/update of the AuthorizationRule will take a few seconds to take effect. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param authorization_rule_name: The authorization rule name. :type authorization_rule_name: str :param parameters: The shared access AuthorizationRule. :type parameters: ~azure.mgmt.eventhub.v2018_01_01_preview.models.AuthorizationRule :keyword callable cls: A custom type or function that will be passed the direct response :return: AuthorizationRule, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.AuthorizationRule :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.AuthorizationRule"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update_authorization_rule.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), 'authorizationRuleName': self._serialize.url("authorization_rule_name", authorization_rule_name, 'str', min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'AuthorizationRule') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AuthorizationRule', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}'} # type: ignore async def get_authorization_rule( self, resource_group_name: str, namespace_name: str, event_hub_name: str, authorization_rule_name: str, **kwargs ) -> "models.AuthorizationRule": """Gets an AuthorizationRule for an Event Hub by rule name. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param authorization_rule_name: The authorization rule name. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AuthorizationRule, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.AuthorizationRule :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.AuthorizationRule"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" # Construct URL url = self.get_authorization_rule.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), 'authorizationRuleName': self._serialize.url("authorization_rule_name", authorization_rule_name, 'str', min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AuthorizationRule', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}'} # type: ignore async def delete_authorization_rule( self, resource_group_name: str, namespace_name: str, event_hub_name: str, authorization_rule_name: str, **kwargs ) -> None: """Deletes an Event Hub AuthorizationRule. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param authorization_rule_name: The authorization rule name. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" # Construct URL url = self.delete_authorization_rule.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), 'authorizationRuleName': self._serialize.url("authorization_rule_name", authorization_rule_name, 'str', min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}'} # type: ignore async def list_keys( self, resource_group_name: str, namespace_name: str, event_hub_name: str, authorization_rule_name: str, **kwargs ) -> "models.AccessKeys": """Gets the ACS and SAS connection strings for the Event Hub. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param authorization_rule_name: The authorization rule name. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: AccessKeys, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.AccessKeys :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.AccessKeys"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" # Construct URL url = self.list_keys.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), 'authorizationRuleName': self._serialize.url("authorization_rule_name", authorization_rule_name, 'str', min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AccessKeys', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}/listKeys'} # type: ignore async def regenerate_keys( self, resource_group_name: str, namespace_name: str, event_hub_name: str, authorization_rule_name: str, parameters: "models.RegenerateAccessKeyParameters", **kwargs ) -> "models.AccessKeys": """Regenerates the ACS and SAS connection strings for the Event Hub. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param authorization_rule_name: The authorization rule name. :type authorization_rule_name: str :param parameters: Parameters supplied to regenerate the AuthorizationRule Keys (PrimaryKey/SecondaryKey). :type parameters: ~azure.mgmt.eventhub.v2018_01_01_preview.models.RegenerateAccessKeyParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: AccessKeys, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.AccessKeys :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.AccessKeys"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.regenerate_keys.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), 'authorizationRuleName': self._serialize.url("authorization_rule_name", authorization_rule_name, 'str', min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'RegenerateAccessKeyParameters') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('AccessKeys', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}/regenerateKeys'} # type: ignore def list_by_namespace( self, resource_group_name: str, namespace_name: str, skip: Optional[int] = None, top: Optional[int] = None, **kwargs ) -> AsyncIterable["models.EventHubListResult"]: """Gets all the Event Hubs in a Namespace. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param skip: Skip is only used if a previous operation returned a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skip parameter that specifies a starting point to use for subsequent calls. :type skip: int :param top: May be used to limit the number of results to the most recent N usageDetails. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventHubListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.eventhub.v2018_01_01_preview.models.EventHubListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.EventHubListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_namespace.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if skip is not None: query_parameters['$skip'] = self._serialize.query("skip", skip, 'int', maximum=1000, minimum=0) if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=1000, minimum=1) request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('EventHubListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_namespace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs'} # type: ignore async def create_or_update( self, resource_group_name: str, namespace_name: str, event_hub_name: str, parameters: "models.Eventhub", **kwargs ) -> "models.Eventhub": """Creates or updates a new Event Hub as a nested resource within a Namespace. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :param parameters: Parameters supplied to create an Event Hub resource. :type parameters: ~azure.mgmt.eventhub.v2018_01_01_preview.models.Eventhub :keyword callable cls: A custom type or function that will be passed the direct response :return: Eventhub, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.Eventhub :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Eventhub"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'Eventhub') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Eventhub', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}'} # type: ignore async def delete( self, resource_group_name: str, namespace_name: str, event_hub_name: str, **kwargs ) -> None: """Deletes an Event Hub from the specified Namespace and resource group. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}'} # type: ignore async def get( self, resource_group_name: str, namespace_name: str, event_hub_name: str, **kwargs ) -> "models.Eventhub": """Gets an Event Hubs description for the specified Event Hub. :param resource_group_name: Name of the resource group within the azure subscription. :type resource_group_name: str :param namespace_name: The Namespace name. :type namespace_name: str :param event_hub_name: The Event Hub name. :type event_hub_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Eventhub, or the result of cls(response) :rtype: ~azure.mgmt.eventhub.v2018_01_01_preview.models.Eventhub :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Eventhub"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-04-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), 'namespaceName': self._serialize.url("namespace_name", namespace_name, 'str', max_length=50, min_length=6), 'eventHubName': self._serialize.url("event_hub_name", event_hub_name, 'str', max_length=256, min_length=1), '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('Eventhub', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}'} # type: ignore
52.181939
268
0.677347
795a31fb56501a00d9138af144a1fa07b5151b8a
4,036
py
Python
sdk/python/pulumi_vsphere/get_tag_category.py
pulumi/pulumi-vsphere
a4536cd49860323bd57cbf2a127c5b57c9f9b60c
[ "ECL-2.0", "Apache-2.0" ]
38
2018-09-17T18:56:29.000Z
2022-03-26T03:07:20.000Z
sdk/python/pulumi_vsphere/get_tag_category.py
pulumi/pulumi-vsphere
a4536cd49860323bd57cbf2a127c5b57c9f9b60c
[ "ECL-2.0", "Apache-2.0" ]
75
2018-09-17T13:18:24.000Z
2022-03-31T21:32:30.000Z
sdk/python/pulumi_vsphere/get_tag_category.py
pulumi/pulumi-vsphere
a4536cd49860323bd57cbf2a127c5b57c9f9b60c
[ "ECL-2.0", "Apache-2.0" ]
2
2019-10-05T10:30:01.000Z
2020-09-30T11:16:59.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = [ 'GetTagCategoryResult', 'AwaitableGetTagCategoryResult', 'get_tag_category', ] @pulumi.output_type class GetTagCategoryResult: """ A collection of values returned by getTagCategory. """ def __init__(__self__, associable_types=None, cardinality=None, description=None, id=None, name=None): if associable_types and not isinstance(associable_types, list): raise TypeError("Expected argument 'associable_types' to be a list") pulumi.set(__self__, "associable_types", associable_types) if cardinality and not isinstance(cardinality, str): raise TypeError("Expected argument 'cardinality' to be a str") pulumi.set(__self__, "cardinality", cardinality) if description and not isinstance(description, str): raise TypeError("Expected argument 'description' to be a str") pulumi.set(__self__, "description", description) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) @property @pulumi.getter(name="associableTypes") def associable_types(self) -> Sequence[str]: return pulumi.get(self, "associable_types") @property @pulumi.getter def cardinality(self) -> str: return pulumi.get(self, "cardinality") @property @pulumi.getter def description(self) -> str: return pulumi.get(self, "description") @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") class AwaitableGetTagCategoryResult(GetTagCategoryResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetTagCategoryResult( associable_types=self.associable_types, cardinality=self.cardinality, description=self.description, id=self.id, name=self.name) def get_tag_category(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTagCategoryResult: """ The `TagCategory` data source can be used to reference tag categories that are not managed by this provider. Its attributes are exactly the same as the `TagCategory` resource, and, like importing, the data source takes a name to search on. The `id` and other attributes are then populated with the data found by the search. > **NOTE:** Tagging support is unsupported on direct ESXi connections and requires vCenter 6.0 or higher. ## Example Usage ```python import pulumi import pulumi_vsphere as vsphere category = vsphere.get_tag_category(name="test-category") ``` :param str name: The name of the tag category. """ __args__ = dict() __args__['name'] = name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('vsphere:index/getTagCategory:getTagCategory', __args__, opts=opts, typ=GetTagCategoryResult).value return AwaitableGetTagCategoryResult( associable_types=__ret__.associable_types, cardinality=__ret__.cardinality, description=__ret__.description, id=__ret__.id, name=__ret__.name)
33.915966
135
0.671952
795a343218326c8ca4a7891eba280d93bf5bdf52
218
py
Python
src/DesviosCondicionais/index5.py
santa-python/python-workshop
00a17b96218625933681df85f73268326adbeb22
[ "MIT" ]
1
2019-03-16T14:49:27.000Z
2019-03-16T14:49:27.000Z
src/DesviosCondicionais/index5.py
santa-python/python-workshop
00a17b96218625933681df85f73268326adbeb22
[ "MIT" ]
null
null
null
src/DesviosCondicionais/index5.py
santa-python/python-workshop
00a17b96218625933681df85f73268326adbeb22
[ "MIT" ]
null
null
null
string = input('digite o que quiser:') occurrence = input('digite sua ocorrência:') while len(occurrence) > 1: occurrence = input('digite apenas uma letra:') if occurrence in string: print('achei') else: print(':(')
27.25
47
0.706422
795a36344af12b19be5e075b7e50331865a83544
67,333
py
Python
spyder/widgets/collectionseditor.py
scottwedge/spyder
e1afd4c78a4572a0ac1992dc2d134dfaf4b4d804
[ "MIT" ]
null
null
null
spyder/widgets/collectionseditor.py
scottwedge/spyder
e1afd4c78a4572a0ac1992dc2d134dfaf4b4d804
[ "MIT" ]
null
null
null
spyder/widgets/collectionseditor.py
scottwedge/spyder
e1afd4c78a4572a0ac1992dc2d134dfaf4b4d804
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright © Spyder Project Contributors # # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) # ---------------------------------------------------------------------------- """ Collections (i.e. dictionary, list, set and tuple) editor widget and dialog. """ #TODO: Multiple selection: open as many editors (array/dict/...) as necessary, # at the same time # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 # Standard library imports from __future__ import print_function import datetime import re import sys import warnings # Third party imports from qtpy.compat import getsavefilename, to_qvariant from qtpy.QtCore import (QAbstractTableModel, QModelIndex, Qt, Signal, Slot) from qtpy.QtGui import QColor, QKeySequence from qtpy.QtWidgets import (QAbstractItemView, QApplication, QDialog, QHBoxLayout, QHeaderView, QInputDialog, QLineEdit, QMenu, QMessageBox, QPushButton, QTableView, QVBoxLayout, QWidget) from spyder_kernels.utils.misc import fix_reference_name from spyder_kernels.utils.nsview import ( DataFrame, display_to_value, FakeObject, get_color_name, get_human_readable_type, get_size, Image, MaskedArray, ndarray, np_savetxt, Series, sort_against, try_to_eval, unsorted_unique, value_to_display, get_object_attrs, get_type_string, NUMERIC_NUMPY_TYPES) # Local imports from spyder.config.base import _, PICKLE_PROTOCOL from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font from spyder.py3compat import (io, is_binary_string, PY3, to_text_string, is_type_text_string, NUMERIC_TYPES) from spyder.utils import icon_manager as ima from spyder.utils.misc import getcwd_or_home from spyder.utils.qthelpers import (add_actions, create_action, mimedata2url) from spyder.utils.stringmatching import get_search_scores, get_search_regex from spyder.plugins.variableexplorer.widgets.collectionsdelegate import ( CollectionsDelegate) from spyder.plugins.variableexplorer.widgets.importwizard import ImportWizard from spyder.widgets.helperwidgets import CustomSortFilterProxy from spyder.plugins.variableexplorer.widgets.basedialog import BaseDialog # Maximum length of a serialized variable to be set in the kernel MAX_SERIALIZED_LENGHT = 1e6 LARGE_NROWS = 100 ROWS_TO_LOAD = 50 class ProxyObject(object): """Dictionary proxy to an unknown object.""" def __init__(self, obj): """Constructor.""" self.__obj__ = obj def __len__(self): """Get len according to detected attributes.""" return len(get_object_attrs(self.__obj__)) def __getitem__(self, key): """Get the attribute corresponding to the given key.""" # Catch NotImplementedError to fix spyder-ide/spyder#6284 in pandas # MultiIndex due to NA checking not being supported on a multiindex. # Catch AttributeError to fix spyder-ide/spyder#5642 in certain special # classes like xml when this method is called on certain attributes. # Catch TypeError to prevent fatal Python crash to desktop after # modifying certain pandas objects. Fix spyder-ide/spyder#6727. # Catch ValueError to allow viewing and editing of pandas offsets. # Fix spyder-ide/spyder#6728- try: attribute_toreturn = getattr(self.__obj__, key) except (NotImplementedError, AttributeError, TypeError, ValueError): attribute_toreturn = None return attribute_toreturn def __setitem__(self, key, value): """Set attribute corresponding to key with value.""" # Catch AttributeError to gracefully handle inability to set an # attribute due to it not being writeable or set-table. # Fix spyder-ide/spyder#6728. # Also, catch NotImplementedError for safety. try: setattr(self.__obj__, key, value) except (TypeError, AttributeError, NotImplementedError): pass except Exception as e: if "cannot set values for" not in str(e): raise class ReadOnlyCollectionsModel(QAbstractTableModel): """CollectionsEditor Read-Only Table Model""" sig_setting_data = Signal() def __init__(self, parent, data, title="", names=False, minmax=False, dataframe_format=None, show_callable_attributes=None, show_special_attributes=None, remote=False): QAbstractTableModel.__init__(self, parent) if data is None: data = {} self._parent = parent self.scores = [] self.names = names self.minmax = minmax self.dataframe_format = dataframe_format self.show_callable_attributes = show_callable_attributes self.show_special_attributes = show_special_attributes self.remote = remote self.header0 = None self._data = None self.total_rows = None self.showndata = None self.keys = None self.title = to_text_string(title) # in case title is not a string if self.title: self.title = self.title + ' - ' self.sizes = [] self.types = [] self.set_data(data) def current_index(self): """Get the currently selected index in the parent table view.""" idx = self._parent.proxy_model.mapToSource(self._parent.currentIndex()) return idx def get_data(self): """Return model data""" return self._data def set_data(self, data, coll_filter=None): """Set model data""" self._data = data data_type = get_type_string(data) if (coll_filter is not None and not self.remote and isinstance(data, (tuple, list, dict, set))): data = coll_filter(data) self.showndata = data self.header0 = _("Index") if self.names: self.header0 = _("Name") if isinstance(data, tuple): self.keys = list(range(len(data))) self.title += _("Tuple") elif isinstance(data, list): self.keys = list(range(len(data))) self.title += _("List") elif isinstance(data, set): self.keys = list(range(len(data))) self.title += _("Set") self._data = list(data) elif isinstance(data, dict): self.keys = list(data.keys()) self.title += _("Dictionary") if not self.names: self.header0 = _("Key") else: self.keys = get_object_attrs(data) self._data = data = self.showndata = ProxyObject(data) if not self.names: self.header0 = _("Attribute") if not isinstance(self._data, ProxyObject): self.title += (' (' + str(len(self.keys)) + ' ' + _("elements") + ')') else: self.title += data_type self.total_rows = len(self.keys) if self.total_rows > LARGE_NROWS: self.rows_loaded = ROWS_TO_LOAD else: self.rows_loaded = self.total_rows self.sig_setting_data.emit() self.set_size_and_type() if len(self.keys): # Needed to update search scores when # adding values to the namespace self.update_search_letters() self.reset() def set_size_and_type(self, start=None, stop=None): data = self._data if start is None and stop is None: start = 0 stop = self.rows_loaded fetch_more = False else: fetch_more = True # Ignore pandas warnings that certain attributes are deprecated # and will be removed, since they will only be accessed if they exist. with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message=(r"^\w+\.\w+ is deprecated and " "will be removed in a future version")) if self.remote: sizes = [data[self.keys[index]]['size'] for index in range(start, stop)] types = [data[self.keys[index]]['type'] for index in range(start, stop)] else: sizes = [get_size(data[self.keys[index]]) for index in range(start, stop)] types = [get_human_readable_type(data[self.keys[index]]) for index in range(start, stop)] if fetch_more: self.sizes = self.sizes + sizes self.types = self.types + types else: self.sizes = sizes self.types = types def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method""" reverse = (order==Qt.DescendingOrder) if column == 0: self.sizes = sort_against(self.sizes, self.keys, reverse) self.types = sort_against(self.types, self.keys, reverse) try: self.keys.sort(reverse=reverse) except: pass elif column == 1: self.keys[:self.rows_loaded] = sort_against(self.keys, self.types, reverse) self.sizes = sort_against(self.sizes, self.types, reverse) try: self.types.sort(reverse=reverse) except: pass elif column == 2: self.keys[:self.rows_loaded] = sort_against(self.keys, self.sizes, reverse) self.types = sort_against(self.types, self.sizes, reverse) try: self.sizes.sort(reverse=reverse) except: pass elif column in [3, 4]: values = [self._data[key] for key in self.keys] self.keys = sort_against(self.keys, values, reverse) self.sizes = sort_against(self.sizes, values, reverse) self.types = sort_against(self.types, values, reverse) self.beginResetModel() self.endResetModel() def columnCount(self, qindex=QModelIndex()): """Array column number""" return 5 def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded def canFetchMore(self, index=QModelIndex()): if self.total_rows > self.rows_loaded: return True else: return False def fetchMore(self, index=QModelIndex()): reminder = self.total_rows - self.rows_loaded items_to_fetch = min(reminder, ROWS_TO_LOAD) self.set_size_and_type(self.rows_loaded, self.rows_loaded + items_to_fetch) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch - 1) self.rows_loaded += items_to_fetch self.endInsertRows() def get_index_from_key(self, key): try: return self.createIndex(self.keys.index(key), 0) except (RuntimeError, ValueError): return QModelIndex() def get_key(self, index): """Return current key""" return self.keys[index.row()] def get_value(self, index): """Return current value""" if index.column() == 0: return self.keys[ index.row() ] elif index.column() == 1: return self.types[ index.row() ] elif index.column() == 2: return self.sizes[ index.row() ] else: return self._data[ self.keys[index.row()] ] def get_bgcolor(self, index): """Background color depending on value""" if index.column() == 0: color = QColor(Qt.lightGray) color.setAlphaF(.05) elif index.column() < 3: color = QColor(Qt.lightGray) color.setAlphaF(.2) else: color = QColor(Qt.lightGray) color.setAlphaF(.3) return color def update_search_letters(self, text=""): """Update search letters with text input in search box.""" self.letters = text names = [str(key) for key in self.keys] results = get_search_scores(text, names, template='<b>{0}</b>') if results: self.normal_text, _, self.scores = zip(*results) self.reset() def row_key(self, row_num): """ Get row name based on model index. Needed for the custom proxy model. """ return self.keys[row_num] def row_type(self, row_num): """ Get row type based on model index. Needed for the custom proxy model. """ return self.types[row_num] def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return to_qvariant() value = self.get_value(index) if index.column() == 4 and role == Qt.DisplayRole: # TODO: Check the effect of not hidding the column # Treating search scores as a table column simplifies the # sorting once a score for a specific string in the finder # has been defined. This column however should always remain # hidden. return to_qvariant(self.scores[index.row()]) if index.column() == 3 and self.remote: value = value['view'] if index.column() == 3: display = value_to_display(value, minmax=self.minmax) else: if is_type_text_string(value): display = to_text_string(value, encoding="utf-8") elif not isinstance(value, NUMERIC_TYPES + NUMERIC_NUMPY_TYPES): display = to_text_string(value) else: display = value if role == Qt.UserRole: if isinstance(value, NUMERIC_TYPES + NUMERIC_NUMPY_TYPES): return to_qvariant(value) else: return to_qvariant(display) elif role == Qt.DisplayRole: return to_qvariant(display) elif role == Qt.EditRole: return to_qvariant(value_to_display(value)) elif role == Qt.TextAlignmentRole: if index.column() == 3: if len(display.splitlines()) < 3: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignTop)) else: return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole: return to_qvariant( self.get_bgcolor(index) ) elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def headerData(self, section, orientation, role=Qt.DisplayRole): """Overriding method headerData""" if role != Qt.DisplayRole: return to_qvariant() i_column = int(section) if orientation == Qt.Horizontal: headers = (self.header0, _("Type"), _("Size"), _("Value"), _("Score")) return to_qvariant( headers[i_column] ) else: return to_qvariant() def flags(self, index): """Overriding method flags""" # This method was implemented in CollectionsModel only, but to enable # tuple exploration (even without editing), this method was moved here if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(int(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)) def reset(self): self.beginResetModel() self.endResetModel() class CollectionsModel(ReadOnlyCollectionsModel): """Collections Table Model""" def set_value(self, index, value): """Set value""" self._data[ self.keys[index.row()] ] = value self.showndata[ self.keys[index.row()] ] = value self.sizes[index.row()] = get_size(value) self.types[index.row()] = get_human_readable_type(value) self.sig_setting_data.emit() def get_bgcolor(self, index): """Background color depending on value""" value = self.get_value(index) if index.column() < 3: color = ReadOnlyCollectionsModel.get_bgcolor(self, index) else: if self.remote: color_name = value['color'] else: color_name = get_color_name(value) color = QColor(color_name) color.setAlphaF(.2) return color def setData(self, index, value, role=Qt.EditRole): """Cell content change""" if not index.isValid(): return False if index.column() < 3: return False value = display_to_value(value, self.get_value(index), ignore_errors=True) self.set_value(index, value) self.dataChanged.emit(index, index) return True class BaseHeaderView(QHeaderView): """ A header view for the BaseTableView that emits a signal when the width of one of its sections is resized by the user. """ sig_user_resized_section = Signal(int, int, int) def __init__(self, parent=None): super(BaseHeaderView, self).__init__(Qt.Horizontal, parent) self._handle_section_is_pressed = False self.sectionResized.connect(self.sectionResizeEvent) # Needed to enable sorting by column # See spyder-ide/spyder#9835 self.setSectionsClickable(True) def mousePressEvent(self, e): super(BaseHeaderView, self).mousePressEvent(e) self._handle_section_is_pressed = (self.cursor().shape() == Qt.SplitHCursor) def mouseReleaseEvent(self, e): super(BaseHeaderView, self).mouseReleaseEvent(e) self._handle_section_is_pressed = False def sectionResizeEvent(self, logicalIndex, oldSize, newSize): if self._handle_section_is_pressed: self.sig_user_resized_section.emit(logicalIndex, oldSize, newSize) class BaseTableView(QTableView): """Base collection editor table view""" sig_option_changed = Signal(str, object) sig_files_dropped = Signal(list) redirect_stdio = Signal(bool) sig_free_memory = Signal() sig_open_editor = Signal() sig_editor_shown = Signal() def __init__(self, parent): QTableView.__init__(self, parent) self.array_filename = None self.menu = None self.empty_ws_menu = None self.paste_action = None self.copy_action = None self.edit_action = None self.plot_action = None self.hist_action = None self.imshow_action = None self.save_array_action = None self.insert_action = None self.remove_action = None self.minmax_action = None self.rename_action = None self.duplicate_action = None self.last_regex = '' self.view_action = None self.delegate = None self.proxy_model = None self.source_model = None self.setAcceptDrops(True) self.automatic_column_width = True self.setHorizontalHeader(BaseHeaderView(parent=self)) self.horizontalHeader().sig_user_resized_section.connect( self.user_resize_columns) def setup_table(self): """Setup table""" self.horizontalHeader().setStretchLastSection(True) self.adjust_columns() # Sorting columns self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder) def setup_menu(self, minmax): """Setup context menu""" if self.minmax_action is not None: self.minmax_action.setChecked(minmax) return resize_action = create_action(self, _("Resize rows to contents"), triggered=self.resizeRowsToContents) resize_columns_action = create_action( self, _("Resize columns to contents"), triggered=self.resize_column_contents) self.paste_action = create_action(self, _("Paste"), icon=ima.icon('editpaste'), triggered=self.paste) self.copy_action = create_action(self, _("Copy"), icon=ima.icon('editcopy'), triggered=self.copy) self.edit_action = create_action(self, _("Edit"), icon=ima.icon('edit'), triggered=self.edit_item) self.plot_action = create_action(self, _("Plot"), icon=ima.icon('plot'), triggered=lambda: self.plot_item('plot')) self.plot_action.setVisible(False) self.hist_action = create_action(self, _("Histogram"), icon=ima.icon('hist'), triggered=lambda: self.plot_item('hist')) self.hist_action.setVisible(False) self.imshow_action = create_action(self, _("Show image"), icon=ima.icon('imshow'), triggered=self.imshow_item) self.imshow_action.setVisible(False) self.save_array_action = create_action(self, _("Save array"), icon=ima.icon('filesave'), triggered=self.save_array) self.save_array_action.setVisible(False) self.insert_action = create_action(self, _("Insert"), icon=ima.icon('insert'), triggered=self.insert_item) self.remove_action = create_action(self, _("Remove"), icon=ima.icon('editdelete'), triggered=self.remove_item) self.minmax_action = create_action(self, _("Show arrays min/max"), toggled=self.toggle_minmax) self.minmax_action.setChecked(minmax) self.toggle_minmax(minmax) self.rename_action = create_action(self, _("Rename"), icon=ima.icon('rename'), triggered=self.rename_item) self.duplicate_action = create_action(self, _("Duplicate"), icon=ima.icon('edit_add'), triggered=self.duplicate_item) self.view_action = create_action( self, _("View with the Object Explorer"), icon=ima.icon('outline_explorer'), triggered=self.view_item) menu = QMenu(self) menu_actions = [self.edit_action, self.plot_action, self.hist_action, self.imshow_action, self.save_array_action, self.insert_action, self.remove_action, self.copy_action, self.paste_action, self.view_action, None, self.rename_action, self.duplicate_action, None, resize_action, resize_columns_action] if ndarray is not FakeObject: menu_actions.append(self.minmax_action) add_actions(menu, menu_actions) self.empty_ws_menu = QMenu(self) add_actions(self.empty_ws_menu, [self.insert_action, self.paste_action, None, resize_action, resize_columns_action]) return menu # ------ Remote/local API ------------------------------------------------- def set_regex(self, regex=None, reset=False): """Update the regex text for the variable finder.""" if reset or not self.finder.text(): text = '' else: text = self.finder.text().replace(' ', '').lower() self.proxy_model.set_filter(text) self.source_model.update_search_letters(text) if text: # TODO: Use constants for column numbers self.sortByColumn(4, Qt.DescendingOrder) # Col 4 for index self.last_regex = regex def next_row(self): """Move to next row from currently selected row.""" row = self.currentIndex().row() rows = self.proxy_model.rowCount() if row + 1 == rows: row = -1 self.selectRow(row + 1) def previous_row(self): """Move to previous row from currently selected row.""" row = self.currentIndex().row() rows = self.proxy_model.rowCount() if row == 0: row = rows self.selectRow(row - 1) def remove_values(self, keys): """Remove values from data""" raise NotImplementedError def copy_value(self, orig_key, new_key): """Copy value""" raise NotImplementedError def new_value(self, key, value): """Create new value in data""" raise NotImplementedError def is_list(self, key): """Return True if variable is a list, a set or a tuple""" raise NotImplementedError def get_len(self, key): """Return sequence length""" raise NotImplementedError def is_array(self, key): """Return True if variable is a numpy array""" raise NotImplementedError def is_image(self, key): """Return True if variable is a PIL.Image image""" raise NotImplementedError def is_dict(self, key): """Return True if variable is a dictionary""" raise NotImplementedError def get_array_shape(self, key): """Return array's shape""" raise NotImplementedError def get_array_ndim(self, key): """Return array's ndim""" raise NotImplementedError def oedit(self, key): """Edit item""" raise NotImplementedError def plot(self, key, funcname): """Plot item""" raise NotImplementedError def imshow(self, key): """Show item's image""" raise NotImplementedError def show_image(self, key): """Show image (item is a PIL image)""" raise NotImplementedError #-------------------------------------------------------------------------- def refresh_menu(self): """Refresh context menu""" index = self.currentIndex() condition = index.isValid() self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.refresh_plot_entries(index) def refresh_plot_entries(self, index): if index.isValid(): key = self.proxy_model.get_key(index) is_list = self.is_list(key) is_array = self.is_array(key) and self.get_len(key) != 0 condition_plot = (is_array and len(self.get_array_shape(key)) <= 2) condition_hist = (is_array and self.get_array_ndim(key) == 1) condition_imshow = condition_plot and self.get_array_ndim(key) == 2 condition_imshow = condition_imshow or self.is_image(key) else: is_array = condition_plot = condition_imshow = is_list \ = condition_hist = False self.plot_action.setVisible(condition_plot or is_list) self.hist_action.setVisible(condition_hist or is_list) self.imshow_action.setVisible(condition_imshow) self.save_array_action.setVisible(is_array) def resize_column_contents(self): """Resize columns to contents.""" self.automatic_column_width = True self.adjust_columns() def user_resize_columns(self, logical_index, old_size, new_size): """Handle the user resize action.""" self.automatic_column_width = False def adjust_columns(self): """Resize two first columns to contents""" if self.automatic_column_width: for col in range(3): self.resizeColumnToContents(col) def set_data(self, data): """Set table data""" if data is not None: self.source_model.set_data(data, self.dictfilter) self.source_model.reset() self.sortByColumn(0, Qt.AscendingOrder) def mousePressEvent(self, event): """Reimplement Qt method""" if event.button() != Qt.LeftButton: QTableView.mousePressEvent(self, event) return index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): if index_clicked == self.currentIndex() \ and index_clicked in self.selectedIndexes(): self.clearSelection() else: QTableView.mousePressEvent(self, event) else: self.clearSelection() event.accept() def mouseDoubleClickEvent(self, event): """Reimplement Qt method""" index_clicked = self.indexAt(event.pos()) if index_clicked.isValid(): row = index_clicked.row() # TODO: Remove hard coded "Value" column number (3 here) index_clicked = index_clicked.child(row, 3) self.edit(index_clicked) else: event.accept() def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item() elif event == QKeySequence.Copy: self.copy() elif event == QKeySequence.Paste: self.paste() else: QTableView.keyPressEvent(self, event) def contextMenuEvent(self, event): """Reimplement Qt method""" if self.source_model.showndata: self.refresh_menu() self.menu.popup(event.globalPos()) event.accept() else: self.empty_ws_menu.popup(event.globalPos()) event.accept() def dragEnterEvent(self, event): """Allow user to drag files""" if mimedata2url(event.mimeData()): event.accept() else: event.ignore() def dragMoveEvent(self, event): """Allow user to move files""" if mimedata2url(event.mimeData()): event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): """Allow user to drop supported files""" urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore() @Slot(bool) def toggle_show_callable_attributes(self, state): """Toggle callable attributes for the Object Explorer.""" self.sig_option_changed.emit('show_callable_attributes', state) self.model.show_callable_attributes = state @Slot(bool) def toggle_show_special_attributes(self, state): """Toggle special attributes for the Object Explorer.""" self.sig_option_changed.emit('show_special_attributes', state) self.model.show_special_attributes = state @Slot(bool) def toggle_minmax(self, state): """Toggle min/max display for numpy arrays""" self.sig_option_changed.emit('minmax', state) self.model.minmax = state @Slot(str) def set_dataframe_format(self, new_format): """ Set format to use in DataframeEditor. Args: new_format (string): e.g. "%.3f" """ self.sig_option_changed.emit('dataframe_format', new_format) self.model.dataframe_format = new_format @Slot() def edit_item(self): """Edit item""" index = self.currentIndex() if not index.isValid(): return # TODO: Remove hard coded "Value" column number (3 here) self.edit(index.child(index.row(), 3)) @Slot() def remove_item(self, force=False): """Remove item""" indexes = self.selectedIndexes() if not indexes: return for index in indexes: if not index.isValid(): return if not force: one = _("Do you want to remove the selected item?") more = _("Do you want to remove all selected items?") answer = QMessageBox.question(self, _("Remove"), one if len(indexes) == 1 else more, QMessageBox.Yes | QMessageBox.No) if force or answer == QMessageBox.Yes: idx_rows = unsorted_unique( [self.proxy_model.mapToSource(idx).row() for idx in indexes]) keys = [self.source_model.keys[idx_row] for idx_row in idx_rows] self.remove_values(keys) def copy_item(self, erase_original=False, new_name=None): """Copy item""" indexes = self.selectedIndexes() if not indexes: return idx_rows = unsorted_unique( [self.proxy_model.mapToSource(idx).row() for idx in indexes]) if len(idx_rows) > 1 or not indexes[0].isValid(): return orig_key = self.source_model.keys[idx_rows[0]] if erase_original: title = _('Rename') field_text = _('New variable name:') else: title = _('Duplicate') field_text = _('Variable name:') data = self.source_model.get_data() if isinstance(data, (list, set)): new_key, valid = len(data), True elif new_name is not None: new_key, valid = new_name, True else: new_key, valid = QInputDialog.getText(self, title, field_text, QLineEdit.Normal, orig_key) if valid and to_text_string(new_key): new_key = try_to_eval(to_text_string(new_key)) if new_key == orig_key: return self.copy_value(orig_key, new_key) if erase_original: self.remove_values([orig_key]) @Slot() def duplicate_item(self): """Duplicate item""" self.copy_item() @Slot() def rename_item(self, new_name=None): """Rename item""" self.copy_item(erase_original=True, new_name=new_name) @Slot() def insert_item(self): """Insert item""" index = self.currentIndex() if not index.isValid(): row = self.source_model.rowCount() else: row = self.proxy_model.mapToSource(index).row() data = self.source_model.get_data() if isinstance(data, list): key = row data.insert(row, '') elif isinstance(data, dict): key, valid = QInputDialog.getText(self, _( 'Insert'), _( 'Key:'), QLineEdit.Normal) if valid and to_text_string(key): key = try_to_eval(to_text_string(key)) else: return else: return value, valid = QInputDialog.getText(self, _('Insert'), _('Value:'), QLineEdit.Normal) if valid and to_text_string(value): self.new_value(key, try_to_eval(to_text_string(value))) @Slot() def view_item(self): """View item with the Object Explorer""" index = self.currentIndex() if not index.isValid(): return # TODO: Remove hard coded "Value" column number (3 here) index = index.child(index.row(), 3) self.delegate.createEditor(self, None, index, object_explorer=True) def __prepare_plot(self): try: import guiqwt.pyplot #analysis:ignore return True except: try: if 'matplotlib' not in sys.modules: import matplotlib matplotlib.use("Qt4Agg") return True except: QMessageBox.warning(self, _("Import error"), _("Please install <b>matplotlib</b>" " or <b>guiqwt</b>.")) def plot_item(self, funcname): """Plot item""" index = self.currentIndex() if self.__prepare_plot(): key = self.source_model.get_key( self.proxy_model.mapToSource(index)) try: self.plot(key, funcname) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to plot data.</b>" "<br><br>Error message:<br>%s" ) % str(error)) @Slot() def imshow_item(self): """Imshow item""" index = self.currentIndex() if self.__prepare_plot(): key = self.source_model.get_key( self.proxy_model.mapToSource(index)) try: if self.is_image(key): self.show_image(key) else: self.imshow(key) except (ValueError, TypeError) as error: QMessageBox.critical(self, _( "Plot"), _("<b>Unable to show image.</b>" "<br><br>Error message:<br>%s" ) % str(error)) @Slot() def save_array(self): """Save array""" title = _( "Save array") if self.array_filename is None: self.array_filename = getcwd_or_home() self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.array_filename, _("NumPy arrays")+" (*.npy)") self.redirect_stdio.emit(True) if filename: self.array_filename = filename data = self.delegate.get_value( self.currentIndex() ) try: import numpy as np np.save(self.array_filename, data) except Exception as error: QMessageBox.critical(self, title, _("<b>Unable to save array</b>" "<br><br>Error message:<br>%s" ) % str(error)) @Slot() def copy(self): """Copy text to clipboard""" clipboard = QApplication.clipboard() clipl = [] for idx in self.selectedIndexes(): if not idx.isValid(): continue obj = self.delegate.get_value(idx) # Check if we are trying to copy a numpy array, and if so make sure # to copy the whole thing in a tab separated format if isinstance(obj, (ndarray, MaskedArray)) \ and ndarray is not FakeObject: if PY3: output = io.BytesIO() else: output = io.StringIO() try: np_savetxt(output, obj, delimiter='\t') except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this array")) return obj = output.getvalue().decode('utf-8') output.close() elif isinstance(obj, (DataFrame, Series)) \ and DataFrame is not FakeObject: output = io.StringIO() try: obj.to_csv(output, sep='\t', index=True, header=True) except Exception: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy " "this dataframe")) return if PY3: obj = output.getvalue() else: obj = output.getvalue().decode('utf-8') output.close() elif is_binary_string(obj): obj = to_text_string(obj, 'utf8') else: obj = to_text_string(obj) clipl.append(obj) clipboard.setText('\n'.join(clipl)) def import_from_string(self, text, title=None): """Import data from string""" data = self.source_model.get_data() # Check if data is a dict if not hasattr(data, "keys"): return editor = ImportWizard(self, text, title=title, contents_title=_("Clipboard contents"), varname=fix_reference_name("data", blacklist=list(data.keys()))) if editor.exec_(): var_name, clip_data = editor.get_data() self.new_value(var_name, clip_data) @Slot() def paste(self): """Import text/data/code from clipboard""" clipboard = QApplication.clipboard() cliptext = '' if clipboard.mimeData().hasText(): cliptext = to_text_string(clipboard.text()) if cliptext.strip(): self.import_from_string(cliptext, title=_("Import from clipboard")) else: QMessageBox.warning(self, _( "Empty clipboard"), _("Nothing to be imported from clipboard.")) class CollectionsEditorTableView(BaseTableView): """CollectionsEditor table view""" def __init__(self, parent, data, readonly=False, title="", names=False, minmax=False): BaseTableView.__init__(self, parent) self.dictfilter = None self.readonly = readonly or isinstance(data, (tuple, set)) CollectionsModelClass = (ReadOnlyCollectionsModel if self.readonly else CollectionsModel) self.source_model = CollectionsModelClass(self, data, title, names=names, minmax=minmax) self.proxy_model = CollectionsCustomSortFilterProxy(self) self.model = self.proxy_model self.proxy_model.setSourceModel(self.source_model) self.proxy_model.setDynamicSortFilter(True) self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) self.proxy_model.setSortRole(Qt.UserRole) self.setModel(self.proxy_model) self.hideColumn(4) # Column 4 for Score self.delegate = CollectionsDelegate(self) self.setItemDelegate(self.delegate) self.setup_table() self.menu = self.setup_menu(minmax) if isinstance(data, set): self.horizontalHeader().hideSection(0) #------ Remote/local API -------------------------------------------------- def remove_values(self, keys): """Remove values from data""" data = self.source_model.get_data() for key in sorted(keys, reverse=True): data.pop(key) self.set_data(data) def copy_value(self, orig_key, new_key): """Copy value""" data = self.source_model.get_data() if isinstance(data, list): data.append(data[orig_key]) if isinstance(data, set): data.add(data[orig_key]) else: data[new_key] = data[orig_key] self.set_data(data) def new_value(self, key, value): """Create new value in data""" data = self.source_model.get_data() data[key] = value self.set_data(data) def is_list(self, key): """Return True if variable is a list or a tuple""" data = self.source_model.get_data() return isinstance(data[key], (tuple, list)) def is_set(self, key): """Return True if variable is a set""" data = self.source_model.get_data() return isinstance(data[key], set) def get_len(self, key): """Return sequence length""" data = self.source_model.get_data() return len(data[key]) def is_array(self, key): """Return True if variable is a numpy array""" data = self.source_model.get_data() return isinstance(data[key], (ndarray, MaskedArray)) def is_image(self, key): """Return True if variable is a PIL.Image image""" data = self.source_model.get_data() return isinstance(data[key], Image) def is_dict(self, key): """Return True if variable is a dictionary""" data = self.source_model.get_data() return isinstance(data[key], dict) def get_array_shape(self, key): """Return array's shape""" data = self.source_model.get_data() return data[key].shape def get_array_ndim(self, key): """Return array's ndim""" data = self.source_model.get_data() return data[key].ndim def oedit(self, key): """Edit item""" data = self.source_model.get_data() from spyder.plugins.variableexplorer.widgets.objecteditor import ( oedit) oedit(data[key]) def plot(self, key, funcname): """Plot item""" data = self.source_model.get_data() import spyder.pyplot as plt plt.figure() getattr(plt, funcname)(data[key]) plt.show() def imshow(self, key): """Show item's image""" data = self.source_model.get_data() import spyder.pyplot as plt plt.figure() plt.imshow(data[key]) plt.show() def show_image(self, key): """Show image (item is a PIL image)""" data = self.source_model.get_data() data[key].show() #-------------------------------------------------------------------------- def refresh_menu(self): """Refresh context menu""" data = self.source_model.get_data() index = self.currentIndex() condition = (not isinstance(data, (tuple, set))) and index.isValid() \ and not self.readonly self.edit_action.setEnabled( condition ) self.remove_action.setEnabled( condition ) self.insert_action.setEnabled( not self.readonly ) self.duplicate_action.setEnabled(condition) condition_rename = not isinstance(data, (tuple, list, set)) self.rename_action.setEnabled(condition_rename) self.refresh_plot_entries(index) def set_filter(self, dictfilter=None): """Set table dict filter""" self.dictfilter = dictfilter class CollectionsEditorWidget(QWidget): """Dictionary Editor Widget""" def __init__(self, parent, data, readonly=False, title="", remote=False): QWidget.__init__(self, parent) if remote: self.editor = RemoteCollectionsEditorTableView(self, data, readonly) else: self.editor = CollectionsEditorTableView(self, data, readonly, title) layout = QVBoxLayout() layout.addWidget(self.editor) self.setLayout(layout) def set_data(self, data): """Set DictEditor data""" self.editor.set_data(data) def get_title(self): """Get model title""" return self.editor.source_model.title class CollectionsEditor(BaseDialog): """Collections Editor Dialog""" def __init__(self, parent=None): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data_copy = None self.widget = None self.btn_save_and_close = None self.btn_close = None def setup(self, data, title='', readonly=False, remote=False, icon=None, parent=None): """Setup editor.""" if isinstance(data, (dict, set)): # dictionnary, set self.data_copy = data.copy() datalen = len(data) elif isinstance(data, (tuple, list)): # list, tuple self.data_copy = data[:] datalen = len(data) else: # unknown object import copy try: self.data_copy = copy.deepcopy(data) except NotImplementedError: self.data_copy = copy.copy(data) except (TypeError, AttributeError): readonly = True self.data_copy = data datalen = len(get_object_attrs(data)) # If the copy has a different type, then do not allow editing, because # this would change the type after saving; cf. spyder-ide/spyder#6936. if type(self.data_copy) != type(data): readonly = True self.widget = CollectionsEditorWidget(self, self.data_copy, title=title, readonly=readonly, remote=remote) self.widget.editor.source_model.sig_setting_data.connect( self.save_and_close_enable) layout = QVBoxLayout() layout.addWidget(self.widget) self.setLayout(layout) # Buttons configuration btn_layout = QHBoxLayout() btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) layout.addLayout(btn_layout) self.setWindowTitle(self.widget.get_title()) if icon is None: self.setWindowIcon(ima.icon('dictedit')) if sys.platform == 'darwin': # See: https://github.com/spyder-ide/spyder/issues/9051 self.setWindowFlags(Qt.Tool) else: # Make the dialog act as a window self.setWindowFlags(Qt.Window) @Slot() def save_and_close_enable(self): """Handle the data change event to enable the save and close button.""" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def get_value(self): """Return modified copy of dictionary or list""" # It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute return self.data_copy #============================================================================== # Remote versions of CollectionsDelegate and CollectionsEditorTableView #============================================================================== class RemoteCollectionsDelegate(CollectionsDelegate): """CollectionsEditor Item Delegate""" def __init__(self, parent=None): CollectionsDelegate.__init__(self, parent) def get_value(self, index): if index.isValid(): source_index = index.model().mapToSource(index) name = source_index.model().keys[source_index.row()] return self.parent().get_value(name) def set_value(self, index, value): if index.isValid(): source_index = index.model().mapToSource(index) name = source_index.model().keys[source_index.row()] self.parent().new_value(name, value) class RemoteCollectionsEditorTableView(BaseTableView): """DictEditor table view""" def __init__(self, parent, data, minmax=False, shellwidget=None, remote_editing=False, dataframe_format=None, show_callable_attributes=None, show_special_attributes=None): BaseTableView.__init__(self, parent) self.shellwidget = shellwidget self.var_properties = {} self.dictfilter = None self.source_model = None self.delegate = None self.readonly = False self.source_model = CollectionsModel( self, data, names=True, minmax=minmax, dataframe_format=dataframe_format, show_callable_attributes=show_callable_attributes, show_special_attributes=show_special_attributes, remote=True) self.proxy_model = CollectionsCustomSortFilterProxy(self) self.model = self.proxy_model self.proxy_model.setSourceModel(self.source_model) self.proxy_model.setDynamicSortFilter(True) self.proxy_model.setFilterKeyColumn(0) # Col 0 for Name self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive) self.proxy_model.setSortRole(Qt.UserRole) self.setModel(self.proxy_model) self.hideColumn(4) # Column 4 for Score self.delegate = RemoteCollectionsDelegate(self) self.delegate.sig_free_memory.connect(self.sig_free_memory.emit) self.delegate.sig_open_editor.connect(self.sig_open_editor.emit) self.delegate.sig_editor_shown.connect(self.sig_editor_shown.emit) self.setItemDelegate(self.delegate) self.setup_table() self.menu = self.setup_menu(minmax) # ------ Remote/local API ------------------------------------------------- def get_value(self, name): """Get the value of a variable""" value = self.shellwidget.get_value(name) return value def new_value(self, name, value): """Create new value in data""" try: self.shellwidget.set_value(name, value) except TypeError as e: QMessageBox.critical(self, _("Error"), "TypeError: %s" % to_text_string(e)) self.shellwidget.refresh_namespacebrowser() def remove_values(self, names): """Remove values from data""" for name in names: self.shellwidget.remove_value(name) self.shellwidget.refresh_namespacebrowser() def copy_value(self, orig_name, new_name): """Copy value""" self.shellwidget.copy_value(orig_name, new_name) self.shellwidget.refresh_namespacebrowser() def is_list(self, name): """Return True if variable is a list, a tuple or a set""" return self.var_properties[name]['is_list'] def is_dict(self, name): """Return True if variable is a dictionary""" return self.var_properties[name]['is_dict'] def get_len(self, name): """Return sequence length""" return self.var_properties[name]['len'] def is_array(self, name): """Return True if variable is a NumPy array""" return self.var_properties[name]['is_array'] def is_image(self, name): """Return True if variable is a PIL.Image image""" return self.var_properties[name]['is_image'] def is_data_frame(self, name): """Return True if variable is a DataFrame""" return self.var_properties[name]['is_data_frame'] def is_series(self, name): """Return True if variable is a Series""" return self.var_properties[name]['is_series'] def get_array_shape(self, name): """Return array's shape""" return self.var_properties[name]['array_shape'] def get_array_ndim(self, name): """Return array's ndim""" return self.var_properties[name]['array_ndim'] def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw.is_waiting_pdb_input(): sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%varexp --%s %s" % (funcname, name)) def imshow(self, name): """Show item's image""" sw = self.shellwidget if sw.is_waiting_pdb_input(): sw.dbg_exec_magic('varexp', '--imshow %s' % name) else: sw.execute("%%varexp --imshow %s" % name) def show_image(self, name): """Show image (item is a PIL image)""" command = "%s.show()" % name sw = self.shellwidget if sw.is_waiting_pdb_input(): sw.pdb_execute(command) else: sw.execute(command) # ------------------------------------------------------------------------- def setup_menu(self, minmax): """Setup context menu.""" menu = BaseTableView.setup_menu(self, minmax) return menu class CollectionsCustomSortFilterProxy(CustomSortFilterProxy): """ Custom column filter based on regex and model data. Reimplements 'filterAcceptsRow' to follow NamespaceBrowser model. Reimplements 'set_filter' to allow sorting while filtering """ @property def show_callable_attributes(self): """Get show_callable_attributes from source model.""" return self.sourceModel().show_callable_attributes @show_callable_attributes.setter def show_callable_attributes(self, value): """Set show_callable_attributes to source model.""" self.sourceModel().show_callable_attributes = value @property def show_special_attributes(self): """Get show_special_attributes from source model.""" return self.sourceModel().show_special_attributes @show_special_attributes.setter def show_special_attributes(self, value): """Set show_special_attributes to source model.""" self.sourceModel().show_special_attributes = value @property def minmax(self): """Get minmax from source model.""" return self.sourceModel().minmax @minmax.setter def minmax(self, value): """Set minmax to source model.""" self.sourceModel().minmax = value @property def dataframe_format(self): """Get dataframe_format from source model.""" return self.sourceModel().dataframe_format @dataframe_format.setter def dataframe_format(self, value): """Set dataframe_format to source model.""" self.sourceModel().dataframe_format = value def get_key(self, index): """Return current key from source model.""" source_index = self.mapToSource(index) return self.sourceModel().get_key(source_index) def get_index_from_key(self, key): """Return index using key from source model.""" source_index = self.sourceModel().get_index_from_key(key) return self.mapFromSource(source_index) def get_value(self, index): """Return current value from source model.""" source_index = self.mapToSource(index) return self.sourceModel().get_value(source_index) def set_value(self, index, value): """Set value in source model.""" try: source_index = self.mapToSource(index) self.sourceModel().set_value(source_index, value) except AttributeError: # Read-only models don't have set_value method pass def set_filter(self, text): """Set regular expression for filter.""" self.pattern = get_search_regex(text) self.invalidateFilter() def filterAcceptsRow(self, row_num, parent): """ Qt override. Reimplemented from base class to allow the use of custom filtering using to columns (name and type). """ model = self.sourceModel() name = to_text_string(model.row_key(row_num)) variable_type = to_text_string(model.row_type(row_num)) r_name = re.search(self.pattern, name) r_type = re.search(self.pattern, variable_type) if r_name is None and r_type is None: return False else: return True # ============================================================================= # Tests # ============================================================================= def get_test_data(): """Create test data.""" import numpy as np from spyder.pil_patch import Image image = Image.fromarray(np.random.randint(256, size=(100, 100)), mode='P') testdict = {'d': 1, 'a': np.random.rand(10, 10), 'b': [1, 2]} testdate = datetime.date(1945, 5, 8) test_timedelta = datetime.timedelta(days=-1, minutes=42, seconds=13) try: import pandas as pd except (ModuleNotFoundError, ImportError): test_timestamp, test_pd_td, test_dtindex, test_series, test_df = None else: test_timestamp = pd.Timestamp("1945-05-08T23:01:00.12345") test_pd_td = pd.Timedelta(days=2193, hours=12) test_dtindex = pd.date_range(start="1939-09-01T", end="1939-10-06", freq="12H") test_series = pd.Series({"series_name": [0, 1, 2, 3, 4, 5]}) test_df = pd.DataFrame({"string_col": ["a", "b", "c", "d"], "int_col": [0, 1, 2, 3], "float_col": [1.1, 2.2, 3.3, 4.4], "bool_col": [True, False, False, True]}) class Foobar(object): def __init__(self): self.text = "toto" self.testdict = testdict self.testdate = testdate foobar = Foobar() return {'object': foobar, 'module': np, 'str': 'kjkj kj k j j kj k jkj', 'unicode': to_text_string('éù', 'utf-8'), 'list': [1, 3, [sorted, 5, 6], 'kjkj', None], 'set': {1, 2, 1, 3, None, 'A', 'B', 'C', True, False}, 'tuple': ([1, testdate, testdict, test_timedelta], 'kjkj', None), 'dict': testdict, 'float': 1.2233, 'int': 223, 'bool': True, 'array': np.random.rand(10, 10).astype(np.int64), 'masked_array': np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]]), '1D-array': np.linspace(-10, 10).astype(np.float16), '3D-array': np.random.randint(2, size=(5, 5, 5)).astype(np.bool_), 'empty_array': np.array([]), 'image': image, 'date': testdate, 'datetime': datetime.datetime(1945, 5, 8, 23, 1, 0, int(1.5e5)), 'timedelta': test_timedelta, 'complex': 2+1j, 'complex64': np.complex64(2+1j), 'complex128': np.complex128(9j), 'int8_scalar': np.int8(8), 'int16_scalar': np.int16(16), 'int32_scalar': np.int32(32), 'int64_scalar': np.int64(64), 'float16_scalar': np.float16(16), 'float32_scalar': np.float32(32), 'float64_scalar': np.float64(64), 'bool_scalar': np.bool(8), 'bool__scalar': np.bool_(8), 'timestamp': test_timestamp, 'timedelta_pd': test_pd_td, 'datetimeindex': test_dtindex, 'series': test_series, 'ddataframe': test_df, 'None': None, 'unsupported1': np.arccos, 'unsupported2': np.cast, # Test for spyder-ide/spyder#3518. 'big_struct_array': np.zeros(1000, dtype=[('ID', 'f8'), ('param1', 'f8', 5000)]), } def editor_test(): """Test Collections editor.""" from spyder.utils.qthelpers import qapplication app = qapplication() #analysis:ignore dialog = CollectionsEditor() dialog.setup(get_test_data()) dialog.show() app.exec_() def remote_editor_test(): """Test remote collections editor.""" from spyder.utils.qthelpers import qapplication app = qapplication() from spyder.config.manager import CONF from spyder_kernels.utils.nsview import (make_remote_view, REMOTE_SETTINGS) settings = {} for name in REMOTE_SETTINGS: settings[name] = CONF.get('variable_explorer', name) remote = make_remote_view(get_test_data(), settings) dialog = CollectionsEditor() dialog.setup(remote, remote=True) dialog.show() app.exec_() if __name__ == "__main__": editor_test() remote_editor_test()
38.454026
87
0.555478
795a3696b517eb7666adf08472e8313398550160
8,439
py
Python
awx/main/tests/functional/models/test_notifications.py
vin-c/awx
72de660ea1039039ffd7e7c72d72e5a44ffcbdf7
[ "Apache-2.0" ]
1
2020-04-10T21:29:52.000Z
2020-04-10T21:29:52.000Z
awx/main/tests/functional/models/test_notifications.py
vin-c/awx
72de660ea1039039ffd7e7c72d72e5a44ffcbdf7
[ "Apache-2.0" ]
12
2021-06-17T07:32:11.000Z
2022-03-29T22:11:45.000Z
awx/main/tests/functional/models/test_notifications.py
srflaxu40/awx
c984c2fa49cc445f610d7cca4c2b3191572b01ae
[ "Apache-2.0" ]
1
2021-09-02T16:59:42.000Z
2021-09-02T16:59:42.000Z
# -*- coding: utf-8 -*- from copy import deepcopy import datetime import pytest #from awx.main.models import NotificationTemplates, Notifications, JobNotificationMixin from awx.main.models import (AdHocCommand, InventoryUpdate, Job, JobNotificationMixin, ProjectUpdate, SystemJob, WorkflowJob) from awx.api.serializers import UnifiedJobSerializer class TestJobNotificationMixin(object): CONTEXT_STRUCTURE = {'job': {'allow_simultaneous': bool, 'custom_virtualenv': str, 'controller_node': str, 'created': datetime.datetime, 'description': str, 'diff_mode': bool, 'elapsed': float, 'execution_node': str, 'failed': bool, 'finished': bool, 'force_handlers': bool, 'forks': int, 'host_status_counts': { 'skipped': int, 'ok': int, 'changed': int, 'failures': int, 'dark': int, 'processed': int, 'rescued': int, 'failed': bool }, 'id': int, 'job_explanation': str, 'job_slice_count': int, 'job_slice_number': int, 'job_tags': str, 'job_type': str, 'launch_type': str, 'limit': str, 'modified': datetime.datetime, 'name': str, 'playbook': str, 'scm_branch': str, 'scm_revision': str, 'skip_tags': str, 'start_at_task': str, 'started': str, 'status': str, 'summary_fields': {'created_by': {'first_name': str, 'id': int, 'last_name': str, 'username': str}, 'instance_group': {'id': int, 'name': str}, 'inventory': {'description': str, 'has_active_failures': bool, 'has_inventory_sources': bool, 'hosts_with_active_failures': int, 'id': int, 'inventory_sources_with_failures': int, 'kind': str, 'name': str, 'organization_id': int, 'total_groups': int, 'total_hosts': int, 'total_inventory_sources': int}, 'job_template': {'description': str, 'id': int, 'name': str}, 'labels': {'count': int, 'results': list}, 'project': {'description': str, 'id': int, 'name': str, 'scm_type': str, 'status': str}, 'unified_job_template': {'description': str, 'id': int, 'name': str, 'unified_job_type': str}}, 'timeout': int, 'type': str, 'url': str, 'use_fact_cache': bool, 'verbosity': int}, 'job_friendly_name': str, 'job_metadata': str, 'approval_status': str, 'approval_node_name': str, 'workflow_url': str, 'url': str} @pytest.mark.django_db @pytest.mark.parametrize('JobClass', [AdHocCommand, InventoryUpdate, Job, ProjectUpdate, SystemJob, WorkflowJob]) def test_context(self, JobClass, sqlite_copy_expert, project, inventory_source): """The Jinja context defines all of the fields that can be used by a template. Ensure that the context generated for each job type has the expected structure.""" def check_structure(expected_structure, obj): if isinstance(expected_structure, dict): assert isinstance(obj, dict) for key in obj: assert key in expected_structure if obj[key] is None: continue if isinstance(expected_structure[key], dict): assert isinstance(obj[key], dict) check_structure(expected_structure[key], obj[key]) else: assert isinstance(obj[key], expected_structure[key]) kwargs = {} if JobClass is InventoryUpdate: kwargs['inventory_source'] = inventory_source kwargs['source'] = inventory_source.source elif JobClass is ProjectUpdate: kwargs['project'] = project job = JobClass.objects.create(name='foo', **kwargs) job_serialization = UnifiedJobSerializer(job).to_representation(job) context = job.context(job_serialization) check_structure(TestJobNotificationMixin.CONTEXT_STRUCTURE, context) def test_context_stub(self): """The context stub is a fake context used to validate custom notification messages. Ensure that this also has the expected structure. Furthermore, ensure that the stub context contains *all* fields that could possibly be included in a context.""" def check_structure_and_completeness(expected_structure, obj): expected_structure = deepcopy(expected_structure) if isinstance(expected_structure, dict): assert isinstance(obj, dict) for key in obj: assert key in expected_structure # Context stub should not have any undefined fields assert obj[key] is not None if isinstance(expected_structure[key], dict): assert isinstance(obj[key], dict) check_structure_and_completeness(expected_structure[key], obj[key]) expected_structure.pop(key) else: assert isinstance(obj[key], expected_structure[key]) expected_structure.pop(key) # Ensure all items in expected structure were present assert not len(expected_structure) context_stub = JobNotificationMixin.context_stub() check_structure_and_completeness(TestJobNotificationMixin.CONTEXT_STRUCTURE, context_stub)
57.80137
120
0.397322
795a36c6393c6920fe98783c72e86f002136d8ce
5,415
py
Python
pyspedas/analysis/time_clip.py
amanotk/pyspedas
ba38f9a318fe96911a0fb3d6fce53e8b1a534ff4
[ "MIT" ]
null
null
null
pyspedas/analysis/time_clip.py
amanotk/pyspedas
ba38f9a318fe96911a0fb3d6fce53e8b1a534ff4
[ "MIT" ]
null
null
null
pyspedas/analysis/time_clip.py
amanotk/pyspedas
ba38f9a318fe96911a0fb3d6fce53e8b1a534ff4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ File: time_clip.py Description: Time clip of data. Parameters: names: str/list of str List of pytplot names. new_names: str/list of str List of new_names for pytplot variables. If '', then pytplot variables are replaced. If not given, then a suffix is applied. suffix: A suffix to apply. Default is '-m'. Notes: Allowed wildcards are ? for a single character, * from multiple characters. """ import pyspedas import pytplot from pytplot import data_quants def time_clip(names, time_start, time_end, new_names=None, suffix=None): old_names = pyspedas.tnames(names) if len(old_names) < 1: print('Time clip error: No pytplot names were provided.') return if suffix is None: suffix = '-tclip' if new_names is None: n_names = [s + suffix for s in old_names] elif new_names == '': n_names = old_names else: n_names = new_names if len(n_names) != len(old_names): n_names = [s + suffix for s in old_names] for j in range(len(old_names)): if old_names[j] != n_names[j]: pyspedas.tcopy(old_names[j], n_names[j]) alldata = pytplot.get_data(n_names[j]) time = alldata[0] data = alldata[1] index_start = 0 index_end = len(time) if index_end < 1: print('Time clip found empty list.') continue new_time = pyspedas.time_float(time) new_time_start = pyspedas.time_float(time_start) new_time_end = pyspedas.time_float(time_end) if new_time_start > new_time_end: print('Error: Start time is larger than end time.') continue if (new_time_start > new_time[-1]) or (new_time_end < new_time[0]): print('Time clip returns empty data.') continue if (new_time_start <= new_time[0]) and (new_time_end >= new_time[-1]): print('Time clip returns full data set.') continue for i in range(index_end): if new_time[i] >= new_time_start: index_start = i break found_end = index_end for i in range(index_start, index_end): if new_time[i] > new_time_end: found_end = i break index_end = found_end tmp_dquant = data_quants[n_names[j]] if 'v1' in tmp_dquant.coords.keys(): if len(tmp_dquant.coords['v1'].values.shape) is 2: v1_data = tmp_dquant.coords['v1'].values[index_start:index_end, :] else: v1_data = tmp_dquant.coords['v1'].values if 'v2' in tmp_dquant.coords.keys(): if len(tmp_dquant.coords['v2'].values.shape) is 2: v2_data = tmp_dquant.coords['v2'].values[index_start:index_end, :] else: v2_data = tmp_dquant.coords['v2'].values if 'v3' in tmp_dquant.coords.keys(): if len(tmp_dquant.coords['v3'].values.shape) is 2: v3_data = tmp_dquant.coords['v3'].values[index_start:index_end, :] else: v3_data = tmp_dquant.coords['v3'].values if 'v' in tmp_dquant.coords.keys(): if len(tmp_dquant.coords['v'].values.shape) is 2: v_data = tmp_dquant.coords['v'].values[index_start:index_end, :] else: v_data = tmp_dquant.coords['v'].values if 'spec_bins' in tmp_dquant.coords.keys(): if len(tmp_dquant.coords['spec_bins'].values.shape) is 2: v_data = tmp_dquant.coords['spec_bins'].values[index_start:index_end, :] else: v_data = tmp_dquant.coords['spec_bins'].values try: if 'v1' in tmp_dquant.coords.keys() and 'v2' in tmp_dquant.coords.keys() and 'v3' in tmp_dquant.coords.keys(): pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end, :, :, :], 'v1': v1_data, 'v2': v2_data, 'v3': v3_data}) elif 'v1' in tmp_dquant.coords.keys() and 'v2' in tmp_dquant.coords.keys(): pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end, :, :], 'v1': v1_data, 'v2': v2_data}) elif 'v1' in tmp_dquant.coords.keys(): pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end, :], 'v1': v1_data}) elif 'spec_bins' in tmp_dquant.coords.keys(): pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end, :], 'v': v_data}) elif 'v' in tmp_dquant.coords.keys(): pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end, :], 'v': v_data}) elif data.ndim == 1: pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end]}) else: pytplot.store_data(n_names[j], data={'x': time[index_start:index_end], 'y': data[index_start:index_end,...]}) except: print('Problem time clipping: ' + n_names[j]) continue print('Time clip was applied to: ' + n_names[j])
37.867133
175
0.582271
795a36e9dab00a40b69bbb67e94bbf5c0503b2e6
1,711
py
Python
src/CmdBoxHandler.py
lookwhoistalkingpython/VoiceEditor
7fb57b1f97d052ea023f6bee2c2669195f76c21c
[ "MIT" ]
2
2020-08-29T21:28:28.000Z
2021-11-05T12:50:40.000Z
src/CmdBoxHandler.py
lookwhoistalkinguvm/VoiceEditorUVM
0769d65cf90c6d82504f22fabdf7957ae03a9699
[ "MIT" ]
null
null
null
src/CmdBoxHandler.py
lookwhoistalkinguvm/VoiceEditorUVM
0769d65cf90c6d82504f22fabdf7957ae03a9699
[ "MIT" ]
1
2021-04-07T11:12:53.000Z
2021-04-07T11:12:53.000Z
# #Copyright 2020 Carsten Thiele # #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 os from CmdDosListDirectory import CmdDosListDirectory from CmdEdit import CmdEdit class CmdBoxHandler : def __init__(self,voiceEditor,cmdBox,editBox,scaleBox,viewBox,statusBox): self.voiceEditor=voiceEditor self.cmdBox=cmdBox self.scaleBox=scaleBox self.editBox=editBox self.statusBox=statusBox self.viewBox=viewBox self.cmd=CmdDosListDirectory\ (voiceEditor,self.cmdBox,self.editBox,self.scaleBox,self.viewBox,self.statusBox) def processCmd(self,command): self.cmd=self.cmd.processThisCommand(command) def is_instance_of_cmdedit(self,objectToCheck): return isinstance(objectToCheck,CmdEdit)
34.22
104
0.799532
795a3718fc711bf89475e02b558d67f326f367b1
1,968
py
Python
app/core/tests/test_models.py
wolfiee007/recipe-app-api
e6f99afa4a009ae71b4b06803e0b618a75ac0536
[ "MIT" ]
null
null
null
app/core/tests/test_models.py
wolfiee007/recipe-app-api
e6f99afa4a009ae71b4b06803e0b618a75ac0536
[ "MIT" ]
6
2020-05-15T10:53:08.000Z
2022-02-10T14:31:30.000Z
app/core/tests/test_models.py
wolfiee007/recipe-app-api
e6f99afa4a009ae71b4b06803e0b618a75ac0536
[ "MIT" ]
null
null
null
from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@wolfiee.com', password='123456'): "Create a sample user" return get_user_model().objects.create_user(email,password) class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = 'test@wolfiee.com' password = '123456' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Test the email for a new user is normalized""" email = 'test@WOLFIEE.COM' user = get_user_model().objects.create_user(email, '123456') self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """Test creating user with no email raises error""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, '123456') def test_create_new_superuser(self): """Test creating a new superuser""" user = get_user_model().objects.create_superuser( 'wolf@wolfiee.com', '123456' ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff) def test_tag_str(self): """Test the tag string representation""" tag = models.Tag.objects.create( user=sample_user(), name='vegan', ) self.assertEqual(str(tag), tag.name) def test_ingredient_str(self): """Test the ingredient string representation""" ingredient = models.Ingredient.objects.create( user = sample_user(), name = 'Cucumber' ) self.assertEqual(str(ingredient),ingredient.name)
31.741935
68
0.643293
795a37a525f02d1c5a44598119cf7361e3466fd3
434
py
Python
yatube/posts/admin.py
Apocalyptic434/hw02_community
04e105d6ed2f76c4b1bb08b7c8af49d5c994d04a
[ "MIT" ]
null
null
null
yatube/posts/admin.py
Apocalyptic434/hw02_community
04e105d6ed2f76c4b1bb08b7c8af49d5c994d04a
[ "MIT" ]
null
null
null
yatube/posts/admin.py
Apocalyptic434/hw02_community
04e105d6ed2f76c4b1bb08b7c8af49d5c994d04a
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import Group, Post @admin.register(Group) class GroupAdmin(admin.ModelAdmin): pass @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('pk', 'text', 'pub_date', 'author', 'group',) list_editable = ('group',) search_fields = ('text',) list_filter = ('pub_date',) empty_value_display = '-пусто-' pass # так ? Без этого flake8 ругается
22.842105
65
0.679724
795a389312a38eff8fb58a601fdae8cab19b2883
118,814
py
Python
keras/layers/convolutional.py
mdand2000/keras-team-keras
5eecd55a6f1d6d149b42f9b76aa53d4c5ab8d3eb
[ "MIT" ]
2
2019-09-17T22:01:41.000Z
2020-05-30T05:48:14.000Z
keras/layers/convolutional.py
mdand2000/keras-team-keras
5eecd55a6f1d6d149b42f9b76aa53d4c5ab8d3eb
[ "MIT" ]
null
null
null
keras/layers/convolutional.py
mdand2000/keras-team-keras
5eecd55a6f1d6d149b42f9b76aa53d4c5ab8d3eb
[ "MIT" ]
3
2019-08-12T18:15:17.000Z
2021-06-20T19:40:13.000Z
# -*- coding: utf-8 -*- """Convolutional layers. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from .. import backend as K from .. import activations from .. import initializers from .. import regularizers from .. import constraints from ..engine.base_layer import Layer from ..engine.base_layer import InputSpec from ..utils import conv_utils from ..legacy import interfaces # imports for backwards namespace compatibility from .pooling import AveragePooling1D from .pooling import AveragePooling2D from .pooling import AveragePooling3D from .pooling import MaxPooling1D from .pooling import MaxPooling2D from .pooling import MaxPooling3D from ..legacy.layers import AtrousConvolution1D from ..legacy.layers import AtrousConvolution2D class _Conv(Layer): """Abstract nD convolution layer (private, used as implementation base). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. # Arguments rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of n integers, specifying the dimensions of the convolution window. strides: An integer or tuple/list of n integers, specifying the strides of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, ..., channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, ...)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: An integer or tuple/list of n integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(_Conv, self).__init__(**kwargs) self.rank = rank self.filters = filters self.kernel_size = conv_utils.normalize_tuple(kernel_size, rank, 'kernel_size') self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') self.padding = conv_utils.normalize_padding(padding) self.data_format = conv_utils.normalize_data_format(data_format) self.dilation_rate = conv_utils.normalize_tuple(dilation_rate, rank, 'dilation_rate') self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.input_spec = InputSpec(ndim=self.rank + 2) def build(self, input_shape): if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = input_shape[channel_axis] kernel_shape = self.kernel_size + (input_dim, self.filters) self.kernel = self.add_weight(shape=kernel_shape, initializer=self.kernel_initializer, name='kernel', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) if self.use_bias: self.bias = self.add_weight(shape=(self.filters,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): if self.rank == 1: outputs = K.conv1d( inputs, self.kernel, strides=self.strides[0], padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate[0]) if self.rank == 2: outputs = K.conv2d( inputs, self.kernel, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if self.rank == 3: outputs = K.conv3d( inputs, self.kernel, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if self.use_bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): if self.data_format == 'channels_last': space = input_shape[1:-1] new_space = [] for i in range(len(space)): new_dim = conv_utils.conv_output_length( space[i], self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i]) new_space.append(new_dim) return (input_shape[0],) + tuple(new_space) + (self.filters,) if self.data_format == 'channels_first': space = input_shape[2:] new_space = [] for i in range(len(space)): new_dim = conv_utils.conv_output_length( space[i], self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i]) new_space.append(new_dim) return (input_shape[0], self.filters) + tuple(new_space) def get_config(self): config = { 'rank': self.rank, 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(_Conv, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Conv1D(_Conv): """1D convolution layer (e.g. temporal convolution). This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide an `input_shape` argument (tuple of integers or `None`, e.g. `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors, or `(None, 128)` for variable-length sequences of 128-dimensional vectors. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of a single integer, specifying the length of the 1D convolution window. strides: An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"causal"` or `"same"` (case-insensitive). `"valid"` means "no padding". `"same"` results in padding the input such that the output has the same length as the original input. `"causal"` results in causal (dilated) convolutions, e.g. output[t] does not depend on input[t+1:]. Useful when modeling temporal data where the model should not violate the temporal order. See [WaveNet: A Generative Model for Raw Audio, section 2.1](https://arxiv.org/abs/1609.03499). data_format: A string, one of `"channels_last"` (default) or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, length, channels)` (default format for temporal data in Keras) while `"channels_first"` corresponds to inputs with shape `(batch, channels, length)`. dilation_rate: an integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 3D tensor with shape: `(batch_size, steps, input_dim)` # Output shape 3D tensor with shape: `(batch_size, new_steps, filters)` `steps` value might have changed due to padding or strides. """ @interfaces.legacy_conv1d_support def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): if padding == 'causal': if data_format != 'channels_last': raise ValueError('When using causal padding in `Conv1D`, ' '`data_format` must be "channels_last" ' '(temporal data).') super(Conv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.input_spec = InputSpec(ndim=3) def get_config(self): config = super(Conv1D, self).get_config() config.pop('rank') return config class Conv2D(_Conv): """2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). Note that `"same"` is slightly inconsistent across backends with `strides` != 1, as described [here](https://github.com/keras-team/keras/pull/9473#issuecomment-372166860) data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(samples, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `(samples, filters, new_rows, new_cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(samples, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. """ @interfaces.legacy_conv2d_support def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.input_spec = InputSpec(ndim=4) def get_config(self): config = super(Conv2D, self).get_config() config.pop('rank') return config class Conv3D(_Conv): """3D convolution layer (e.g. spatial convolution over volumes). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes with a single channel, in `data_format="channels_last"`. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along each spatial dimension. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 5D tensor with shape: `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if `data_format` is `"channels_first"` or 5D tensor with shape: `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if `data_format` is `"channels_last"`. # Output shape 5D tensor with shape: `(samples, filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if `data_format` is `"channels_first"` or 5D tensor with shape: `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, filters)` if `data_format` is `"channels_last"`. `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding. """ @interfaces.legacy_conv3d_support def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3D, self).__init__( rank=3, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.input_spec = InputSpec(ndim=5) def get_config(self): config = super(Conv3D, self).get_config() config.pop('rank') return config class Conv2DTranspose(Conv2D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 4D tensor with shape: `(batch, channels, rows, cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. # References - [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf) """ @interfaces.legacy_deconv2d_support def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2DTranspose, self).__init__( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.input_spec = InputSpec(ndim=4) def build(self, input_shape): if len(input_shape) != 4: raise ValueError('Inputs should have rank ' + str(4) + '; Received input shape:', str(input_shape)) if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = input_shape[channel_axis] kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight(shape=kernel_shape, initializer=self.kernel_initializer, name='kernel', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) if self.use_bias: self.bias = self.add_weight(shape=(self.filters,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): input_shape = K.shape(inputs) batch_size = input_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 height, width = input_shape[h_axis], input_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides # Infer the dynamic output shape: out_height = conv_utils.deconv_length(height, stride_h, kernel_h, self.padding) out_width = conv_utils.deconv_length(width, stride_w, kernel_w, self.padding) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) outputs = K.conv2d_transpose( inputs, self.kernel, output_shape, self.strides, padding=self.padding, data_format=self.data_format) if self.bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, h_axis, w_axis = 1, 2, 3 else: c_axis, h_axis, w_axis = 3, 1, 2 kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides output_shape[c_axis] = self.filters output_shape[h_axis] = conv_utils.deconv_length( output_shape[h_axis], stride_h, kernel_h, self.padding) output_shape[w_axis] = conv_utils.deconv_length( output_shape[w_axis], stride_w, kernel_w, self.padding) return tuple(output_shape) def get_config(self): config = super(Conv2DTranspose, self).get_config() config.pop('dilation_rate') return config class Conv3DTranspose(Conv3D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels if `data_format="channels_last"`. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 3 integers, specifying the height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, depth, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). kernel_constraint: Constraint function applied to the kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 5D tensor with shape: `(batch, channels, depth, rows, cols)` if `data_format` is `"channels_first"` or 5D tensor with shape: `(batch, depth, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 5D tensor with shape: `(batch, filters, new_depth, new_rows, new_cols)` if `data_format` is `"channels_first"` or 5D tensor with shape: `(batch, new_depth, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `depth` and `rows` and `cols` values might have changed due to padding. # References - [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf) """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3DTranspose, self).__init__( filters, kernel_size, strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, kernel_constraint=kernel_constraint, bias_constraint=bias_constraint, **kwargs) self.input_spec = InputSpec(ndim=5) def build(self, input_shape): if len(input_shape) != 5: raise ValueError('Inputs should have rank ' + str(5) + '; Received input shape:', str(input_shape)) if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = -1 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = input_shape[channel_axis] kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight(shape=kernel_shape, initializer=self.kernel_initializer, name='kernel', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) if self.use_bias: self.bias = self.add_weight(shape=(self.filters,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): input_shape = K.shape(inputs) batch_size = input_shape[0] if self.data_format == 'channels_first': d_axis, h_axis, w_axis = 2, 3, 4 else: d_axis, h_axis, w_axis = 1, 2, 3 depth = input_shape[d_axis] height = input_shape[h_axis] width = input_shape[w_axis] kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides # Infer the dynamic output shape: out_depth = conv_utils.deconv_length(depth, stride_d, kernel_d, self.padding) out_height = conv_utils.deconv_length(height, stride_h, kernel_h, self.padding) out_width = conv_utils.deconv_length(width, stride_w, kernel_w, self.padding) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_depth, out_height, out_width) else: output_shape = (batch_size, out_depth, out_height, out_width, self.filters) outputs = K.conv3d_transpose(inputs, self.kernel, output_shape, self.strides, padding=self.padding, data_format=self.data_format) if self.bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4 else: c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3 kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides output_shape[c_axis] = self.filters output_shape[d_axis] = conv_utils.deconv_length(output_shape[d_axis], stride_d, kernel_d, self.padding) output_shape[h_axis] = conv_utils.deconv_length(output_shape[h_axis], stride_h, kernel_h, self.padding) output_shape[w_axis] = conv_utils.deconv_length(output_shape[w_axis], stride_w, kernel_w, self.padding) return tuple(output_shape) def get_config(self): config = super(Conv3DTranspose, self).get_config() config.pop('dilation_rate') return config class _SeparableConv(_Conv): """Abstract nD depthwise separable convolution layer (private). Separable convolutions consist in first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes together the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. # Arguments rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of n integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix (see [initializers](../initializers.md)). pointwise_initializer: Initializer for the pointwise kernel matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see [regularizer](../regularizers.md)). pointwise_regularizer: Regularizer function applied to the pointwise kernel matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). depthwise_constraint: Constraint function applied to the depthwise kernel matrix (see [constraints](../constraints.md)). pointwise_constraint: Constraint function applied to the pointwise kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 4D tensor with shape: `(batch, channels, rows, cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(_SeparableConv, self).__init__( rank=rank, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, bias_constraint=bias_constraint, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.pointwise_initializer = initializers.get(pointwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.pointwise_regularizer = regularizers.get(pointwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.pointwise_constraint = constraints.get(pointwise_constraint) def build(self, input_shape): if len(input_shape) < self.rank + 2: raise ValueError('Inputs to `SeparableConv' + str(self.rank) + 'D` ' 'should have rank ' + str(self.rank + 2) + '. ' 'Received input shape:', str(input_shape)) channel_axis = 1 if self.data_format == 'channels_first' else -1 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) depthwise_kernel_shape = self.kernel_size + (input_dim, self.depth_multiplier) pointwise_kernel_shape = (1,) * self.rank + (self.depth_multiplier * input_dim, self.filters) self.depthwise_kernel = self.add_weight( shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, name='depthwise_kernel', regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint) self.pointwise_kernel = self.add_weight( shape=pointwise_kernel_shape, initializer=self.pointwise_initializer, name='pointwise_kernel', regularizer=self.pointwise_regularizer, constraint=self.pointwise_constraint) if self.use_bias: self.bias = self.add_weight(shape=(self.filters,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): if self.rank == 1: outputs = K.separable_conv1d( inputs, self.depthwise_kernel, self.pointwise_kernel, data_format=self.data_format, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate) if self.rank == 2: outputs = K.separable_conv2d( inputs, self.depthwise_kernel, self.pointwise_kernel, data_format=self.data_format, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate) if self.bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def get_config(self): config = super(_SeparableConv, self).get_config() config.pop('rank') config.pop('kernel_initializer') config.pop('kernel_regularizer') config.pop('kernel_constraint') config['depth_multiplier'] = self.depth_multiplier config['depthwise_initializer'] = initializers.serialize(self.depthwise_initializer) config['pointwise_initializer'] = initializers.serialize(self.pointwise_initializer) config['depthwise_regularizer'] = regularizers.serialize(self.depthwise_regularizer) config['pointwise_regularizer'] = regularizers.serialize(self.pointwise_regularizer) config['depthwise_constraint'] = constraints.serialize(self.depthwise_constraint) config['pointwise_constraint'] = constraints.serialize(self.pointwise_constraint) return config class SeparableConv1D(_SeparableConv): """Depthwise separable 1D convolution. Separable convolutions consist in first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes together the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of single integer, specifying the length of the 1D convolution window. strides: An integer or tuple/list of single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: An integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix (see [initializers](../initializers.md)). pointwise_initializer: Initializer for the pointwise kernel matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see [regularizer](../regularizers.md)). pointwise_regularizer: Regularizer function applied to the pointwise kernel matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). depthwise_constraint: Constraint function applied to the depthwise kernel matrix (see [constraints](../constraints.md)). pointwise_constraint: Constraint function applied to the pointwise kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 3D tensor with shape: `(batch, channels, steps)` if `data_format` is `"channels_first"` or 3D tensor with shape: `(batch, steps, channels)` if `data_format` is `"channels_last"`. # Output shape 3D tensor with shape: `(batch, filters, new_steps)` if `data_format` is `"channels_first"` or 3D tensor with shape: `(batch, new_steps, filters)` if `data_format` is `"channels_last"`. `new_steps` values might have changed due to padding or strides. """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activation, use_bias=use_bias, depthwise_initializer=depthwise_initializer, pointwise_initializer=pointwise_initializer, bias_initializer=bias_initializer, depthwise_regularizer=depthwise_regularizer, pointwise_regularizer=pointwise_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, depthwise_constraint=depthwise_constraint, pointwise_constraint=pointwise_constraint, bias_constraint=bias_constraint, **kwargs) class SeparableConv2D(_SeparableConv): """Depthwise separable 2D convolution. Separable convolutions consist in first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes together the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. # Arguments filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix (see [initializers](../initializers.md)). pointwise_initializer: Initializer for the pointwise kernel matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see [regularizer](../regularizers.md)). pointwise_regularizer: Regularizer function applied to the pointwise kernel matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see [regularizer](../regularizers.md)). depthwise_constraint: Constraint function applied to the depthwise kernel matrix (see [constraints](../constraints.md)). pointwise_constraint: Constraint function applied to the pointwise kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 4D tensor with shape: `(batch, channels, rows, cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, rows, cols, channels)` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `(batch, filters, new_rows, new_cols)` if `data_format` is `"channels_first"` or 4D tensor with shape: `(batch, new_rows, new_cols, filters)` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. """ @interfaces.legacy_separable_conv2d_support def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activation, use_bias=use_bias, depthwise_initializer=depthwise_initializer, pointwise_initializer=pointwise_initializer, bias_initializer=bias_initializer, depthwise_regularizer=depthwise_regularizer, pointwise_regularizer=pointwise_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, depthwise_constraint=depthwise_constraint, pointwise_constraint=pointwise_constraint, bias_constraint=bias_constraint, **kwargs) class DepthwiseConv2D(Conv2D): """Depthwise separable 2D convolution. Depthwise Separable convolutions consists in performing just the first step in a depthwise spatial convolution (which acts on each input channel separately). The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. # Arguments kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `'valid'` or `'same'` (case-insensitive). depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be 'channels_last'. activation: Activation function to use (see [activations](../activations.md)). If you don't specify anything, no activation is applied (ie. 'linear' activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix (see [initializers](../initializers.md)). bias_initializer: Initializer for the bias vector (see [initializers](../initializers.md)). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see [regularizer](../regularizers.md)). bias_regularizer: Regularizer function applied to the bias vector (see [regularizer](../regularizers.md)). activity_regularizer: Regularizer function applied to the output of the layer (its 'activation'). (see [regularizer](../regularizers.md)). depthwise_constraint: Constraint function applied to the depthwise kernel matrix (see [constraints](../constraints.md)). bias_constraint: Constraint function applied to the bias vector (see [constraints](../constraints.md)). # Input shape 4D tensor with shape: `[batch, channels, rows, cols]` if `data_format` is `"channels_first"` or 4D tensor with shape: `[batch, rows, cols, channels]` if `data_format` is `"channels_last"`. # Output shape 4D tensor with shape: `[batch, filters, new_rows, new_cols]` if `data_format` is `"channels_first"` or 4D tensor with shape: `[batch, new_rows, new_cols, filters]` if `data_format` is `"channels_last"`. `rows` and `cols` values might have changed due to padding. """ def __init__(self, kernel_size, strides=(1, 1), padding='valid', depth_multiplier=1, data_format=None, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs): super(DepthwiseConv2D, self).__init__( filters=None, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, activation=activation, use_bias=use_bias, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, bias_constraint=bias_constraint, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.bias_initializer = initializers.get(bias_initializer) def build(self, input_shape): if len(input_shape) < 4: raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' 'Received input shape:', str(input_shape)) if self.data_format == 'channels_first': channel_axis = 1 else: channel_axis = 3 if input_shape[channel_axis] is None: raise ValueError('The channel dimension of the inputs to ' '`DepthwiseConv2D` ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) depthwise_kernel_shape = (self.kernel_size[0], self.kernel_size[1], input_dim, self.depth_multiplier) self.depthwise_kernel = self.add_weight( shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, name='depthwise_kernel', regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint) if self.use_bias: self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) self.built = True def call(self, inputs, training=None): outputs = K.depthwise_conv2d( inputs, self.depthwise_kernel, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate, data_format=self.data_format) if self.bias: outputs = K.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] out_filters = input_shape[1] * self.depth_multiplier elif self.data_format == 'channels_last': rows = input_shape[1] cols = input_shape[2] out_filters = input_shape[3] * self.depth_multiplier rows = conv_utils.conv_output_length(rows, self.kernel_size[0], self.padding, self.strides[0]) cols = conv_utils.conv_output_length(cols, self.kernel_size[1], self.padding, self.strides[1]) if self.data_format == 'channels_first': return (input_shape[0], out_filters, rows, cols) elif self.data_format == 'channels_last': return (input_shape[0], rows, cols, out_filters) def get_config(self): config = super(DepthwiseConv2D, self).get_config() config.pop('filters') config.pop('kernel_initializer') config.pop('kernel_regularizer') config.pop('kernel_constraint') config['depth_multiplier'] = self.depth_multiplier config['depthwise_initializer'] = initializers.serialize(self.depthwise_initializer) config['depthwise_regularizer'] = regularizers.serialize(self.depthwise_regularizer) config['depthwise_constraint'] = constraints.serialize(self.depthwise_constraint) return config class UpSampling1D(Layer): """Upsampling layer for 1D inputs. Repeats each temporal step `size` times along the time axis. # Arguments size: integer. Upsampling factor. # Input shape 3D tensor with shape: `(batch, steps, features)`. # Output shape 3D tensor with shape: `(batch, upsampled_steps, features)`. """ @interfaces.legacy_upsampling1d_support def __init__(self, size=2, **kwargs): super(UpSampling1D, self).__init__(**kwargs) self.size = int(size) self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): size = self.size * input_shape[1] if input_shape[1] is not None else None return (input_shape[0], size, input_shape[2]) def call(self, inputs): output = K.repeat_elements(inputs, self.size, axis=1) return output def get_config(self): config = {'size': self.size} base_config = super(UpSampling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class UpSampling2D(Layer): """Upsampling layer for 2D inputs. Repeats the rows and columns of the data by size[0] and size[1] respectively. # Arguments size: int, or tuple of 2 integers. The upsampling factors for rows and columns. data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, rows, cols)` # Output shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, upsampled_rows, upsampled_cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, upsampled_rows, upsampled_cols)` """ @interfaces.legacy_upsampling2d_support def __init__(self, size=(2, 2), data_format=None, **kwargs): super(UpSampling2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 2, 'size') self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': height = self.size[0] * input_shape[2] if input_shape[2] is not None else None width = self.size[1] * input_shape[3] if input_shape[3] is not None else None return (input_shape[0], input_shape[1], height, width) elif self.data_format == 'channels_last': height = self.size[0] * input_shape[1] if input_shape[1] is not None else None width = self.size[1] * input_shape[2] if input_shape[2] is not None else None return (input_shape[0], height, width, input_shape[3]) def call(self, inputs): return K.resize_images(inputs, self.size[0], self.size[1], self.data_format) def get_config(self): config = {'size': self.size, 'data_format': self.data_format} base_config = super(UpSampling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class UpSampling3D(Layer): """Upsampling layer for 3D inputs. Repeats the 1st, 2nd and 3rd dimensions of the data by size[0], size[1] and size[2] respectively. # Arguments size: int, or tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3. data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, dim1, dim2, dim3, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, dim1, dim2, dim3)` # Output shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` """ @interfaces.legacy_upsampling3d_support def __init__(self, size=(2, 2, 2), data_format=None, **kwargs): self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 3, 'size') self.input_spec = InputSpec(ndim=5) super(UpSampling3D, self).__init__(**kwargs) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': dim1 = self.size[0] * input_shape[2] if input_shape[2] is not None else None dim2 = self.size[1] * input_shape[3] if input_shape[3] is not None else None dim3 = self.size[2] * input_shape[4] if input_shape[4] is not None else None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.data_format == 'channels_last': dim1 = self.size[0] * input_shape[1] if input_shape[1] is not None else None dim2 = self.size[1] * input_shape[2] if input_shape[2] is not None else None dim3 = self.size[2] * input_shape[3] if input_shape[3] is not None else None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) def call(self, inputs): return K.resize_volumes(inputs, self.size[0], self.size[1], self.size[2], self.data_format) def get_config(self): config = {'size': self.size, 'data_format': self.data_format} base_config = super(UpSampling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding1D(Layer): """Zero-padding layer for 1D input (e.g. temporal sequence). # Arguments padding: int, or tuple of int (length 2), or dictionary. - If int: How many zeros to add at the beginning and end of the padding dimension (axis 1). - If tuple of int (length 2): How many zeros to add at the beginning and at the end of the padding dimension (`(left_pad, right_pad)`). # Input shape 3D tensor with shape `(batch, axis_to_pad, features)` # Output shape 3D tensor with shape `(batch, padded_axis, features)` """ def __init__(self, padding=1, **kwargs): super(ZeroPadding1D, self).__init__(**kwargs) self.padding = conv_utils.normalize_tuple(padding, 2, 'padding') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): if input_shape[1] is not None: length = input_shape[1] + self.padding[0] + self.padding[1] else: length = None return (input_shape[0], length, input_shape[2]) def call(self, inputs): return K.temporal_padding(inputs, padding=self.padding) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding2D(Layer): """Zero-padding layer for 2D input (e.g. picture). This layer can add rows and columns of zeros at the top, bottom, left and right side of an image tensor. # Arguments padding: int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_height_pad, symmetric_width_pad)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_pad, bottom_pad), (left_pad, right_pad))` data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, rows, cols)` # Output shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, padded_rows, padded_cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, padded_rows, padded_cols)` """ @interfaces.legacy_zeropadding2d_support def __init__(self, padding=(1, 1), data_format=None, **kwargs): super(ZeroPadding2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 2: raise ValueError('`padding` should have two elements. ' 'Found: ' + str(padding)) height_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') width_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') self.padding = (height_padding, width_padding) else: raise ValueError('`padding` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_pad, symmetric_width_pad), ' 'or a tuple of 2 tuples of 2 ints ' '((top_pad, bottom_pad), (left_pad, right_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': if input_shape[2] is not None: rows = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[3] is not None: cols = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: cols = None return (input_shape[0], input_shape[1], rows, cols) elif self.data_format == 'channels_last': if input_shape[1] is not None: rows = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[2] is not None: cols = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: cols = None return (input_shape[0], rows, cols, input_shape[3]) def call(self, inputs): return K.spatial_2d_padding(inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class ZeroPadding3D(Layer): """Zero-padding layer for 3D data (spatial or spatio-temporal). # Arguments padding: int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 3 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_pad, right_dim1_pad), (left_dim2_pad, right_dim2_pad), (left_dim3_pad, right_dim3_pad))` data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch, depth, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad)` # Output shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, first_padded_axis, second_padded_axis, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch, depth, first_padded_axis, second_padded_axis, third_axis_to_pad)` """ @interfaces.legacy_zeropadding3d_support def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): super(ZeroPadding3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 3: raise ValueError('`padding` should have 3 elements. ' 'Found: ' + str(padding)) dim1_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') dim2_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') dim3_padding = conv_utils.normalize_tuple(padding[2], 2, '3rd entry of padding') self.padding = (dim1_padding, dim2_padding, dim3_padding) else: raise ValueError('`padding` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_pad, right_dim1_pad),' ' (left_dim2_pad, right_dim2_pad),' ' (left_dim3_pad, right_dim2_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] + self.padding[2][0] + self.padding[2][1] else: dim3 = None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] + self.padding[2][0] + self.padding[2][1] else: dim3 = None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) def call(self, inputs): return K.spatial_3d_padding(inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping1D(Layer): """Cropping layer for 1D input (e.g. temporal sequence). It crops along the time dimension (axis 1). # Arguments cropping: int or tuple of int (length 2) How many units should be trimmed off at the beginning and end of the cropping dimension (axis 1). If a single int is provided, the same value will be used for both. # Input shape 3D tensor with shape `(batch, axis_to_crop, features)` # Output shape 3D tensor with shape `(batch, cropped_axis, features)` """ def __init__(self, cropping=(1, 1), **kwargs): super(Cropping1D, self).__init__(**kwargs) self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): if input_shape[1] is not None: length = input_shape[1] - self.cropping[0] - self.cropping[1] else: length = None return (input_shape[0], length, input_shape[2]) def call(self, inputs): if self.cropping[1] == 0: return inputs[:, self.cropping[0]:, :] else: return inputs[:, self.cropping[0]: -self.cropping[1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping2D(Layer): """Cropping layer for 2D input (e.g. picture). It crops along spatial dimensions, i.e. height and width. # Arguments cropping: int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric cropping is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric cropping values for height and width: `(symmetric_height_crop, symmetric_width_crop)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_crop, bottom_crop), (left_crop, right_crop))` data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, rows, cols)` # Output shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, cropped_rows, cropped_cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, cropped_rows, cropped_cols)` # Examples ```python # Crop the input 2D images or feature maps model = Sequential() model.add(Cropping2D(cropping=((2, 2), (4, 4)), input_shape=(28, 28, 3))) # now model.output_shape == (None, 24, 20, 3) model.add(Conv2D(64, (3, 3), padding='same')) model.add(Cropping2D(cropping=((2, 2), (2, 2)))) # now model.output_shape == (None, 20, 16. 64) ``` """ @interfaces.legacy_cropping2d_support def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): super(Cropping2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 2: raise ValueError('`cropping` should have two elements. ' 'Found: ' + str(cropping)) height_cropping = conv_utils.normalize_tuple( cropping[0], 2, '1st entry of cropping') width_cropping = conv_utils.normalize_tuple( cropping[1], 2, '2nd entry of cropping') self.cropping = (height_cropping, width_cropping) else: raise ValueError('`cropping` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_crop, symmetric_width_crop), ' 'or a tuple of 2 tuples of 2 ints ' '((top_crop, bottom_crop), (left_crop, right_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': return (input_shape[0], input_shape[1], input_shape[2] - self.cropping[0][0] - self.cropping[0][1] if input_shape[2] else None, input_shape[3] - self.cropping[1][0] - self.cropping[1][1] if input_shape[3] else None) elif self.data_format == 'channels_last': return (input_shape[0], input_shape[1] - self.cropping[0][0] - self.cropping[0][1] if input_shape[1] else None, input_shape[2] - self.cropping[1][0] - self.cropping[1][1] if input_shape[2] else None, input_shape[3]) def call(self, inputs): if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:] return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1]] elif self.data_format == 'channels_last': if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:, :] return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1], :] def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Cropping3D(Layer): """Cropping layer for 3D data (e.g. spatial or spatio-temporal). # Arguments cropping: int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric cropping is applied to depth, height, and width. - If tuple of 3 ints: interpreted as two different symmetric cropping values for depth, height, and width: `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_crop, right_dim1_crop), (left_dim2_crop, right_dim2_crop), (left_dim3_crop, right_dim3_crop))` data_format: A string, one of `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop, depth)` - If `data_format` is `"channels_first"`: `(batch, depth, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop)` # Output shape 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, first_cropped_axis, second_cropped_axis, third_cropped_axis, depth)` - If `data_format` is `"channels_first"`: `(batch, depth, first_cropped_axis, second_cropped_axis, third_cropped_axis)` """ @interfaces.legacy_cropping3d_support def __init__(self, cropping=((1, 1), (1, 1), (1, 1)), data_format=None, **kwargs): super(Cropping3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 3: raise ValueError('`cropping` should have 3 elements. ' 'Found: ' + str(cropping)) dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2, '3rd entry of cropping') self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping) else: raise ValueError('`cropping` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_crop, right_dim1_crop),' ' (left_dim2_crop, right_dim2_crop),' ' (left_dim3_crop, right_dim2_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return (input_shape[0], input_shape[1], dim1, dim2, dim3) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return (input_shape[0], dim1, dim2, dim3, input_shape[4]) def call(self, inputs): if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1]] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1]] elif self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:] return inputs[:, :, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1]] elif self.data_format == 'channels_last': if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:, :] return inputs[:, self.cropping[0][0]: -self.cropping[0][1], self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Aliases Convolution1D = Conv1D Convolution2D = Conv2D Convolution3D = Conv3D SeparableConvolution1D = SeparableConv1D SeparableConvolution2D = SeparableConv2D Convolution2DTranspose = Conv2DTranspose Deconvolution2D = Deconv2D = Conv2DTranspose Deconvolution3D = Deconv3D = Conv3DTranspose # Legacy aliases AtrousConv1D = AtrousConvolution1D AtrousConv2D = AtrousConvolution2D
44.835472
123
0.577541
795a3905e70de94d67bfa6ebd9b0dd4c12b195ea
81
py
Python
cvk/apps.py
cvk007/ML_Model
8437257cc84c7a0ac42e7b6728431494f145882b
[ "MIT" ]
null
null
null
cvk/apps.py
cvk007/ML_Model
8437257cc84c7a0ac42e7b6728431494f145882b
[ "MIT" ]
null
null
null
cvk/apps.py
cvk007/ML_Model
8437257cc84c7a0ac42e7b6728431494f145882b
[ "MIT" ]
null
null
null
from django.apps import AppConfig class CvkConfig(AppConfig): name = 'cvk'
13.5
33
0.728395
795a3a6caa5ae5b7e488b465f0707922ca3b00a7
3,415
py
Python
tools/pot/openvino/tools/pot/graph/graph_utils.py
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
1
2021-02-01T06:35:55.000Z
2021-02-01T06:35:55.000Z
tools/pot/openvino/tools/pot/graph/graph_utils.py
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
58
2020-11-06T12:13:45.000Z
2022-03-28T13:20:11.000Z
tools/pot/openvino/tools/pot/graph/graph_utils.py
maindude111/openvino
c23025dfd2e3da57981e7fc7328074e3895759ea
[ "Apache-2.0" ]
1
2021-02-15T01:13:57.000Z
2021-02-15T01:13:57.000Z
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import tempfile from copy import deepcopy from openvino.tools.mo.graph.graph import Graph from openvino.tools.mo.utils.ir_reader.restore_graph import restore_graph_from_ir, save_restored_graph from openvino.tools.mo.utils.logger import init_logger from openvino.inference_engine import IECore # pylint: disable=E0611 from openvino.offline_transformations import ApplyPOTTransformations # pylint: disable=import-error,no-name-in-module from ..graph.passes import ModelPreprocessor, remove_converts, add_removed_converts from ..utils.logger import stdout_redirect init_logger('ERROR', False) ie = IECore() def load_graph(model_config, target_device='ANY'): """ Loads model from specified path :return NetworkX model """ special_transform_devices = ['GNA'] serialized_bin_path = os.path.join(tempfile.gettempdir(), 'serialized_ir.bin') serialized_xml_path = os.path.join(tempfile.gettempdir(), 'serialized_ir.xml') bin_path = model_config.weights xml_path = model_config.model if target_device in special_transform_devices: network = ie.read_network(model=xml_path, weights=bin_path) ApplyPOTTransformations(network, target_device.encode('utf-8')) bin_path = serialized_bin_path xml_path = serialized_xml_path network.serialize(xml_path, bin_path) if not os.path.exists(xml_path): raise RuntimeError('Input model xml should link to an existing file. Please, provide a correct path.') if not os.path.exists(bin_path): raise RuntimeError('Input model bin should link to an existing file. Please, provide a correct path.') graph_from_ir, meta_data = stdout_redirect(restore_graph_from_ir, xml_path, bin_path) orig_graph_from_ir, meta_data = stdout_redirect(restore_graph_from_ir, model_config.model, model_config.weights) meta_data['quantization_parameters'] = model_config.quantization_info graph_from_ir.meta_data = meta_data graph_from_ir.ir_v10 = True graph_from_ir.graph['cmd_params'] = orig_graph_from_ir.graph['cmd_params'] remove_converts(graph_from_ir) model_preprocessing(graph_from_ir) if os.path.exists(serialized_xml_path): os.remove(serialized_xml_path) if os.path.exists(serialized_bin_path): os.remove(serialized_bin_path) return graph_from_ir def save_graph(graph: Graph, save_path, model_name=None): """ Save model as IR in specified path :param graph: NetworkX model to save :param save_path: path to save the model :param model_name: name under which the model will be saved """ if not os.path.exists(save_path): try: os.makedirs(save_path) except PermissionError as e: raise type(e)( 'Failed to create a directory {}. Permission denied. '.format(save_path)) else: if not os.access(save_path, os.W_OK): raise PermissionError( 'Output directory {} is not writable for the current user. '.format(save_path)) graph_copy = deepcopy(graph) add_removed_converts(graph_copy) save_restored_graph(graph=graph_copy, path=save_path, meta_data=graph.meta_data, name=model_name) def model_preprocessing(model): ModelPreprocessor().find_and_replace_pattern(model) model.clean_up()
40.654762
118
0.738507
795a3a7443236be65b274f11e4a326c064a0662a
192
py
Python
sqlite-view.py
tbaschak/hpkp-pinfail
afdb0cce1586bbc195c472ec5a03597f3bd3f822
[ "MIT" ]
1
2016-04-17T09:49:33.000Z
2016-04-17T09:49:33.000Z
sqlite-view.py
tbaschak/hpkp-pinfail
afdb0cce1586bbc195c472ec5a03597f3bd3f822
[ "MIT" ]
null
null
null
sqlite-view.py
tbaschak/hpkp-pinfail
afdb0cce1586bbc195c472ec5a03597f3bd3f822
[ "MIT" ]
null
null
null
#!/usr/bin/env python import sqlite3 conn = sqlite3.connect('hpkp.sqlite') c = conn.cursor() # Create table for row in c.execute('''SELECT * FROM reports'''): print row conn.close()
14.769231
50
0.666667
795a3ab858c7c5243577f55a2e16559b2804e47d
10,097
py
Python
test/test_state_network_size_request.py
vericred/vericred-python
be45691c821a595c3d77a561b2ca33049b1239b4
[ "Apache-2.0" ]
3
2016-08-10T23:39:11.000Z
2021-08-25T02:39:39.000Z
test/test_state_network_size_request.py
vericred/vericred-python
be45691c821a595c3d77a561b2ca33049b1239b4
[ "Apache-2.0" ]
2
2016-05-27T12:44:08.000Z
2016-08-24T18:19:36.000Z
test/test_state_network_size_request.py
vericred/vericred-python
be45691c821a595c3d77a561b2ca33049b1239b4
[ "Apache-2.0" ]
4
2016-05-27T08:18:14.000Z
2021-08-25T02:41:18.000Z
# coding: utf-8 """ Vericred API Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,states.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` root ::= coverage coverage ::= (simple_coverage | tiered_coverage) (space pipe space coverage_modifier)? tiered_coverage ::= tier (space slash space tier)* tier ::= tier_name colon space (tier_coverage | not_applicable) tier_coverage ::= simple_coverage (space (then | or | and) space simple_coverage)* tier_limitation? simple_coverage ::= (pre_coverage_limitation space)? coverage_amount (space post_coverage_limitation)? (comma? space coverage_condition)? coverage_modifier ::= limit_condition colon space (((simple_coverage | simple_limitation) (semicolon space see_carrier_documentation)?) | see_carrier_documentation | waived_if_admitted | shared_across_tiers) waived_if_admitted ::= ("copay" space)? "waived if admitted" simple_limitation ::= pre_coverage_limitation space "copay applies" tier_name ::= "In-Network-Tier-2" | "Out-of-Network" | "In-Network" limit_condition ::= "limit" | "condition" tier_limitation ::= comma space "up to" space (currency | (integer space time_unit plural?)) (space post_coverage_limitation)? coverage_amount ::= currency | unlimited | included | unknown | percentage | (digits space (treatment_unit | time_unit) plural?) pre_coverage_limitation ::= first space digits space time_unit plural? post_coverage_limitation ::= (((then space currency) | "per condition") space)? "per" space (treatment_unit | (integer space time_unit) | time_unit) plural? coverage_condition ::= ("before deductible" | "after deductible" | "penalty" | allowance | "in-state" | "out-of-state") (space allowance)? allowance ::= upto_allowance | after_allowance upto_allowance ::= "up to" space (currency space)? "allowance" after_allowance ::= "after" space (currency space)? "allowance" see_carrier_documentation ::= "see carrier documentation for more information" shared_across_tiers ::= "shared across all tiers" unknown ::= "unknown" unlimited ::= /[uU]nlimited/ included ::= /[iI]ncluded in [mM]edical/ time_unit ::= /[hH]our/ | (((/[cC]alendar/ | /[cC]ontract/) space)? /[yY]ear/) | /[mM]onth/ | /[dD]ay/ | /[wW]eek/ | /[vV]isit/ | /[lL]ifetime/ | ((((/[bB]enefit/ plural?) | /[eE]ligibility/) space)? /[pP]eriod/) treatment_unit ::= /[pP]erson/ | /[gG]roup/ | /[cC]ondition/ | /[sS]cript/ | /[vV]isit/ | /[eE]xam/ | /[iI]tem/ | /[sS]tay/ | /[tT]reatment/ | /[aA]dmission/ | /[eE]pisode/ comma ::= "," colon ::= ":" semicolon ::= ";" pipe ::= "|" slash ::= "/" plural ::= "(s)" | "s" then ::= "then" | ("," space) | space or ::= "or" and ::= "and" not_applicable ::= "Not Applicable" | "N/A" | "NA" first ::= "first" currency ::= "$" number percentage ::= number "%" number ::= float | integer float ::= digits "." digits integer ::= /[0-9]/+ (comma_int | under_int)* comma_int ::= ("," /[0-9]/*3) !"_" under_int ::= ("_" /[0-9]/*3) !"," digits ::= /[0-9]/+ ("_" /[0-9]/+)* space ::= /[ \t]/+ ``` OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import os import sys import unittest import vericred_client from vericred_client.rest import ApiException from vericred_client.models.state_network_size_request import StateNetworkSizeRequest class TestStateNetworkSizeRequest(unittest.TestCase): """ StateNetworkSizeRequest unit test stubs """ def setUp(self): pass def tearDown(self): pass def testStateNetworkSizeRequest(self): """ Test StateNetworkSizeRequest """ model = vericred_client.models.state_network_size_request.StateNetworkSizeRequest() if __name__ == '__main__': unittest.main()
40.388
228
0.669407
795a3d94272c99104a4b71e6c1019931e189ac43
1,757
py
Python
neutron/extensions/l2_adjacency.py
cleo4zheng/neutron
6d65318308edfd984bdd0ff1ac7fef9486a040f7
[ "Apache-2.0" ]
4
2018-08-05T00:43:03.000Z
2021-10-13T00:45:45.000Z
neutron/extensions/l2_adjacency.py
cleo4zheng/neutron
6d65318308edfd984bdd0ff1ac7fef9486a040f7
[ "Apache-2.0" ]
8
2018-06-14T14:50:16.000Z
2018-11-13T16:30:42.000Z
neutron/extensions/l2_adjacency.py
cleo4zheng/neutron
6d65318308edfd984bdd0ff1ac7fef9486a040f7
[ "Apache-2.0" ]
7
2018-06-12T18:57:04.000Z
2019-05-09T15:42:30.000Z
# Copyright (c) 2016 NEC Technologies Ltd. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron_lib.api import extensions L2_ADJACENCY = 'l2_adjacency' EXTENDED_ATTRIBUTES_2_0 = { 'networks': { L2_ADJACENCY: {'allow_post': False, 'allow_put': False, 'is_visible': True} } } class L2_adjacency(extensions.ExtensionDescriptor): """Extension class supporting L2 Adjacency for Routed Networks The following class is used by neutron's extension framework to provide metadata related to the L2 Adjacency for Neutron Routed Network, exposing the same to clients. No new resources have been defined by this extension. """ @classmethod def get_name(cls): return "L2 Adjacency" @classmethod def get_alias(cls): return "l2_adjacency" @classmethod def get_description(cls): return "Display L2 Adjacency for Neutron Networks." @classmethod def get_updated(cls): return "2016-04-12T16:00:00-00:00" def get_extended_resources(self, version): if version == "2.0": return EXTENDED_ATTRIBUTES_2_0 else: return {}
29.779661
78
0.676153
795a3edcf461d2d1576f2303e1566ecd225c5f43
2,404
py
Python
tensorflow/python/data/experimental/ops/counter.py
yage99/tensorflow
c7fa71b32a3635eb25596ae80d007b41007769c4
[ "Apache-2.0" ]
78
2020-08-04T12:36:25.000Z
2022-03-25T04:23:40.000Z
tensorflow/python/data/experimental/ops/counter.py
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
203
2019-06-14T23:53:10.000Z
2022-02-10T02:27:23.000Z
tensorflow/python/data/experimental/ops/counter.py
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
66
2020-05-15T10:05:12.000Z
2022-02-14T07:28:18.000Z
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Counter Dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python import tf2 from tensorflow.python.data.experimental.ops import scan_ops from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.util.tf_export import tf_export @tf_export("data.experimental.Counter", v1=[]) def CounterV2(start=0, step=1, dtype=dtypes.int64): """Creates a `Dataset` that counts from `start` in steps of size `step`. For example: ```python Dataset.count() == [0, 1, 2, ...) Dataset.count(2) == [2, 3, ...) Dataset.count(2, 5) == [2, 7, 12, ...) Dataset.count(0, -1) == [0, -1, -2, ...) Dataset.count(10, -1) == [10, 9, ...) ``` Args: start: (Optional.) The starting value for the counter. Defaults to 0. step: (Optional.) The step size for the counter. Defaults to 1. dtype: (Optional.) The data type for counter elements. Defaults to `tf.int64`. Returns: A `Dataset` of scalar `dtype` elements. """ with ops.name_scope("counter"): start = ops.convert_to_tensor(start, dtype=dtype, name="start") step = ops.convert_to_tensor(step, dtype=dtype, name="step") return dataset_ops.Dataset.from_tensors(0).repeat(None).apply( scan_ops.scan(start, lambda state, _: (state + step, state))) @tf_export(v1=["data.experimental.Counter"]) def CounterV1(start=0, step=1, dtype=dtypes.int64): return dataset_ops.DatasetV1Adapter(CounterV2(start, step, dtype)) CounterV1.__doc__ = CounterV2.__doc__ if tf2.enabled(): Counter = CounterV2 else: Counter = CounterV1
35.880597
80
0.698003
795a3f029819973136f92b1daa9efc9b0d762635
25
py
Python
src/wta/__init__.py
kaist-irnlp/SparseColBERT
f0f0ed4acff5dc3c747f13315de0fe7ea50b5b70
[ "MIT" ]
null
null
null
src/wta/__init__.py
kaist-irnlp/SparseColBERT
f0f0ed4acff5dc3c747f13315de0fe7ea50b5b70
[ "MIT" ]
null
null
null
src/wta/__init__.py
kaist-irnlp/SparseColBERT
f0f0ed4acff5dc3c747f13315de0fe7ea50b5b70
[ "MIT" ]
null
null
null
from .wta import WTAModel
25
25
0.84
795a3f58ec603bb6ef567a91c2c2f86a4cf7cc8f
3,055
py
Python
experiments/20200328/StationA-48samples.py
emilyjunkins/covid19
ab57fa9e9d601eef25a12847ca868d86a4799ca2
[ "Apache-2.0" ]
11
2020-03-30T07:20:15.000Z
2022-03-20T08:41:35.000Z
experiments/20200328/StationA-48samples.py
emilyjunkins/covid19
ab57fa9e9d601eef25a12847ca868d86a4799ca2
[ "Apache-2.0" ]
4
2020-03-31T19:36:37.000Z
2020-05-13T14:06:27.000Z
experiments/20200328/StationA-48samples.py
emilyjunkins/covid19
ab57fa9e9d601eef25a12847ca868d86a4799ca2
[ "Apache-2.0" ]
7
2020-04-07T12:20:25.000Z
2021-12-04T02:32:43.000Z
metadata = { 'protocolName': 'BP Genomics Station A 48 Samples', 'author': 'Chaz <chaz@opentrons.com', 'source': 'Custom Protocol Request', 'apiLevel': '2.2' } def run(protocol): tips200 = [protocol.load_labware('opentrons_96_tiprack_300ul', '9')] tips20 = [protocol.load_labware('opentrons_96_filtertiprack_20ul', '8')] p300 = protocol.load_instrument( 'p300_single_gen2', 'left', tip_racks=tips200) p20 = protocol.load_instrument( 'p20_single_gen2', 'right', tip_racks=tips20) plate = protocol.load_labware('nest_96_deepwell_2ml', '1') platewells = [well for pl in plate.columns()[::2] for well in pl] samplerack1 = protocol.load_labware('bpg_24_tuberack_2ml', '5') samplerack2 = protocol.load_labware('bpg_24_tuberack_2ml', '2') samps = samplerack1.wells()[:]+samplerack2.wells()[:] tempdeck = protocol.load_module('tempdeck', '7') temprack = tempdeck.load_labware( 'opentrons_96_aluminumblock_generic_pcr_strip_200ul') tempdeck.set_temperature(4) re_rack = protocol.load_labware( 'opentrons_24_tuberack_eppendorf_1.5ml_safelock_snapcap', '4', 'Opentrons 24 TubeRack with Reagents') pk = re_rack['D6'] lysis_wells = [ re_rack[w] for w in [ltr+str(i) for ltr in 'ABCD' for i in range(1, 4)] ] spike1 = temprack['H1'] spike2 = temprack['H4'] p20.flow_rate.aspirate = 10 p20.flow_rate.dispense = 20 p20.flow_rate.blow_out = 100 p300.flow_rate.aspirate = 50 p300.flow_rate.dispense = 150 p300.flow_rate.blow_out = 300 p300.pick_up_tip() lysis_tip = 2 for idx, well in enumerate(platewells): l_well = idx//4 if lysis_tip == l_well: p300.drop_tip() p300.pick_up_tip() lysis_tip += 2 lysis = lysis_wells[l_well] for _ in range(2): p300.transfer(150, lysis, well.top(-2), new_tip='never') p300.drop_tip() p20.pick_up_tip() for well in platewells: p20.transfer(20, pk, well.top(-6), new_tip='never') p20.blow_out(well.top(-6)) p20.drop_tip() p300.flow_rate.aspirate = 150 p300.flow_rate.dispense = 300 for src, dest in zip(samps, platewells): p300.pick_up_tip() p300.aspirate(180, src.bottom(9)) for _ in range(2): p300.dispense(150, src.bottom(9)) p300.aspirate(150, src.bottom(9)) p300.dispense(180, src.bottom(9)) p300.transfer(200, src.bottom(9), dest.top(-6), new_tip='never') p300.blow_out(dest.top(-6)) p300.aspirate(200, src.bottom(9)) for _ in range(5): p300.dispense(180, dest) p300.aspirate(180, dest) p300.dispense(200, dest) p300.blow_out(dest.top(-6)) p300.aspirate(20, dest.top(-6)) p300.drop_tip() for idx, well in enumerate(platewells): spike = spike1 if idx < 24 else spike2 p20.pick_up_tip() p20.transfer(4, spike, well, new_tip='never') p20.drop_tip()
34.715909
79
0.627496
795a3fb9ededa5ce7050157031c1327f66345df2
202
py
Python
ClassCode/P7/create_ndarray.py
tsyet12/ClassCode
db1db97f71a6f31769d58739c6687863bc6b88c4
[ "MIT" ]
null
null
null
ClassCode/P7/create_ndarray.py
tsyet12/ClassCode
db1db97f71a6f31769d58739c6687863bc6b88c4
[ "MIT" ]
null
null
null
ClassCode/P7/create_ndarray.py
tsyet12/ClassCode
db1db97f71a6f31769d58739c6687863bc6b88c4
[ "MIT" ]
null
null
null
import numpy as np x_zero= np.zeros((2,3)) print(x_zero) x_arange=np.arange(100) print(x_arange) x_linspace=np.linspace(1,10,100) print(x_linspace) x_indices=np.indices((5,5)) print(x_indices)
10.631579
32
0.732673
795a40e5bc41eda01ee92d1ee998ffd333ba2b03
4,701
py
Python
datasets/wikisql/wikisql_data.py
IBM/row-column-intersection
fbc4214d7f92f9602a1b219b4336a940de3d6ee4
[ "Apache-2.0" ]
29
2021-04-20T07:15:41.000Z
2022-03-01T06:32:40.000Z
datasets/wikisql/wikisql_data.py
IBM/row-column-intersection
fbc4214d7f92f9602a1b219b4336a940de3d6ee4
[ "Apache-2.0" ]
4
2021-04-25T06:49:13.000Z
2021-10-07T11:00:14.000Z
datasets/wikisql/wikisql_data.py
IBM/row-column-intersection
fbc4214d7f92f9602a1b219b4336a940de3d6ee4
[ "Apache-2.0" ]
5
2021-04-28T21:52:41.000Z
2022-02-21T07:16:35.000Z
import json from tqdm import tqdm from datasets.wikisql.wikisql_dbengine import DBEngine from lib.query import Query from lib.common import count_lines import os from util.line_corpus import jsonl_lines, write_open from util.args_help import fill_from_args from datasets.wikisql.tables2agg_classify import write_agg_classify import logging logger = logging.getLogger(__name__) def cell_value_is_answer(cv, answers): if cv in answers or cv.lower() in answers: return True try: cvf = float(cv) for ans in answers: try: if cvf == float(ans): return True except: pass except: pass return False def convert(queries, tables, outfile, *, skip_aggregation=True, show_aggregation=False): """Creates examples for the training and dev sets.""" tid2rows = dict() for line in tables: jobj = json.loads(line) tid = jobj['id'] header = jobj['header'] rows_orig = jobj['rows'] rows = [] for r in rows_orig: rows.append([str(cv) for cv in r]) tid2rows[tid] = [[str(h) for h in header]] + rows with write_open(outfile) as out: for qid, line in enumerate(queries): jobj = json.loads(line) agg_index = jobj['sql']['agg'] if skip_aggregation and agg_index != 0: # skip aggregation queries continue table_id = jobj['table_id'] rows = tid2rows[table_id] qtext = jobj['question'] target_column = jobj['sql']['sel'] condition_columns = [colndx for colndx, comp, val in jobj['sql']['conds']] answers = jobj['answer'] rowids = jobj['rowids'] if 'rowids' in jobj else None jobj = dict() jobj['id'] = f'{qid}' jobj['question'] = qtext jobj['header'] = rows[0] jobj['rows'] = rows[1:] jobj['target_column'] = target_column jobj['condition_columns'] = condition_columns jobj['table_id'] = table_id jobj['agg_index'] = agg_index if rowids is not None: jobj['target_rows'] = rowids if agg_index == 0: answers = [str(ans) for ans in answers] clean_answers = [] for r in rows[1:]: if cell_value_is_answer(r[target_column], answers): clean_answers.append(r[target_column]) if not clean_answers: logger.info(f'no answers found! {answers} in {rows}') if len(clean_answers) != len(answers): logger.info(f'answers changed from {answers} to {clean_answers}') jobj['answers'] = list(set(clean_answers)) else: jobj['answers'] = answers if show_aggregation and rowids and len(rowids) > 1 and agg_index != 0: print(json.dumps(jobj)) out.write(json.dumps(jobj)+'\n') if __name__ == '__main__': class Options: def __init__(self): self.data_dir = '' opts = Options() fill_from_args(opts) for split in ['train', 'dev', 'test']: orig = os.path.join(opts.data_dir, f'{split}.jsonl') db_file = os.path.join(opts.data_dir, f'{split}.db') ans_file = os.path.join(opts.data_dir, f"{split}_ans.jsonl.gz") tbl_file = os.path.join(opts.data_dir, f"{split}.tables.jsonl") engine = DBEngine(db_file) exact_match = [] with open(orig) as fs, write_open(ans_file) as fo: grades = [] for ls in tqdm(fs, total=count_lines(orig)): eg = json.loads(ls) sql = eg['sql'] qg = Query.from_dict(sql, ordered=False) gold = engine.execute_query(eg['table_id'], qg, lower=True) assert isinstance(gold, list) #if len(gold) != 1: # print(f'for {sql} : {gold}') eg['answer'] = gold eg['rowids'] = engine.execute_query_rowid(eg['table_id'], qg, lower=True) # CONSIDER: if it is not an agg query, somehow identify the particular cell fo.write(json.dumps(eg)+'\n') convert(jsonl_lines(ans_file), jsonl_lines(tbl_file), os.path.join(opts.data_dir, f"{split}_agg.jsonl.gz"), skip_aggregation=False) convert(jsonl_lines(ans_file), jsonl_lines(tbl_file), os.path.join(opts.data_dir, f"{split}_lookup.jsonl.gz"), skip_aggregation=True) write_agg_classify(opts.data_dir, split)
38.85124
95
0.562859
795a414ca8d27b1c2dd9ace96c58e06ff6c3966b
428
py
Python
broker/eudat/login_eudat_test.py
ebloc/EBlocBroker
8e0a8be0fb4e998b0b7214c3eb3eff20b90a8253
[ "MIT" ]
null
null
null
broker/eudat/login_eudat_test.py
ebloc/EBlocBroker
8e0a8be0fb4e998b0b7214c3eb3eff20b90a8253
[ "MIT" ]
null
null
null
broker/eudat/login_eudat_test.py
ebloc/EBlocBroker
8e0a8be0fb4e998b0b7214c3eb3eff20b90a8253
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from broker import config from broker.config import env from broker.libs import eudat eudat.login(env.OC_USER, env.LOG_PATH.joinpath(".eudat_client.txt"), env.OC_CLIENT) oc = config.oc print("running: `oc.list('.')`") _list = oc.list(".") for item in _list: print(item) # for item in _list: # print(item) # try: # oc.delete(item.path) # except Exception as e: # print(e)
22.526316
83
0.658879
795a4165a660ce360f80ebcaca6823f1bbdd69f8
37,102
py
Python
venv/Lib/site-packages/werkzeug/utils.py
camehu2022/cotacao_moeda
0f161b58184c783e64b76803596862c45fb4a947
[ "MIT" ]
null
null
null
venv/Lib/site-packages/werkzeug/utils.py
camehu2022/cotacao_moeda
0f161b58184c783e64b76803596862c45fb4a947
[ "MIT" ]
null
null
null
venv/Lib/site-packages/werkzeug/utils.py
camehu2022/cotacao_moeda
0f161b58184c783e64b76803596862c45fb4a947
[ "MIT" ]
null
null
null
import codecs import io import mimetypes import os import pkgutil import re import sys import typing as t import unicodedata import warnings from datetime import datetime from html.entities import name2codepoint from time import time from zlib import adler32 from ._internal import _DictAccessorProperty from ._internal import _missing from ._internal import _parse_signature from ._internal import _TAccessorValue from .datastructures import Headers from .exceptions import NotFound from .exceptions import RequestedRangeNotSatisfiable from .security import safe_join from .urls import url_quote from .wsgi import wrap_file if t.TYPE_CHECKING: from _typeshed.wsgi import WSGIEnvironment from .wrappers.request import Request from .wrappers.response import Response _T = t.TypeVar("_T") _entity_re = re.compile(r"&([^;]+);") _filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]") _windows_device_files = ( "CON", "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3", "PRN", "NUL", ) class cached_property(property, t.Generic[_T]): """A :func:`property` that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again. .. code-block:: python class Example: @cached_property def value(self): # calculate something important here return 42 e = Example() e.value # evaluates e.value # uses cache e.value = 16 # sets cache del e.value # clears cache The class must have a ``__dict__`` for this to work. .. versionchanged:: 2.0 ``del obj.name`` clears the cached value. """ def __init__( self, fget: t.Callable[[t.Any], _T], name: t.Optional[str] = None, doc: t.Optional[str] = None, ) -> None: super().__init__(fget, doc=doc) self.__name__ = name or fget.__name__ self.__module__ = fget.__module__ def __set__(self, obj: object, value: _T) -> None: obj.__dict__[self.__name__] = value def __get__(self, obj: object, type: type = None) -> _T: # type: ignore if obj is None: return self # type: ignore value: _T = obj.__dict__.get(self.__name__, _missing) if value is _missing: value = self.fget(obj) # type: ignore obj.__dict__[self.__name__] = value return value def __delete__(self, obj: object) -> None: del obj.__dict__[self.__name__] def invalidate_cached_property(obj: object, name: str) -> None: """Invalidates the cache for a :class:`cached_property`: >>> class Test(object): ... @cached_property ... def magic_number(self): ... print("recalculating...") ... return 42 ... >>> var = Test() >>> var.magic_number recalculating... 42 >>> var.magic_number 42 >>> invalidate_cached_property(var, "magic_number") >>> var.magic_number recalculating... 42 You must pass the name of the cached property as the second argument. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use ``del obj.name`` instead. """ warnings.warn( "'invalidate_cached_property' is deprecated and will be removed" " in Werkzeug 2.1. Use 'del obj.name' instead.", DeprecationWarning, stacklevel=2, ) delattr(obj, name) class environ_property(_DictAccessorProperty[_TAccessorValue]): """Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute: >>> class Test(object): ... environ = {'key': 'value'} ... test = environ_property('key') >>> var = Test() >>> var.test 'value' If you pass it a second value it's used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value is used. If no default value is provided `None` is used. Per default the property is read only. You have to explicitly enable it by passing ``read_only=False`` to the constructor. """ read_only = True def lookup(self, obj: "Request") -> "WSGIEnvironment": return obj.environ class header_property(_DictAccessorProperty[_TAccessorValue]): """Like `environ_property` but for headers.""" def lookup(self, obj: t.Union["Request", "Response"]) -> Headers: return obj.headers class HTMLBuilder: """Helper object for HTML generation. Per default there are two instances of that class. The `html` one, and the `xhtml` one for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML. Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it's a good idea to use a list with the star-syntax for some children: >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ', ... html.a('bar', href='bar.html')]) '<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>' This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist. Calling the builder escapes the string passed: >>> html.p(html("<foo>")) '<p>&lt;foo&gt;</p>' .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. """ _entity_re = re.compile(r"&([^;]+);") _entities = name2codepoint.copy() _entities["apos"] = 39 _empty_elements = { "area", "base", "basefont", "br", "col", "command", "embed", "frame", "hr", "img", "input", "keygen", "isindex", "link", "meta", "param", "source", "wbr", } _boolean_attributes = { "selected", "checked", "compact", "declare", "defer", "disabled", "ismap", "multiple", "nohref", "noresize", "noshade", "nowrap", } _plaintext_elements = {"textarea"} _c_like_cdata = {"script", "style"} def __init__(self, dialect): # type: ignore self._dialect = dialect def __call__(self, s): # type: ignore import html warnings.warn( "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.", DeprecationWarning, stacklevel=2, ) return html.escape(s) def __getattr__(self, tag): # type: ignore import html warnings.warn( "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.", DeprecationWarning, stacklevel=2, ) if tag[:2] == "__": raise AttributeError(tag) def proxy(*children, **arguments): # type: ignore buffer = f"<{tag}" for key, value in arguments.items(): if value is None: continue if key[-1] == "_": key = key[:-1] if key in self._boolean_attributes: if not value: continue if self._dialect == "xhtml": value = f'="{key}"' else: value = "" else: value = f'="{html.escape(value)}"' buffer += f" {key}{value}" if not children and tag in self._empty_elements: if self._dialect == "xhtml": buffer += " />" else: buffer += ">" return buffer buffer += ">" children_as_string = "".join([str(x) for x in children if x is not None]) if children_as_string: if tag in self._plaintext_elements: children_as_string = html.escape(children_as_string) elif tag in self._c_like_cdata and self._dialect == "xhtml": children_as_string = f"/*<![CDATA[*/{children_as_string}/*]]>*/" buffer += children_as_string + f"</{tag}>" return buffer return proxy def __repr__(self) -> str: return f"<{type(self).__name__} for {self._dialect!r}>" html = HTMLBuilder("html") xhtml = HTMLBuilder("xhtml") # https://cgit.freedesktop.org/xdg/shared-mime-info/tree/freedesktop.org.xml.in # https://www.iana.org/assignments/media-types/media-types.xhtml # Types listed in the XDG mime info that have a charset in the IANA registration. _charset_mimetypes = { "application/ecmascript", "application/javascript", "application/sql", "application/xml", "application/xml-dtd", "application/xml-external-parsed-entity", } def get_content_type(mimetype: str, charset: str) -> str: """Returns the full content type string with charset for a mimetype. If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged. :param mimetype: The mimetype to be used as content type. :param charset: The charset to be appended for text mimetypes. :return: The content type. .. versionchanged:: 0.15 Any type that ends with ``+xml`` gets a charset, not just those that start with ``application/``. Known text types such as ``application/javascript`` are also given charsets. """ if ( mimetype.startswith("text/") or mimetype in _charset_mimetypes or mimetype.endswith("+xml") ): mimetype += f"; charset={charset}" return mimetype def detect_utf_encoding(data: bytes) -> str: """Detect which UTF encoding was used to encode the given bytes. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big or little endian. Some editors or libraries may prepend a BOM. :internal: :param data: Bytes in unknown UTF encoding. :return: UTF encoding name .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. This is built in to :func:`json.loads`. .. versionadded:: 0.15 """ warnings.warn( "'detect_utf_encoding' is deprecated and will be removed in" " Werkzeug 2.1. This is built in to 'json.loads'.", DeprecationWarning, stacklevel=2, ) head = data[:4] if head[:3] == codecs.BOM_UTF8: return "utf-8-sig" if b"\x00" not in head: return "utf-8" if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE): return "utf-32" if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE): return "utf-16" if len(head) == 4: if head[:3] == b"\x00\x00\x00": return "utf-32-be" if head[::2] == b"\x00\x00": return "utf-16-be" if head[1:] == b"\x00\x00\x00": return "utf-32-le" if head[1::2] == b"\x00\x00": return "utf-16-le" if len(head) == 2: return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le" return "utf-8" def format_string(string: str, context: t.Mapping[str, t.Any]) -> str: """String-templates format a string: >>> format_string('$foo and ${foo}s', dict(foo=42)) '42 and 42s' This does not do any attribute lookup. :param string: the format string. :param context: a dict with the variables to insert. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use :class:`string.Template` instead. """ from string import Template warnings.warn( "'utils.format_string' is deprecated and will be removed in" " Werkzeug 2.1. Use 'string.Template' instead.", DeprecationWarning, stacklevel=2, ) return Template(string).substitute(context) def secure_filename(filename: str) -> str: r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure """ filename = unicodedata.normalize("NFKD", filename) filename = filename.encode("ascii", "ignore").decode("ascii") for sep in os.path.sep, os.path.altsep: if sep: filename = filename.replace(sep, " ") filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip( "._" ) # on nt a couple of special files are present in each folder. We # have to ensure that the target file is not such a filename. In # this case we prepend an underline if ( os.name == "nt" and filename and filename.split(".")[0].upper() in _windows_device_files ): filename = f"_{filename}" return filename def escape(s: t.Any) -> str: """Replace ``&``, ``<``, ``>``, ``"``, and ``'`` with HTML-safe sequences. ``None`` is escaped to an empty string. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use MarkupSafe instead. """ import html warnings.warn( "'utils.escape' is deprecated and will be removed in Werkzeug" " 2.1. Use MarkupSafe instead.", DeprecationWarning, stacklevel=2, ) if s is None: return "" if hasattr(s, "__html__"): return s.__html__() # type: ignore if not isinstance(s, str): s = str(s) return html.escape(s, quote=True) # type: ignore def unescape(s: str) -> str: """The reverse of :func:`escape`. This unescapes all the HTML entities, not only those inserted by ``escape``. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use MarkupSafe instead. """ import html warnings.warn( "'utils.unescape' is deprecated and will be removed in Werkzueg" " 2.1. Use MarkupSafe instead.", DeprecationWarning, stacklevel=2, ) return html.unescape(s) def redirect( location: str, code: int = 302, Response: t.Optional[t.Type["Response"]] = None ) -> "Response": """Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. .. versionadded:: 0.10 The class used for the Response object can now be passed in. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. :param class Response: a Response class to use when instantiating a response. The default is :class:`werkzeug.wrappers.Response` if unspecified. """ import html if Response is None: from .wrappers import Response # type: ignore display_location = html.escape(location) if isinstance(location, str): # Safe conversion is necessary here as we might redirect # to a broken URI scheme (for instance itms-services). from .urls import iri_to_uri location = iri_to_uri(location, safe_conversion=True) response = Response( # type: ignore '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' "<title>Redirecting...</title>\n" "<h1>Redirecting...</h1>\n" "<p>You should be redirected automatically to target URL: " f'<a href="{html.escape(location)}">{display_location}</a>. If' " not click the link.", code, mimetype="text/html", ) response.headers["Location"] = location return response def append_slash_redirect(environ: "WSGIEnvironment", code: int = 301) -> "Response": """Redirects to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already. :param environ: the WSGI environment for the request that triggers the redirect. :param code: the status code for the redirect. """ new_path = environ["PATH_INFO"].strip("/") + "/" query_string = environ.get("QUERY_STRING") if query_string: new_path += f"?{query_string}" return redirect(new_path, code) def send_file( path_or_file: t.Union[os.PathLike, str, t.IO[bytes]], environ: "WSGIEnvironment", mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, use_x_sendfile: bool = False, response_class: t.Optional[t.Type["Response"]] = None, _root_path: t.Optional[t.Union[os.PathLike, str]] = None, ) -> "Response": """Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with :class:`io.BytesIO`. Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn't intend. If the WSGI server sets a ``file_wrapper`` in ``environ``, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports ``X-Sendfile``, ``use_x_sendfile=True`` will tell the server to send the given path, which is much more efficient than reading it in Python. :param path_or_file: The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. :param environ: The WSGI environ for the current request. :param mimetype: The MIME type to send for the file. If not provided, it will try to detect it from the file name. :param as_attachment: Indicate to a browser that it should offer to save the file instead of displaying it. :param download_name: The default name browsers will use when saving the file. Defaults to the passed file name. :param conditional: Enable conditional and range responses based on request headers. Requires passing a file path and ``environ``. :param etag: Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. :param last_modified: The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. :param max_age: How long the client should cache the file, in seconds. If set, ``Cache-Control`` will be ``public``, otherwise it will be ``no-cache`` to prefer conditional caching. :param use_x_sendfile: Set the ``X-Sendfile`` header to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path. :param response_class: Build the response using this class. Defaults to :class:`~werkzeug.wrappers.Response`. :param _root_path: Do not use. For internal use only. Use :func:`send_from_directory` to safely send files under a path. .. versionchanged:: 2.0.2 ``send_file`` only sets a detected ``Content-Encoding`` if ``as_attachment`` is disabled. .. versionadded:: 2.0 Adapted from Flask's implementation. .. versionchanged:: 2.0 ``download_name`` replaces Flask's ``attachment_filename`` parameter. If ``as_attachment=False``, it is passed with ``Content-Disposition: inline`` instead. .. versionchanged:: 2.0 ``max_age`` replaces Flask's ``cache_timeout`` parameter. ``conditional`` is enabled and ``max_age`` is not set by default. .. versionchanged:: 2.0 ``etag`` replaces Flask's ``add_etags`` parameter. It can be a string to use instead of generating one. .. versionchanged:: 2.0 If an encoding is returned when guessing ``mimetype`` from ``download_name``, set the ``Content-Encoding`` header. """ if response_class is None: from .wrappers import Response response_class = Response path: t.Optional[str] = None file: t.Optional[t.IO[bytes]] = None size: t.Optional[int] = None mtime: t.Optional[float] = None headers = Headers() if isinstance(path_or_file, (os.PathLike, str)) or hasattr( path_or_file, "__fspath__" ): path_or_file = t.cast(t.Union[os.PathLike, str], path_or_file) # Flask will pass app.root_path, allowing its send_file wrapper # to not have to deal with paths. if _root_path is not None: path = os.path.join(_root_path, path_or_file) else: path = os.path.abspath(path_or_file) stat = os.stat(path) size = stat.st_size mtime = stat.st_mtime else: file = path_or_file if download_name is None and path is not None: download_name = os.path.basename(path) if mimetype is None: if download_name is None: raise TypeError( "Unable to detect the MIME type because a file name is" " not available. Either set 'download_name', pass a" " path instead of a file, or set 'mimetype'." ) mimetype, encoding = mimetypes.guess_type(download_name) if mimetype is None: mimetype = "application/octet-stream" # Don't send encoding for attachments, it causes browsers to # save decompress tar.gz files. if encoding is not None and not as_attachment: headers.set("Content-Encoding", encoding) if download_name is not None: try: download_name.encode("ascii") except UnicodeEncodeError: simple = unicodedata.normalize("NFKD", download_name) simple = simple.encode("ascii", "ignore").decode("ascii") quoted = url_quote(download_name, safe="") names = {"filename": simple, "filename*": f"UTF-8''{quoted}"} else: names = {"filename": download_name} value = "attachment" if as_attachment else "inline" headers.set("Content-Disposition", value, **names) elif as_attachment: raise TypeError( "No name provided for attachment. Either set" " 'download_name' or pass a path instead of a file." ) if use_x_sendfile and path is not None: headers["X-Sendfile"] = path data = None else: if file is None: file = open(path, "rb") # type: ignore elif isinstance(file, io.BytesIO): size = file.getbuffer().nbytes elif isinstance(file, io.TextIOBase): raise ValueError("Files must be opened in binary mode or use BytesIO.") data = wrap_file(environ, file) rv = response_class( data, mimetype=mimetype, headers=headers, direct_passthrough=True ) if size is not None: rv.content_length = size if last_modified is not None: rv.last_modified = last_modified # type: ignore elif mtime is not None: rv.last_modified = mtime # type: ignore rv.cache_control.no_cache = True # Flask will pass app.get_send_file_max_age, allowing its send_file # wrapper to not have to deal with paths. if callable(max_age): max_age = max_age(path) if max_age is not None: if max_age > 0: rv.cache_control.no_cache = None rv.cache_control.public = True rv.cache_control.max_age = max_age rv.expires = int(time() + max_age) # type: ignore if isinstance(etag, str): rv.set_etag(etag) elif etag and path is not None: check = adler32(path.encode("utf-8")) & 0xFFFFFFFF rv.set_etag(f"{mtime}-{size}-{check}") if conditional: try: rv = rv.make_conditional(environ, accept_ranges=True, complete_length=size) except RequestedRangeNotSatisfiable: if file is not None: file.close() raise # Some x-sendfile implementations incorrectly ignore the 304 # status code and send the file anyway. if rv.status_code == 304: rv.headers.pop("x-sendfile", None) return rv def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], environ: "WSGIEnvironment", **kwargs: t.Any, ) -> "Response": """Send a file from within a directory using :func:`send_file`. This is a secure way to serve files from a folder, such as static files or uploads. Uses :func:`~werkzeug.security.safe_join` to ensure the path coming from the client is not maliciously crafted to point outside the specified directory. If the final path does not point to an existing regular file, returns a 404 :exc:`~werkzeug.exceptions.NotFound` error. :param directory: The directory that ``path`` must be located under. :param path: The path to the file to send, relative to ``directory``. :param environ: The WSGI environ for the current request. :param kwargs: Arguments to pass to :func:`send_file`. .. versionadded:: 2.0 Adapted from Flask's implementation. """ path = safe_join(os.fspath(directory), os.fspath(path)) if path is None: raise NotFound() # Flask will pass app.root_path, allowing its send_from_directory # wrapper to not have to deal with paths. if "_root_path" in kwargs: path = os.path.join(kwargs["_root_path"], path) try: if not os.path.isfile(path): raise NotFound() except ValueError: # path contains null byte on Python < 3.8 raise NotFound() from None return send_file(path, environ, **kwargs) def import_string(import_name: str, silent: bool = False) -> t.Any: """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object """ import_name = import_name.replace(":", ".") try: try: __import__(import_name) except ImportError: if "." not in import_name: raise else: return sys.modules[import_name] module_name, obj_name = import_name.rsplit(".", 1) module = __import__(module_name, globals(), locals(), [obj_name]) try: return getattr(module, obj_name) except AttributeError as e: raise ImportError(e) from None except ImportError as e: if not silent: raise ImportStringError(import_name, e).with_traceback( sys.exc_info()[2] ) from None return None def find_modules( import_path: str, include_packages: bool = False, recursive: bool = False ) -> t.Iterator[str]: """Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_path: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator """ module = import_string(import_path) path = getattr(module, "__path__", None) if path is None: raise ValueError(f"{import_path!r} is not a package") basename = f"{module.__name__}." for _importer, modname, ispkg in pkgutil.iter_modules(path): modname = basename + modname if ispkg: if include_packages: yield modname if recursive: yield from find_modules(modname, include_packages, True) else: yield modname def validate_arguments(func, args, kwargs, drop_extra=True): # type: ignore """Checks if the function accepts the arguments and keyword arguments. Returns a new ``(args, kwargs)`` tuple that can safely be passed to the function without causing a `TypeError` because the function signature is incompatible. If `drop_extra` is set to `True` (which is the default) any extra positional or keyword arguments are dropped automatically. The exception raised provides three attributes: `missing` A set of argument names that the function expected but where missing. `extra` A dict of keyword arguments that the function can not handle but where provided. `extra_positional` A list of values that where given by positional argument but the function cannot accept. This can be useful for decorators that forward user submitted data to a view function:: from werkzeug.utils import ArgumentValidationError, validate_arguments def sanitize(f): def proxy(request): data = request.values.to_dict() try: args, kwargs = validate_arguments(f, (request,), data) except ArgumentValidationError: raise BadRequest('The browser failed to transmit all ' 'the data expected.') return f(*args, **kwargs) return proxy :param func: the function the validation is performed against. :param args: a tuple of positional arguments. :param kwargs: a dict of keyword arguments. :param drop_extra: set to `False` if you don't want extra arguments to be silently dropped. :return: tuple in the form ``(args, kwargs)``. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use :func:`inspect.signature` instead. """ warnings.warn( "'utils.validate_arguments' is deprecated and will be removed" " in Werkzeug 2.1. Use 'inspect.signature' instead.", DeprecationWarning, stacklevel=2, ) parser = _parse_signature(func) args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5] if missing: raise ArgumentValidationError(tuple(missing)) elif (extra or extra_positional) and not drop_extra: raise ArgumentValidationError(None, extra, extra_positional) return tuple(args), kwargs def bind_arguments(func, args, kwargs): # type: ignore """Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments. .. deprecated:: 2.0 Will be removed in Werkzeug 2.1. Use :meth:`Signature.bind` instead. """ warnings.warn( "'utils.bind_arguments' is deprecated and will be removed in" " Werkzeug 2.1. Use 'Signature.bind' instead.", DeprecationWarning, stacklevel=2, ) ( args, kwargs, missing, extra, extra_positional, arg_spec, vararg_var, kwarg_var, ) = _parse_signature(func)(args, kwargs) values = {} for (name, _has_default, _default), value in zip(arg_spec, args): values[name] = value if vararg_var is not None: values[vararg_var] = tuple(extra_positional) elif extra_positional: raise TypeError("too many positional arguments") if kwarg_var is not None: multikw = set(extra) & {x[0] for x in arg_spec} if multikw: raise TypeError( f"got multiple values for keyword argument {next(iter(multikw))!r}" ) values[kwarg_var] = extra elif extra: raise TypeError(f"got unexpected keyword argument {next(iter(extra))!r}") return values class ArgumentValidationError(ValueError): """Raised if :func:`validate_arguments` fails to validate .. deprecated:: 2.0 Will be removed in Werkzeug 2.1 along with ``utils.bind`` and ``validate_arguments``. """ def __init__(self, missing=None, extra=None, extra_positional=None): # type: ignore self.missing = set(missing or ()) self.extra = extra or {} self.extra_positional = extra_positional or [] super().__init__( "function arguments invalid." f" ({len(self.missing)} missing," f" {len(self.extra) + len(self.extra_positional)} additional)" ) class ImportStringError(ImportError): """Provides information about a failed :func:`import_string` attempt.""" #: String in dotted notation that failed to be imported. import_name: str #: Wrapped exception. exception: BaseException def __init__(self, import_name: str, exception: BaseException) -> None: self.import_name = import_name self.exception = exception msg = import_name name = "" tracked = [] for part in import_name.replace(":", ".").split("."): name = f"{name}.{part}" if name else part imported = import_string(name, silent=True) if imported: tracked.append((name, getattr(imported, "__file__", None))) else: track = [f"- {n!r} found in {i!r}." for n, i in tracked] track.append(f"- {name!r} not found.") track_str = "\n".join(track) msg = ( f"import_string() failed for {import_name!r}. Possible reasons" f" are:\n\n" "- missing __init__.py in a package;\n" "- package or module path not included in sys.path;\n" "- duplicated package or module name taking precedence in" " sys.path;\n" "- missing module, class, function or variable;\n\n" f"Debugged import:\n\n{track_str}\n\n" f"Original exception:\n\n{type(exception).__name__}: {exception}" ) break super().__init__(msg) def __repr__(self) -> str: return f"<{type(self).__name__}({self.import_name!r}, {self.exception!r})>"
33.729091
88
0.623929
795a41fae2e45b7288b9b1ec646a798b3175b0c0
254
py
Python
built_in.py
aadilmughal786/ACulator-Tkinter
8953d7c2b4598e104140f265e5b9cd330ea1bc02
[ "MIT" ]
1
2021-06-03T21:14:27.000Z
2021-06-03T21:14:27.000Z
built_in.py
aadilmughal786/ACulator
8953d7c2b4598e104140f265e5b9cd330ea1bc02
[ "MIT" ]
null
null
null
built_in.py
aadilmughal786/ACulator
8953d7c2b4598e104140f265e5b9cd330ea1bc02
[ "MIT" ]
null
null
null
#-------------------- Built-in --------------------------- #-------------------------- variables ----------------------- #---------------------------- objects -------------------------- #---------------------------- functions -------------------------
36.285714
65
0.125984
795a425b90dd48adb3812efcc61c304be668e808
10,573
py
Python
topaz/frame.py
ruby-compiler-survey/topaz
bf4a56adbe03ae9ab4984729c733fcbc64a164c4
[ "BSD-3-Clause" ]
241
2015-01-02T18:49:09.000Z
2022-03-15T15:08:45.000Z
topaz/frame.py
ruby-compiler-survey/topaz
bf4a56adbe03ae9ab4984729c733fcbc64a164c4
[ "BSD-3-Clause" ]
16
2015-05-04T21:31:08.000Z
2020-06-04T22:49:36.000Z
topaz/frame.py
ruby-compiler-survey/topaz
bf4a56adbe03ae9ab4984729c733fcbc64a164c4
[ "BSD-3-Clause" ]
24
2015-02-15T05:35:11.000Z
2022-03-22T13:29:04.000Z
from rpython.rlib import jit from topaz.closure import LocalCell from topaz.objects.hashobject import W_HashObject from topaz.objects.functionobject import W_FunctionObject class BaseFrame(object): _attrs_ = ["backref", "escaped", "back_last_instr"] def __init__(self): self.backref = jit.vref_None self.escaped = False class Frame(BaseFrame): _virtualizable_ = [ "bytecode", "localsstack_w[*]", "stackpos", "w_self", "block", "cells[*]", "lastblock", "lexical_scope", "last_instr", "parent_interp", "top_parent_interp", ] @jit.unroll_safe def __init__(self, bytecode, w_self, lexical_scope, block, parent_interp, top_parent_interp, regexp_match_cell): self = jit.hint(self, fresh_virtualizable=True, access_directly=True) BaseFrame.__init__(self) self.bytecode = bytecode self.localsstack_w = [None] * ( len(bytecode.cellvars) + bytecode.max_stackdepth) self.stackpos = len(bytecode.cellvars) self.last_instr = 0 self.cells = ([LocalCell() for _ in bytecode.cellvars] + [None] * len(bytecode.freevars)) self.regexp_match_cell = regexp_match_cell self.w_self = w_self self.lexical_scope = lexical_scope self.block = block self.parent_interp = parent_interp self.top_parent_interp = top_parent_interp self.visibility = W_FunctionObject.PUBLIC self.lastblock = None def _set_arg(self, space, pos, w_value): assert pos >= 0 self.cells[pos].set(space, self, pos, w_value) def handle_block_args(self, space, bytecode, args_w, block): if (len(args_w) == 1 and ( len(bytecode.arg_pos) >= 2 or ( len(bytecode.arg_pos) > 0 and bytecode.splat_arg_pos != -1))): w_arg = args_w[0] if (not space.is_kind_of(w_arg, space.w_array) and space.respond_to(w_arg, "to_ary")): w_arg = space.convert_type(w_arg, space.w_array, "to_ary", raise_error=True, reraise_error=True) if space.is_kind_of(w_arg, space.w_array): args_w = space.listview(w_arg) minargc = len(bytecode.arg_pos) - len(bytecode.defaults) if len(args_w) < minargc: args_w.extend([space.w_nil] * (minargc - len(args_w))) if bytecode.splat_arg_pos == -1: if len(args_w) > len(bytecode.arg_pos): del args_w[len(bytecode.arg_pos):] return self.handle_args(space, bytecode, args_w, block) @jit.unroll_safe def handle_args(self, space, bytecode, args_w, block): from topaz.interpreter import Interpreter keywords_hash = None if len(bytecode.kwarg_names) > 0 or bytecode.kwrest_pos != -1: # we only take the hash if we have more than enough arguments min_args = max(len(bytecode.arg_pos) - len(bytecode.defaults), 0) if len(args_w) > min_args: w_obj = args_w[-1] if not space.is_kind_of(w_obj, space.w_hash): w_obj = space.convert_type( w_obj, space.w_hash, "to_hash", reraise_error=True) if isinstance(w_obj, W_HashObject): keywords_hash = space.send(w_obj, "clone") assert isinstance(keywords_hash, W_HashObject) if (len(bytecode.kw_defaults) < len(bytecode.kwarg_names) and not keywords_hash): raise space.error( space.w_ArgumentError, "missing keywords: %s" % ",".join(bytecode.kwarg_names)) pre = 0 post = len(args_w) if keywords_hash is None else len(args_w) - 1 if (post < (len(bytecode.arg_pos) - len(bytecode.defaults)) or (bytecode.splat_arg_pos == -1 and post > len(bytecode.arg_pos))): raise space.error( space.w_ArgumentError, "wrong number of arguments (%d for %d)" % ( len(args_w), len(bytecode.arg_pos) - len(bytecode.defaults))) if bytecode.default_arg_begin != -1: len_pre_args = bytecode.default_arg_begin elif bytecode.splat_arg_pos != -1: len_pre_args = bytecode.splat_arg_pos else: len_pre_args = len(bytecode.arg_pos) len_post_arg = (len(bytecode.arg_pos) - len(bytecode.defaults) - len_pre_args) # [required args, optional args, splat arg, required args, keywords args, keyword rest, block] # ^ ^ # pre post # fill post-arguments from back. actual_args_len = post offset = len(bytecode.arg_pos) - post for i in xrange(actual_args_len - 1, actual_args_len - len_post_arg - 1, -1): self._set_arg(space, bytecode.arg_pos[i + offset], args_w[i]) post -= 1 # [required args, optional args, splat arg, required args, keywords args, keyword rest, block] # ^ ^------------- # pre post # fill arguments from start as far as we can (until we hit post or the # end of the default arguments + normal arguments for i in xrange(min(post, len_pre_args + len(bytecode.defaults))): self._set_arg(space, bytecode.arg_pos[i], args_w[i]) pre += 1 # [required args, optional args, splat arg, required args, keywords args, keyword rest, block] # ------------------------^ ^ # pre post given_defaults = pre - len_pre_args # fill up remaining default arguments with their default values for i in xrange(given_defaults, len(bytecode.defaults)): bc = bytecode.defaults[i] self.bytecode = bc w_value = Interpreter().interpret(space, self, bc) self._set_arg(space, bytecode.arg_pos[len_pre_args + i], w_value) if bytecode.splat_arg_pos != -1: if pre >= post: splat_args_w = [] else: splat_args_w = args_w[pre:post] w_splat_args = space.newarray(splat_args_w) self._set_arg(space, bytecode.splat_arg_pos, w_splat_args) for i, name in enumerate(bytecode.kwarg_names): w_key = space.newsymbol(name) w_value = None if keywords_hash is not None: try: w_value = keywords_hash.getitem(w_key) keywords_hash.delete(w_key) except KeyError: pass # kword arguments with defaults come first, so if we get an # index error here, we're missing a required keyword argument if w_value is None: try: bc = bytecode.kw_defaults[i] except IndexError: raise space.error( space.w_ArgumentError, "missing keyword: %s" % name) self.bytecode = bc w_value = Interpreter().interpret(space, self, bc) self._set_arg(space, bytecode.cellvars.index(name), w_value) self.bytecode = bytecode if bytecode.kwrest_pos != -1: if keywords_hash is not None: self._set_arg(space, bytecode.kwrest_pos, keywords_hash) else: self._set_arg(space, bytecode.kwrest_pos, space.newhash()) elif keywords_hash is not None: if keywords_hash.size() > 0: raise space.error( space.w_ArgumentError, "unknown keywords: %s" % space.str_w( space.send(space.send(keywords_hash, "keys"), "to_s") )) if bytecode.block_arg_pos != -1: if block is None: w_block = space.w_nil else: w_block = block.copy(space) self._set_arg(space, bytecode.block_arg_pos, w_block) def push(self, w_obj): stackpos = jit.promote(self.stackpos) self.localsstack_w[stackpos] = w_obj self.stackpos = stackpos + 1 def pop(self): stackpos = jit.promote(self.stackpos) - 1 assert stackpos >= 0 w_res = self.localsstack_w[stackpos] self.localsstack_w[stackpos] = None self.stackpos = stackpos return w_res @jit.unroll_safe def popitemsreverse(self, n): items_w = [None] * n for i in xrange(n - 1, -1, -1): items_w[i] = self.pop() return items_w def peek(self): stackpos = jit.promote(self.stackpos) - 1 assert stackpos >= 0 return self.localsstack_w[stackpos] def popblock(self): lastblock = self.lastblock if lastblock is not None: self.lastblock = lastblock.lastblock return lastblock @jit.unroll_safe def unrollstack(self, kind): while self.lastblock is not None: block = self.popblock() if block.handling_mask & kind: return block block.cleanupstack(self) def unrollstack_and_jump(self, space, unroller): block = self.unrollstack(unroller.kind) return block.handle(space, self, unroller) def has_contents(self): return True def get_filename(self): return self.bytecode.filepath def get_lineno(self, prev_frame): if prev_frame is None: instr = self.last_instr else: instr = prev_frame.back_last_instr - 1 try: return self.bytecode.lineno_table[instr] except IndexError: return self.last_instr def get_code_name(self): return self.bytecode.name class BuiltinFrame(BaseFrame): def __init__(self, name): BaseFrame.__init__(self) self.name = name def has_contents(self): return self.backref() is not None def get_filename(self): return self.backref().get_filename() def get_lineno(self, prev_frame): return self.backref().get_lineno(self) def get_code_name(self): return self.name
38.447273
102
0.565592
795a428a572922a0feb1cd52d26aa45d17997124
976
py
Python
q2_types/distance_matrix/tests/test_type.py
Leo-Simpson/q2-types
2946fda4fe2817fde1646ddcdc8e8ebf41abe5a4
[ "BSD-3-Clause" ]
null
null
null
q2_types/distance_matrix/tests/test_type.py
Leo-Simpson/q2-types
2946fda4fe2817fde1646ddcdc8e8ebf41abe5a4
[ "BSD-3-Clause" ]
null
null
null
q2_types/distance_matrix/tests/test_type.py
Leo-Simpson/q2-types
2946fda4fe2817fde1646ddcdc8e8ebf41abe5a4
[ "BSD-3-Clause" ]
null
null
null
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import unittest from q2_types.distance_matrix import (DistanceMatrix, DistanceMatrixDirectoryFormat) from qiime2.plugin.testing import TestPluginBase class TestTypes(TestPluginBase): package = 'q2_types.distance_matrix.tests' def test_distance_matrix_semantic_type_registration(self): self.assertRegisteredSemanticType(DistanceMatrix) def test_distance_matrix_semantic_type_to_format_registration(self): self.assertSemanticTypeRegisteredToFormat( DistanceMatrix, DistanceMatrixDirectoryFormat) if __name__ == "__main__": unittest.main()
33.655172
78
0.633197
795a433ae6b46f0506af6a061d713f0e8d955006
1,175
tac
Python
server/smtpserver.tac
thepatrick/smtp2web
15ee20199134ce1edc97aa9094a7005ec0230dad
[ "Apache-2.0" ]
1
2015-03-12T10:42:11.000Z
2015-03-12T10:42:11.000Z
server/smtpserver.tac
thepatrick/smtp2web
15ee20199134ce1edc97aa9094a7005ec0230dad
[ "Apache-2.0" ]
null
null
null
server/smtpserver.tac
thepatrick/smtp2web
15ee20199134ce1edc97aa9094a7005ec0230dad
[ "Apache-2.0" ]
null
null
null
# Copyright 2008 arachnid AT notdot.net, # 2010 Patrick Quinn-Graham # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from twisted.application import service from twisted.application import internet from twisted.enterprise import adbapi import sys import os sys.path.append(os.path.dirname(__file__)) import smtp2web application = service.Application("smtp2web Service") settings = smtp2web.Settings(secret_key="", state_file="state", master_host="www.s2w.m.ac.nz") smtpServerFactory = smtp2web.ESMTPFactory(settings) smtpServerService = internet.TCPServer(2025, smtpServerFactory) smtpServerService.setServiceParent(application)
34.558824
79
0.764255
795a438faef16b0fa56f4a39b523269717696e81
475
py
Python
book/timed.py
tebeka/pythonwise
56f8cb7aa792c3ad6a3dc754e15f6a04890d694a
[ "BSD-3-Clause" ]
21
2016-11-16T20:08:56.000Z
2021-12-11T23:13:05.000Z
book/timed.py
tebeka/pythonwise
56f8cb7aa792c3ad6a3dc754e15f6a04890d694a
[ "BSD-3-Clause" ]
1
2020-10-05T08:35:31.000Z
2020-10-05T08:35:31.000Z
book/timed.py
tebeka/pythonwise
56f8cb7aa792c3ad6a3dc754e15f6a04890d694a
[ "BSD-3-Clause" ]
8
2016-11-12T22:54:55.000Z
2021-02-10T10:46:23.000Z
from time import monotonic, sleep from functools import wraps def timed(fn): """Timing decorator""" @wraps(fn) def wrapper(*args, **kw): start = monotonic() try: return fn(*args, **kw) finally: duration = monotonic() - start print('{} took {:.2f}sec'.format(fn.__name__, duration)) return wrapper @timed def add(a, b): """Does addition""" sleep(a/10.0) # Simulate work return a + b
20.652174
68
0.557895
795a439eb05239c6ac408caceb0f4368efa46369
7,640
py
Python
demisto_sdk/commands/lint/tests/test_linter/docker_runner_test.py
yalonso7/demisto-sdk
4b832078cdadb0b604a064532975e8be68ac726a
[ "MIT" ]
null
null
null
demisto_sdk/commands/lint/tests/test_linter/docker_runner_test.py
yalonso7/demisto-sdk
4b832078cdadb0b604a064532975e8be68ac726a
[ "MIT" ]
null
null
null
demisto_sdk/commands/lint/tests/test_linter/docker_runner_test.py
yalonso7/demisto-sdk
4b832078cdadb0b604a064532975e8be68ac726a
[ "MIT" ]
null
null
null
from unittest.mock import DEFAULT import pytest from demisto_sdk.commands.common.constants import TYPE_PWSH, TYPE_PYTHON from demisto_sdk.commands.lint import linter from demisto_sdk.commands.lint.linter import Linter class TestCreateImage: def test_build_image_no_errors(self, linter_obj: Linter, demisto_content, create_integration, mocker): content_path = demisto_content create_integration(content_path=content_path) # Expected returns exp_test_image_id = 'test-image' exp_errors = "" # Jinja2 mocking mocker.patch.multiple(linter, Environment=DEFAULT, FileSystemLoader=DEFAULT, exceptions=DEFAULT, hashlib=DEFAULT) # Facts mocking mocker.patch.dict(linter_obj._facts, { "images": [], "python_version": 0, "test": False, "lint_files": [], "additional_requirements": [], "docker_engine": True, "env_vars": { "CI": True, "DEMISTO_LINT_UPDATE_CERTS": "yes" } }) mocker.patch.object(linter, 'io') # Docker client mocking mocker.patch.object(linter_obj, '_docker_client') docker_build_response = mocker.MagicMock() docker_build_response.short_id = exp_test_image_id linter_obj._docker_client.images.build().__getitem__().short_id = exp_test_image_id act_test_image_id, act_errors = linter_obj._docker_image_create(docker_base_image=[exp_test_image_id, 3.7]) assert act_test_image_id == exp_test_image_id assert act_errors == exp_errors class TestPylint: def test_run_pylint_no_errors(self, mocker, linter_obj: Linter): # Expected values exp_container_exit_code = 0 exp_container_log = "" # Docker client mocking mocker.patch.object(linter_obj, '_docker_client') linter_obj._docker_client.containers.run().wait.return_value = {"StatusCode": exp_container_exit_code} linter_obj._docker_client.containers.run().logs.return_value = exp_container_log.encode('utf-8') act_container_exit_code, act_container_log = linter_obj._docker_run_pylint(test_image='test-image', keep_container=False) assert exp_container_exit_code == act_container_exit_code assert exp_container_log == act_container_log @pytest.mark.parametrize(argnames="exp_container_exit_code, exp_container_log, exp_exit_code, exp_output", argvalues=[(1, "test", 1, "test"), (2, "test", 1, "test"), (4, "test", 0, ""), (8, "test", 0, ""), (16, "test", 0, ""), (32, "test", 2, "")]) def test_run_pylint_with_errors(self, mocker, linter_obj: Linter, exp_container_exit_code: int, exp_container_log: str, exp_exit_code: int, exp_output: str): # Docker client mocking mocker.patch.object(linter_obj, '_docker_client') linter_obj._docker_client.containers.run().wait.return_value = {"StatusCode": exp_container_exit_code} linter_obj._docker_client.containers.run().logs.return_value = exp_container_log.encode('utf-8') act_exit_code, act_output = linter_obj._docker_run_pylint(test_image='test-image', keep_container=False) assert act_exit_code == exp_exit_code assert act_output == exp_output class TestPytest: @pytest.mark.parametrize(argnames="exp_container_exit_code, exp_exit_code", argvalues=[(0, 0), (1, 1), (2, 1), (5, 0)]) def test_run_pytest(self, mocker, linter_obj: Linter, exp_container_exit_code: int, exp_exit_code: int): exp_test_json = mocker.MagicMock() # Docker client mocking mocker.patch.object(linter_obj, '_docker_client') linter_obj._docker_client.containers.run().wait.return_value = {"StatusCode": exp_container_exit_code} # Docker related mocking mocker.patch.object(linter, 'json') linter.json.loads.return_value = exp_test_json mocker.patch.object(linter, 'get_file_from_container') act_container_exit_code, act_output, act_test_json = linter_obj._docker_run_pytest(test_image='test-image', keep_container=False, test_xml="") assert exp_exit_code == act_container_exit_code assert exp_test_json == act_test_json class TestRunLintInContainer: """Pylint/Pytest""" @pytest.mark.parametrize(argnames="no_test, no_pylint, no_pwsh_analyze, no_pwsh_test, pack_type", argvalues=[(True, True, False, False, TYPE_PYTHON), (False, True, True, True, TYPE_PYTHON), (True, False, True, False, TYPE_PYTHON), (False, False, False, False, TYPE_PYTHON)]) def test_run_one_lint_check_success(self, mocker, linter_obj, lint_files, no_test: bool, no_pylint: bool, no_pwsh_analyze: bool, no_pwsh_test: bool, pack_type: str): mocker.patch.dict(linter_obj._facts, { "images": [["image", "3.7"]], "test": True, "version_two": False, "lint_files": lint_files, "additional_requirements": [] }) mocker.patch.dict(linter_obj._pkg_lint_status, { "pack_type": pack_type, }) mocker.patch.object(linter_obj, '_docker_image_create') linter_obj._docker_image_create.return_value = ("test-image", "") mocker.patch.object(linter_obj, '_docker_run_pytest') linter_obj._docker_run_pytest.return_value = (0b0, '', {}) mocker.patch.object(linter_obj, '_docker_run_pylint') linter_obj._docker_run_pylint.return_value = (0b0, '') mocker.patch.object(linter_obj, '_docker_run_pwsh_analyze') linter_obj._docker_run_pwsh_analyze.return_value = (0b0, {}) mocker.patch.object(linter_obj, '_docker_run_pwsh_test') linter_obj._docker_run_pwsh_test.return_value = (0b0, '') linter_obj._run_lint_on_docker_image(no_pylint=no_pylint, no_test=no_test, no_pwsh_analyze=no_pwsh_analyze, no_pwsh_test=no_pwsh_test, test_xml="", keep_container=False) assert linter_obj._pkg_lint_status.get("exit_code") == 0b0 if not no_test and pack_type == TYPE_PYTHON: linter_obj._docker_run_pytest.assert_called_once() elif not no_pylint and pack_type == TYPE_PYTHON: linter_obj._docker_run_pylint.assert_called_once() elif not no_pwsh_analyze and pack_type == TYPE_PWSH: linter_obj._docker_run_pwsh_analyze.assert_called_once() elif not no_pwsh_test and pack_type == TYPE_PWSH: linter_obj._docker_run_pwsh_test.assert_called_once()
50.263158
123
0.593717
795a485916c904bb66ddb7f69063625cb3c8e211
5,847
py
Python
predict.py
Ceciliawangwang/image_segmentation_deeplabv3
32b2c9a272a903023d78ebc3a2523147522346b4
[ "MIT" ]
null
null
null
predict.py
Ceciliawangwang/image_segmentation_deeplabv3
32b2c9a272a903023d78ebc3a2523147522346b4
[ "MIT" ]
null
null
null
predict.py
Ceciliawangwang/image_segmentation_deeplabv3
32b2c9a272a903023d78ebc3a2523147522346b4
[ "MIT" ]
null
null
null
from torch.utils.data import dataset from tqdm import tqdm import network import utils import os import random import argparse import numpy as np import time from torch.utils import data from datasets import VOCSegmentation, Cityscapes, cityscapes from torchvision import transforms as T from metrics import StreamSegMetrics import torch import torch.nn as nn from PIL import Image # import matplotlib # import matplotlib.pyplot as plt from glob import glob def get_argparser(): parser = argparse.ArgumentParser() # Datset Options parser.add_argument("--input", type=str, default='img', help="path to a single image or image directory") parser.add_argument("--dataset", type=str, default='cityscapes', choices=['voc', 'cityscapes'], help='Name of training set') # Deeplab Options parser.add_argument("--model", type=str, default='deeplabv3plus_mobilenet', choices=['deeplabv3_resnet50', 'deeplabv3plus_resnet50', 'deeplabv3_resnet101', 'deeplabv3plus_resnet101', 'deeplabv3_mobilenet', 'deeplabv3plus_mobilenet'], help='model name') parser.add_argument("--separable_conv", action='store_true', default=False, help="apply separable conv to decoder and aspp") parser.add_argument("--output_stride", type=int, default=16, choices=[8, 16]) # Train Options parser.add_argument("--save_val_results_to", default='img_out', help="save segmentation results to the specified dir") parser.add_argument("--crop_val", action='store_true', default=False, help='crop validation (default: False)') parser.add_argument("--val_batch_size", type=int, default=4, help='batch size for validation (default: 4)') parser.add_argument("--crop_size", type=int, default=513) parser.add_argument("--ckpt", default='checkpoints/best_deeplabv3plus_mobilenet_cityscapes_os16.pth', type=str, help="resume from checkpoint") parser.add_argument("--gpu_id", type=str, default='0', help="GPU ID") return parser def main(): opts = get_argparser().parse_args() if opts.dataset.lower() == 'voc': opts.num_classes = 21 decode_fn = VOCSegmentation.decode_target elif opts.dataset.lower() == 'cityscapes': opts.num_classes = 19 decode_fn = Cityscapes.decode_target os.environ['CUDA_VISIBLE_DEVICES'] = opts.gpu_id device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("Device: %s" % device) # Setup dataloader image_files = [] if os.path.isdir(opts.input): # for ext in ['png', 'jpeg', 'jpg', 'JPEG']: for ext in ['jpg']: # @@@ Meihui files = glob(os.path.join(opts.input, '**/*.jpg'), recursive=True) if len(files)>0: image_files.extend(files) elif os.path.isfile(opts.input): image_files.append(opts.input) # Set up model model_map = { 'deeplabv3_resnet50': network.deeplabv3_resnet50, 'deeplabv3plus_resnet50': network.deeplabv3plus_resnet50, 'deeplabv3_resnet101': network.deeplabv3_resnet101, 'deeplabv3plus_resnet101': network.deeplabv3plus_resnet101, 'deeplabv3_mobilenet': network.deeplabv3_mobilenet, 'deeplabv3plus_mobilenet': network.deeplabv3plus_mobilenet } model = model_map[opts.model](num_classes=opts.num_classes, output_stride=opts.output_stride) if opts.separable_conv and 'plus' in opts.model: network.convert_to_separable_conv(model.classifier) utils.set_bn_momentum(model.backbone, momentum=0.01) if opts.ckpt is not None and os.path.isfile(opts.ckpt): # https://github.com/VainF/DeepLabV3Plus-Pytorch/issues/8#issuecomment-605601402, @PytaichukBohdan checkpoint = torch.load(opts.ckpt, map_location=torch.device('cpu')) model.load_state_dict(checkpoint["model_state"]) model = nn.DataParallel(model) model.to(device) print("Resume model from %s" % opts.ckpt) del checkpoint else: print("[!] Retrain") model = nn.DataParallel(model) model.to(device) #denorm = utils.Denormalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # denormalization for ori images if opts.crop_val: transform = T.Compose([ T.Resize(opts.crop_size), T.CenterCrop(opts.crop_size), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) else: transform = T.Compose([ T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) if opts.save_val_results_to is not None: os.makedirs(opts.save_val_results_to, exist_ok=True) with torch.no_grad(): model = model.eval() for img_path in tqdm(image_files): img_name = os.path.basename(img_path).split('.')[0] img = Image.open(img_path).convert('RGB') img = transform(img).unsqueeze(0) # To tensor of NCHW img = img.to(device) pred = model(img).max(1)[1].cpu().numpy()[0] # HW colorized_preds = decode_fn(pred).astype('uint8') colorized_preds = Image.fromarray(colorized_preds) if opts.save_val_results_to: colorized_preds.save(os.path.join(opts.save_val_results_to, img_name+'.png')) if __name__ == '__main__': ts = time.time() main() print('Time in serial:', time.time() - ts) print('finished!')
39.506757
120
0.625278
795a4921f4452766e97a972d83c88355294f68a1
641
py
Python
adjMatrix.py
deka1105/Playbooks
c1f2157681ca5371688ff8a457f097962f81beff
[ "MIT" ]
null
null
null
adjMatrix.py
deka1105/Playbooks
c1f2157681ca5371688ff8a457f097962f81beff
[ "MIT" ]
null
null
null
adjMatrix.py
deka1105/Playbooks
c1f2157681ca5371688ff8a457f097962f81beff
[ "MIT" ]
null
null
null
import pandas as pd allCol = ['0A','1B','2C','3D','4E','5F','6G','7H','8I','9J','10K','12L','12M','13N'] sol = { 0:[11,], 1:[2,6,7,8,9,10,11], 3:[6,7,8,9,10,11], 4:[4,], 5:[11,], 7:[6,9], 10:[11,], 12:[2,9,10,11]} adj_matrix = pd.DataFrame() adj_matrix['Row Names'] = allCol def createAdj(): global adj_matrix for i in range (0, len(allCol)-1): ls = [] for j in allCol: ls.append('-') try: solList = sol[i] for j in solList: ls[j] = 'X' except: pass adj_matrix[allCol[i]] = ls createAdj() adj_matrix
23.740741
84
0.460218
795a49504684b96cc7037822c4f9e94bd817a1a6
11,205
py
Python
src/_cffi_src/openssl/evp.py
hanzhichao/cryptography
98c534d8c83474b93891e8447bf822bbd7fa6f85
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/_cffi_src/openssl/evp.py
hanzhichao/cryptography
98c534d8c83474b93891e8447bf822bbd7fa6f85
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/_cffi_src/openssl/evp.py
hanzhichao/cryptography
98c534d8c83474b93891e8447bf822bbd7fa6f85
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. INCLUDES = """ #include <openssl/evp.h> """ TYPES = """ typedef ... EVP_CIPHER; typedef ... EVP_CIPHER_CTX; typedef ... EVP_MD; typedef ... EVP_MD_CTX; typedef ... EVP_PKEY; typedef ... EVP_PKEY_CTX; static const int EVP_PKEY_RSA; static const int EVP_PKEY_DSA; static const int EVP_PKEY_DH; static const int EVP_PKEY_DHX; static const int EVP_PKEY_EC; static const long EVP_PKEY_SM2; static const int EVP_PKEY_X25519; static const int EVP_PKEY_ED25519; static const int EVP_PKEY_X448; static const int EVP_PKEY_ED448; static const int EVP_PKEY_POLY1305; static const int EVP_MAX_MD_SIZE; static const int EVP_CTRL_AEAD_SET_IVLEN; static const int EVP_CTRL_AEAD_GET_TAG; static const int EVP_CTRL_AEAD_SET_TAG; static const int Cryptography_HAS_SCRYPT; static const int Cryptography_HAS_EVP_PKEY_DHX; static const int Cryptography_HAS_EVP_PKEY_get_set_tls_encodedpoint; static const int Cryptography_HAS_ONESHOT_EVP_DIGEST_SIGN_VERIFY; static const long Cryptography_HAS_RAW_KEY; static const long Cryptography_HAS_EVP_DIGESTFINAL_XOF; static const long Cryptography_HAS_300_FIPS; static const long Cryptography_HAS_EVP_PKEY_DH; """ FUNCTIONS = """ const EVP_CIPHER *EVP_get_cipherbyname(const char *); int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *, int); int EVP_CipherInit_ex(EVP_CIPHER_CTX *, const EVP_CIPHER *, ENGINE *, const unsigned char *, const unsigned char *, int); int EVP_CipherUpdate(EVP_CIPHER_CTX *, unsigned char *, int *, const unsigned char *, int); int EVP_CipherFinal_ex(EVP_CIPHER_CTX *, unsigned char *, int *); int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *); EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *); int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *, int); int EVP_MD_CTX_copy_ex(EVP_MD_CTX *, const EVP_MD_CTX *); int EVP_DigestInit_ex(EVP_MD_CTX *, const EVP_MD *, ENGINE *); int EVP_DigestUpdate(EVP_MD_CTX *, const void *, size_t); int EVP_DigestFinal_ex(EVP_MD_CTX *, unsigned char *, unsigned int *); int EVP_DigestFinalXOF(EVP_MD_CTX *, unsigned char *, size_t); const EVP_MD *EVP_get_digestbyname(const char *); EVP_PKEY *EVP_PKEY_new(void); void EVP_PKEY_free(EVP_PKEY *); int EVP_PKEY_type(int); int EVP_PKEY_size(EVP_PKEY *); RSA *EVP_PKEY_get1_RSA(EVP_PKEY *); DSA *EVP_PKEY_get1_DSA(EVP_PKEY *); DH *EVP_PKEY_get1_DH(EVP_PKEY *); int EVP_PKEY_encrypt(EVP_PKEY_CTX *, unsigned char *, size_t *, const unsigned char *, size_t); int EVP_PKEY_decrypt(EVP_PKEY_CTX *, unsigned char *, size_t *, const unsigned char *, size_t); int EVP_SignInit(EVP_MD_CTX *, const EVP_MD *); int EVP_SignUpdate(EVP_MD_CTX *, const void *, size_t); int EVP_SignFinal(EVP_MD_CTX *, unsigned char *, unsigned int *, EVP_PKEY *); int EVP_VerifyInit(EVP_MD_CTX *, const EVP_MD *); int EVP_VerifyUpdate(EVP_MD_CTX *, const void *, size_t); int EVP_VerifyFinal(EVP_MD_CTX *, const unsigned char *, unsigned int, EVP_PKEY *); int EVP_DigestSignInit(EVP_MD_CTX *, EVP_PKEY_CTX **, const EVP_MD *, ENGINE *, EVP_PKEY *); int EVP_DigestSignUpdate(EVP_MD_CTX *, const void *, size_t); int EVP_DigestSignFinal(EVP_MD_CTX *, unsigned char *, size_t *); int EVP_DigestVerifyInit(EVP_MD_CTX *, EVP_PKEY_CTX **, const EVP_MD *, ENGINE *, EVP_PKEY *); EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *, ENGINE *); EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int, ENGINE *); void EVP_PKEY_CTX_free(EVP_PKEY_CTX *); int EVP_PKEY_sign_init(EVP_PKEY_CTX *); int EVP_PKEY_sign(EVP_PKEY_CTX *, unsigned char *, size_t *, const unsigned char *, size_t); int EVP_PKEY_verify_init(EVP_PKEY_CTX *); int EVP_PKEY_verify(EVP_PKEY_CTX *, const unsigned char *, size_t, const unsigned char *, size_t); int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *); int EVP_PKEY_verify_recover(EVP_PKEY_CTX *, unsigned char *, size_t *, const unsigned char *, size_t); int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *); int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *); int EVP_PKEY_set1_RSA(EVP_PKEY *, RSA *); int EVP_PKEY_set1_DSA(EVP_PKEY *, DSA *); int EVP_PKEY_set1_DH(EVP_PKEY *, DH *); int EVP_PKEY_cmp(const EVP_PKEY *, const EVP_PKEY *); int EVP_PKEY_keygen_init(EVP_PKEY_CTX *); int EVP_PKEY_keygen(EVP_PKEY_CTX *, EVP_PKEY **); int EVP_PKEY_derive_init(EVP_PKEY_CTX *); int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *, EVP_PKEY *); int EVP_PKEY_derive(EVP_PKEY_CTX *, unsigned char *, size_t *); int EVP_PKEY_set_type(EVP_PKEY *, int); int EVP_PKEY_id(const EVP_PKEY *); EVP_MD_CTX *EVP_MD_CTX_new(void); void EVP_MD_CTX_free(EVP_MD_CTX *); /* This function is no longer used by pyOpenSSL >= 21.1 */ EVP_MD_CTX *Cryptography_EVP_MD_CTX_new(void); /* This function is no longer used by pyOpenSSL >= 21.1 */ void Cryptography_EVP_MD_CTX_free(EVP_MD_CTX *); /* Added in 1.1.1 */ int EVP_DigestSign(EVP_MD_CTX *, unsigned char *, size_t *, const unsigned char *, size_t); int EVP_DigestVerify(EVP_MD_CTX *, const unsigned char *, size_t, const unsigned char *, size_t); /* Added in 1.1.0 */ size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *, unsigned char **); int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *, const unsigned char *, size_t); /* EVP_PKEY * became const in 1.1.0 */ int EVP_PKEY_bits(EVP_PKEY *); void OpenSSL_add_all_algorithms(void); int EVP_PKEY_assign_RSA(EVP_PKEY *, RSA *); EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *); int EVP_PKEY_set1_EC_KEY(EVP_PKEY *, EC_KEY *); int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *, int, int, void *); int PKCS5_PBKDF2_HMAC(const char *, int, const unsigned char *, int, int, const EVP_MD *, int, unsigned char *); int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *, const EVP_MD *); int EVP_PBE_scrypt(const char *, size_t, const unsigned char *, size_t, uint64_t, uint64_t, uint64_t, uint64_t, unsigned char *, size_t); EVP_PKEY *EVP_PKEY_new_raw_private_key(int, ENGINE *, const unsigned char *, size_t); EVP_PKEY *EVP_PKEY_new_raw_public_key(int, ENGINE *, const unsigned char *, size_t); int EVP_PKEY_get_raw_private_key(const EVP_PKEY *, unsigned char *, size_t *); int EVP_PKEY_get_raw_public_key(const EVP_PKEY *, unsigned char *, size_t *); int EVP_default_properties_is_fips_enabled(OSSL_LIB_CTX *); int EVP_default_properties_enable_fips(OSSL_LIB_CTX *, int); """ CUSTOMIZATIONS = """ #ifdef EVP_PKEY_DHX const long Cryptography_HAS_EVP_PKEY_DHX = 1; #else const long Cryptography_HAS_EVP_PKEY_DHX = 0; const long EVP_PKEY_DHX = -1; #endif EVP_MD_CTX *Cryptography_EVP_MD_CTX_new(void) { return EVP_MD_CTX_new(); } void Cryptography_EVP_MD_CTX_free(EVP_MD_CTX *md) { EVP_MD_CTX_free(md); } #if CRYPTOGRAPHY_IS_LIBRESSL || defined(OPENSSL_NO_SCRYPT) static const long Cryptography_HAS_SCRYPT = 0; int (*EVP_PBE_scrypt)(const char *, size_t, const unsigned char *, size_t, uint64_t, uint64_t, uint64_t, uint64_t, unsigned char *, size_t) = NULL; #else static const long Cryptography_HAS_SCRYPT = 1; #endif #if !CRYPTOGRAPHY_IS_LIBRESSL static const long Cryptography_HAS_EVP_PKEY_get_set_tls_encodedpoint = 1; #else static const long Cryptography_HAS_EVP_PKEY_get_set_tls_encodedpoint = 0; size_t (*EVP_PKEY_get1_tls_encodedpoint)(EVP_PKEY *, unsigned char **) = NULL; int (*EVP_PKEY_set1_tls_encodedpoint)(EVP_PKEY *, const unsigned char *, size_t) = NULL; #endif #if CRYPTOGRAPHY_LIBRESSL_LESS_THAN_340 || \ (CRYPTOGRAPHY_OPENSSL_LESS_THAN_111 && !CRYPTOGRAPHY_IS_LIBRESSL) static const long Cryptography_HAS_ONESHOT_EVP_DIGEST_SIGN_VERIFY = 0; int (*EVP_DigestSign)(EVP_MD_CTX *, unsigned char *, size_t *, const unsigned char *tbs, size_t) = NULL; int (*EVP_DigestVerify)(EVP_MD_CTX *, const unsigned char *, size_t, const unsigned char *, size_t) = NULL; #else static const long Cryptography_HAS_ONESHOT_EVP_DIGEST_SIGN_VERIFY = 1; #endif #if CRYPTOGRAPHY_OPENSSL_LESS_THAN_111 static const long Cryptography_HAS_RAW_KEY = 0; static const long Cryptography_HAS_EVP_DIGESTFINAL_XOF = 0; int (*EVP_DigestFinalXOF)(EVP_MD_CTX *, unsigned char *, size_t) = NULL; EVP_PKEY *(*EVP_PKEY_new_raw_private_key)(int, ENGINE *, const unsigned char *, size_t) = NULL; EVP_PKEY *(*EVP_PKEY_new_raw_public_key)(int, ENGINE *, const unsigned char *, size_t) = NULL; int (*EVP_PKEY_get_raw_private_key)(const EVP_PKEY *, unsigned char *, size_t *) = NULL; int (*EVP_PKEY_get_raw_public_key)(const EVP_PKEY *, unsigned char *, size_t *) = NULL; #else static const long Cryptography_HAS_RAW_KEY = 1; static const long Cryptography_HAS_EVP_DIGESTFINAL_XOF = 1; #endif /* OpenSSL 1.1.0+ does this define for us, but if not present we'll do it */ #if !defined(EVP_CTRL_AEAD_SET_IVLEN) # define EVP_CTRL_AEAD_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN #endif #if !defined(EVP_CTRL_AEAD_GET_TAG) # define EVP_CTRL_AEAD_GET_TAG EVP_CTRL_GCM_GET_TAG #endif #if !defined(EVP_CTRL_AEAD_SET_TAG) # define EVP_CTRL_AEAD_SET_TAG EVP_CTRL_GCM_SET_TAG #endif /* This is tied to X25519 support so we reuse the Cryptography_HAS_X25519 conditional to remove it. OpenSSL 1.1.0 didn't have this define, but 1.1.1 will when it is released. We can remove this in the distant future when we drop 1.1.0 support. */ #ifndef EVP_PKEY_X25519 #define EVP_PKEY_X25519 NID_X25519 #endif /* This is tied to X448 support so we reuse the Cryptography_HAS_X448 conditional to remove it. OpenSSL 1.1.1 adds this define. We can remove this in the distant future when we drop 1.1.0 support. */ #ifndef EVP_PKEY_X448 #define EVP_PKEY_X448 NID_X448 #endif /* This is tied to ED25519 support so we reuse the Cryptography_HAS_ED25519 conditional to remove it. */ #ifndef EVP_PKEY_ED25519 #define EVP_PKEY_ED25519 NID_ED25519 #endif /* This is tied to ED448 support so we reuse the Cryptography_HAS_ED448 conditional to remove it. */ #ifndef EVP_PKEY_ED448 #define EVP_PKEY_ED448 NID_ED448 #endif /* This is tied to poly1305 support so we reuse the Cryptography_HAS_POLY1305 conditional to remove it. */ #ifndef EVP_PKEY_POLY1305 #define EVP_PKEY_POLY1305 NID_poly1305 #endif #if CRYPTOGRAPHY_OPENSSL_300_OR_GREATER static const long Cryptography_HAS_300_FIPS = 1; #else static const long Cryptography_HAS_300_FIPS = 0; int (*EVP_default_properties_is_fips_enabled)(OSSL_LIB_CTX *) = NULL; int (*EVP_default_properties_enable_fips)(OSSL_LIB_CTX *, int) = NULL; #endif #if CRYPTOGRAPHY_IS_BORINGSSL static const long Cryptography_HAS_EVP_PKEY_DH = 0; int (*EVP_PKEY_set1_DH)(EVP_PKEY *, DH *) = NULL; #else static const long Cryptography_HAS_EVP_PKEY_DH = 1; #endif """
38.242321
79
0.735564
795a49972034beb2859bf32375a487c14ca6255b
1,759
py
Python
python/Microsoftpython/Class 23:inheritance/class 23:inheritance.py
HeisenbergChueng/python-studynote
fc032316a6e69ee538c7592b548e7319a33a7954
[ "CC0-1.0" ]
453
2021-12-13T16:13:22.000Z
2021-12-19T01:30:05.000Z
python/Microsoftpython/Class 23:inheritance/class 23:inheritance.py
HeisenbergChueng/python-studynote
fc032316a6e69ee538c7592b548e7319a33a7954
[ "CC0-1.0" ]
null
null
null
python/Microsoftpython/Class 23:inheritance/class 23:inheritance.py
HeisenbergChueng/python-studynote
fc032316a6e69ee538c7592b548e7319a33a7954
[ "CC0-1.0" ]
59
2021-12-13T16:14:17.000Z
2021-12-15T17:14:11.000Z
# 以下為本課借用上堂課的例子 class Person: def __init__(self,name): self.name = name def say_hello(self): print("Hello," + self.name) # 以下為本課例子,子類Student繼承自Person,繼承的關係是person包含了student,student是person的一部份 # 可以用英文表達繼承就是,student is a person但不是所有person都是student class Student(Person): # 在子類Student中,若要使用父類Person的屬性,則必須使用super(),如下便使用了父類的name屬性 def __init__(self,name,school): super().__init__(name) self.school = school def sing_school_song(self): print('Ode to' + self.school) def say_hello(self): super().say_hello() print('I am rather tired') # 同時,一切的類皆為object(python語言)的子類,所以一切如str、int、float、list、都可以在class中以寫死方式使用 def __str__(self): return f'Student {self.name} from {self.school}' student = Student('Heisenberg', 'UMD') # 此處可以看見,特殊參數self為此class的主要物件,heisenberg為name,UMD為school student.say_hello() # 對應def say_hello()那段 student.sing_school_song() # 對應def sing_school_song()那段 print(student) # 在class中寫死方式使用__str__()方法,就可以讓print()方法輸出的字串變成我們想要的 print() # isinstance()方法,可以檢查一個物件是否屬於某個類別,如果是,則回傳True,否則回傳False # 如果要檢查物件student是否為Student類別,則可以用isinstance(student,Student) # 如果要檢查物件student是否為Person類別,則可以用isinstance(student,Person) # 如果要檢查class Student是否為class Person的子類,則可以用issubclass(Student,Person) print(f'Is this a student? {isinstance(student,Student)}') print(f'Is this a person? {isinstance(student,Person)}') print(f'Is Student a Person? {issubclass(Student,Person)}') print() # 多給一個單獨使用繼承object的類別的__str__()方法,就可以讓print()方法輸出的字串變成我們想要的 class Presenter: def __init__(self,name): self.name = name def say_hello(self): print("Hello," + self.name) def __str__(self): return self.name presenter = Presenter('Heisenberg') print(presenter)
33.826923
95
0.739625
795a4b6ff2c1f7aac6a9a38023794b6eb28b8124
1,682
py
Python
polygon_area/gui/qt4/widgets/__init__.py
nycholas/polygon-area
748e9a36d022234c8d4f17546b1e2b6dcd5ed1fe
[ "BSD-3-Clause" ]
2
2017-01-02T15:31:36.000Z
2021-06-30T11:15:06.000Z
polygon_area/gui/qt4/widgets/__init__.py
nycholas/polygon-area
748e9a36d022234c8d4f17546b1e2b6dcd5ed1fe
[ "BSD-3-Clause" ]
null
null
null
polygon_area/gui/qt4/widgets/__init__.py
nycholas/polygon-area
748e9a36d022234c8d4f17546b1e2b6dcd5ed1fe
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Calculate the area of the polygon. # Copyright (c) 2011, Nycholas de Oliveira e Oliveira <nycholas@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the Nycholas de Oliveira e Oliveira nor the names of # its contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.
54.258065
78
0.776457
795a4c111bccd2da6bdfc16e2c69b2de8500e236
3,686
py
Python
bouncing_box/player.py
JSlowgrove/Bouncing-Box
e9334616e1946cdb7426680e423bd458002613dd
[ "MIT" ]
null
null
null
bouncing_box/player.py
JSlowgrove/Bouncing-Box
e9334616e1946cdb7426680e423bd458002613dd
[ "MIT" ]
null
null
null
bouncing_box/player.py
JSlowgrove/Bouncing-Box
e9334616e1946cdb7426680e423bd458002613dd
[ "MIT" ]
null
null
null
"""A module that contains the class and functions for the Player.""" import pygame class Player: """ This class contains all of the functions and variables that is used by the Player. """ # The Player's sprite. Universal to all instances of Player. sprite = pygame.image.load('assets/images/player.png') # The Player's Dimensions. Universal to all instances of Player. dimensions = pygame.math.Vector2(sprite.get_width(), sprite.get_height()) # The Player's maximum fall velocity. Universal to all instances of Player. maxVelocity = 500.0 def __init__(self, pos): """ The Player constructor. :param pos: The initial value of the Player position. :type pos: class:`pygame.math.Vector2` """ # The position of this instance of the Player. self.pos = pos # The y velocity of this instance of the Player. self.velocity = 0.0 def setPos(self, pos): """ The Player position setter. :param pos: The new value of the Player's position. :type pos: class:`pygame.math.Vector2` """ self.pos = pos def setX(self, x): """ The Player x position setter. :param x: The new value of the Player's x position. :type x: float """ self.pos.x = x def setY(self, y): """ The Player y position setter. :param y: The new value of the Player's y position. :type y: float """ self.pos.y = y def getPos(self): """ The Player position getter. :return: The Player's position. :rtype: class:`pygame.math.Vector2` """ return self.pos def getX(self): """ The Player x position getter. :return: The Player's x position. :rtype: float """ return self.pos.x def getY(self): """ The Player y position getter. :return: The Player's y position. :rtype: float """ return self.pos.y def getDimensions(self): """ The Player Dimensions getter. :return: The Player's dimensions. :rtype: class:`pygame.math.Vector2` """ return self.dimensions def getWidth(self): """ The Player width getter. :return: The Player's width. :rtype: float """ return self.dimensions.x def getHeight(self): """ The Player height getter. :return: The Player's height. :rtype: float """ return self.dimensions.y def jump(self): """ A function to make the player jump by setting the velocity to launch it up. """ self.velocity = -750.0 def update(self, dt): """ A function to update the Player. :param dt: The delta time. :type dt: float """ # If the velocity is less than the max. if self.velocity < self.maxVelocity: # Increase the velocity self.velocity += 50.0 # Update the player position on the screen. self.pos.y += (self.velocity * dt) # Make sure that the Player does not go above the screen if self.pos.y < 0.0: self.pos.y = 0.0 def draw(self, screen): """ A function to draw the Player to the screen. :param screen: The screen to draw to. :type screen: class `pygame.Surface` """ # Draw the sprite to the screen at the current player's position. screen.blit(self.sprite, (self.getX(), self.getY()))
25.07483
79
0.556972
795a4c1bfcd51d93ac77149dbb23b12fc1c26f21
2,784
py
Python
data/ansible-module-template.py
trskop/hsansible
00b2c5894edcdd6a4af710e28497b3b327fdd87c
[ "BSD-3-Clause" ]
12
2015-01-06T23:59:53.000Z
2021-01-02T13:58:26.000Z
data/ansible-module-template.py
trskop/hsansible
00b2c5894edcdd6a4af710e28497b3b327fdd87c
[ "BSD-3-Clause" ]
1
2021-10-06T12:44:10.000Z
2022-01-12T11:21:42.000Z
data/ansible-module-template.py
trskop/hsansible
00b2c5894edcdd6a4af710e28497b3b327fdd87c
[ "BSD-3-Clause" ]
2
2020-04-25T17:25:26.000Z
2021-11-07T21:13:49.000Z
#!/usr/bin/env python # This file was generated using $program$ $version$ from a template # with following copyringht notice. # # Copyright (c) 2013, Peter Trsko <peter.trsko@gmail.com> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of Peter Trsko nor the names of other # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. $if(documentation)$ DOCUMENTATION = ''' $documentation$''' $endif$ import atexit import base64 import os import stat import subprocess import sys import tempfile try: import json except ImportError: import simplejson as json def remove_temporary_file(fn): if fn is not None: os.remove(fn) def fail_json(msg): print json.dumps(dict(failed=True, msg=msg)) sys.exit(1) def main(): try: fd, fn = tempfile.mkstemp() atexit.register(remove_temporary_file, fn) except Exception as e: fail_json("Error creating temporary file: %s" % str(e)) try: os.fchmod(fd, stat.S_IEXEC) os.write(fd, base64.b64decode(encodedBinary)) os.fsync(fd) os.close(fd) except Exception as e: fail_json("Error recreating executable: %s" % str(e)) try: subprocess.call([fn] + sys.argv[1:]) except Exception as e: fail_json("Error while calling executable: %s" % str(e)) encodedBinary = ''' $encodedBinary$''' if __name__ == '__main__': main()
31.280899
77
0.716236
795a4c54b99ed7e4be96bc8c923f102ba27ab299
43
py
Python
web_delta/__init__.py
N-Buchanan/web_delta
1497d9624ae4afa59d7c44176c479845c4993130
[ "MIT" ]
null
null
null
web_delta/__init__.py
N-Buchanan/web_delta
1497d9624ae4afa59d7c44176c479845c4993130
[ "MIT" ]
null
null
null
web_delta/__init__.py
N-Buchanan/web_delta
1497d9624ae4afa59d7c44176c479845c4993130
[ "MIT" ]
null
null
null
from .web_delta import WebDelta, RateLimit
21.5
42
0.837209
795a4e1be944f02468700a1982c30f5d5020fcb8
579
py
Python
dpnp/pca/GPU/pca.py
geexie/dpbench
7d41409ded3c816f35003bc5aea071852bceb892
[ "BSD-2-Clause" ]
8
2021-03-26T15:17:58.000Z
2022-01-21T21:56:19.000Z
dpnp/pca/GPU/pca.py
geexie/dpbench
7d41409ded3c816f35003bc5aea071852bceb892
[ "BSD-2-Clause" ]
22
2021-03-30T21:20:57.000Z
2022-02-22T13:42:17.000Z
dpnp/pca/GPU/pca.py
geexie/dpbench
7d41409ded3c816f35003bc5aea071852bceb892
[ "BSD-2-Clause" ]
7
2021-03-23T11:00:43.000Z
2022-02-02T12:28:55.000Z
# Copyright (C) 2017-2018 Intel Corporation # # SPDX-License-Identifier: MIT import dpctl import base_pca import dpnp as np def pca_impl(data): tdata = data.T m = np.empty(tdata.shape[0]) # for i in range(tdata.shape[0]): # m[i] = np.mean(tdata[i]) m = np.mean(tdata, axis=1) c = data - m v = np.cov(c.T) values, vectors = np.linalg.eig(v) a = vectors.T b = c.T arr = np.dot(a, b) return arr.T def pca_dpctl(data): with dpctl.device_context("opencl:gpu"): pca_impl(data) base_pca.run("Numba", pca_dpctl)
16.542857
44
0.604491
795a4f0d8015ce6760c1a41920b9b867b5f291ba
167
py
Python
tests/src/helpers/write.py
NVinity/fson
276b4bba05ad23a5725e5f9e631682fa62f0367b
[ "MIT" ]
null
null
null
tests/src/helpers/write.py
NVinity/fson
276b4bba05ad23a5725e5f9e631682fa62f0367b
[ "MIT" ]
null
null
null
tests/src/helpers/write.py
NVinity/fson
276b4bba05ad23a5725e5f9e631682fa62f0367b
[ "MIT" ]
null
null
null
##### type_1 #---# def type_1(data,sink_file_name): #&&&# with open(sink_file_name, "w") as sink_file: sink_file.write(data) #---# return ##### type_1
18.555556
48
0.580838
795a4fc28e89d6456c1ac8ed1e083d75a41fba93
21,542
py
Python
Structured/models/building_blocks/transformers.py
hlzhang109/TransTEE
00e6977147a6dcb3e83f1fe70cd1f4cbef7321a4
[ "MIT" ]
11
2022-02-08T12:50:06.000Z
2022-03-08T15:03:37.000Z
Structured/models/building_blocks/transformers.py
hlzhang109/TransTEE
00e6977147a6dcb3e83f1fe70cd1f4cbef7321a4
[ "MIT" ]
1
2022-03-30T08:32:24.000Z
2022-03-31T14:01:04.000Z
Structured/models/building_blocks/transformers.py
hlzhang109/TransTEE
00e6977147a6dcb3e83f1fe70cd1f4cbef7321a4
[ "MIT" ]
null
null
null
import copy from typing import Optional, Any import numpy as np import torch from torch import Tensor, nn from torch.nn.parameter import Parameter import torch.nn.functional as F from torch.nn.modules.module import Module from torch.nn.modules.container import ModuleList from torch.nn.modules.batchnorm import BatchNorm1d from torch.nn.init import xavier_uniform_, constant_ from torch.nn.modules.dropout import Dropout from torch.nn.modules.linear import Linear, NonDynamicallyQuantizableLinear from torch.nn.modules.normalization import LayerNorm class MultiheadAttention(Module): r"""Allows the model to jointly attend to information from different representation subspaces. See reference: Attention Is All You Need .. math:: \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V) Args: embed_dim: total dimension of the model. num_heads: parallel attention heads. dropout: a Dropout layer on attn_output_weights. Default: 0.0. bias: add bias as module parameter. Default: True. add_bias_kv: add bias to the key and value sequences at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. kdim: total number of features in key. Default: None. vdim: total number of features in value. Default: None. Note: if kdim and vdim are None, they will be set to embed_dim such that query, key, and value have the same number of features. Examples:: >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads) >>> attn_output, attn_output_weights = multihead_attn(query, key, value) """ bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None): super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" if self._qkv_same_embed_dim is False: self.q_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) self.k_proj_weight = Parameter(torch.Tensor(embed_dim, self.kdim)) self.v_proj_weight = Parameter(torch.Tensor(embed_dim, self.vdim)) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty(3 * embed_dim, embed_dim)) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) if bias: self.in_proj_bias = Parameter(torch.empty(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = NonDynamicallyQuantizableLinear(embed_dim, embed_dim) if add_bias_kv: self.bias_k = Parameter(torch.empty(1, 1, embed_dim)) self.bias_v = Parameter(torch.empty(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self._reset_parameters() def _reset_parameters(self): if self._qkv_same_embed_dim: xavier_uniform_(self.in_proj_weight) else: xavier_uniform_(self.q_proj_weight) xavier_uniform_(self.k_proj_weight) xavier_uniform_(self.v_proj_weight) if self.in_proj_bias is not None: constant_(self.in_proj_bias, 0.) constant_(self.out_proj.bias, 0.) if self.bias_k is not None: xavier_normal_(self.bias_k) if self.bias_v is not None: xavier_normal_(self.bias_v) def __setstate__(self, state): # Support loading old MultiheadAttention checkpoints generated by v1.1.0 if '_qkv_same_embed_dim' not in state: state['_qkv_same_embed_dim'] = True super(MultiheadAttention, self).__setstate__(state) def forward(self, query, key, value, key_padding_mask=None, need_weights=True, attn_mask=None): # type: (Tensor, Tensor, Tensor, Optional[Tensor], bool, Optional[Tensor]) -> Tuple[Tensor, Optional[Tensor]] r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a byte mask and a value is non-zero, the corresponding value on the attention layer will be ignored need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. Shape: - Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the position with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. """ if not self._qkv_same_embed_dim: return F.multi_head_attention_forward( query, key, value, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask, use_separate_proj_weight=True, q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) else: return F.multi_head_attention_forward( query, key, value, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask) class TransformerEncoder(Module): r"""TransformerEncoder is a stack of N encoder layers Args: encoder_layer: an instance of the TransformerEncoderLayer() class (required). num_layers: the number of sub-encoder-layers in the encoder (required). norm: the layer normalization component (optional). Examples:: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) >>> transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6) >>> src = torch.rand(10, 32, 512) >>> out = transformer_encoder(src) """ __constants__ = ['norm'] def __init__(self, encoder_layer, num_layers, norm=None): super(TransformerEncoder, self).__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src: Tensor, mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None) : r"""Pass the input through the encoder layers in turn. Args: src: the sequence to the encoder (required). mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """ output = src for mod in self.layers: output = mod(output, src_mask=mask, src_key_padding_mask=src_key_padding_mask) if self.norm is not None: output = self.norm(output) return output class TransformerDecoder(Module): r"""TransformerDecoder is a stack of N decoder layers Args: decoder_layer: an instance of the TransformerDecoderLayer() class (required). num_layers: the number of sub-decoder-layers in the decoder (required). norm: the layer normalization component (optional). Examples:: >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) >>> transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=6) >>> memory = torch.rand(10, 32, 512) >>> tgt = torch.rand(20, 32, 512) >>> out = transformer_decoder(tgt, memory) """ __constants__ = ['norm'] def __init__(self, decoder_layer, num_layers, norm=None): super(TransformerDecoder, self).__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None): r"""Pass the inputs (and mask) through the decoder layer in turn. Args: tgt: the sequence to the decoder (required). memory: the sequence from the last layer of the encoder (required). tgt_mask: the mask for the tgt sequence (optional). memory_mask: the mask for the memory sequence (optional). tgt_key_padding_mask: the mask for the tgt keys per batch (optional). memory_key_padding_mask: the mask for the memory keys per batch (optional). Shape: see the docs in Transformer class. """ output = tgt for mod in self.layers: output = mod(output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask) if self.norm is not None: output = self.norm(output) return output class TransformerDecoderLayer(Module): r"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. This standard decoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). Examples:: >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) >>> memory = torch.rand(10, 32, 512) >>> tgt = torch.rand(20, 32, 512) >>> out = decoder_layer(tgt, memory) """ def __init__(self, d_model, nhead=2, dim_feedforward=2048, dropout=0.1, activation="relu", num_t=1): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = Linear(d_model, dim_feedforward) self.dropout = Dropout(dropout) self.linear2 = Linear(dim_feedforward, d_model) self.norm1 = BatchNorm1d(num_t) self.norm2 = BatchNorm1d(num_t) self.norm3 = BatchNorm1d(num_t) self.dropout1 = Dropout(dropout) self.dropout2 = Dropout(dropout) self.dropout3 = Dropout(dropout) self.activation = _get_activation_fn(activation) def __setstate__(self, state): if 'activation' not in state: state['activation'] = F.relu super(TransformerDecoderLayer, self).__setstate__(state) def forward(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None): r"""Pass the inputs (and mask) through the decoder layer. Args: tgt: the sequence to the decoder layer (required). memory: the sequence from the last layer of the encoder (required). tgt_mask: the mask for the tgt sequence (optional). memory_mask: the mask for the memory sequence (optional). tgt_key_padding_mask: the mask for the tgt keys per batch (optional). memory_key_padding_mask: the mask for the memory keys per batch (optional). Shape: see the docs in Transformer class. """ tgt2 = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt.permute(1, 0, 2)).permute(1, 0, 2) tgt2, weight = self.multihead_attn(tgt, memory, memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask) tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt.permute(1, 0, 2)) tgt = tgt.permute(1, 0, 2) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt.permute(1, 0, 2)) return tgt.permute(1, 0, 2) def _get_clones(module, N): return ModuleList([copy.deepcopy(module) for i in range(N)]) def _get_activation_fn(activation): if activation == "relu": return F.relu elif activation == "gelu": return F.gelu raise RuntimeError("activation should be relu/gelu, not {}".format(activation)) class TransformerEncoderLayer(Module): r"""TransformerEncoderLayer is made up of self-attn and feedforward network. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). Examples:: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) >>> src = torch.rand(10, 32, 512) >>> out = encoder_layer(src) """ def __init__(self, d_model, nhead, dim_feedforward=50, dropout=0.1, activation="relu", num_cov=25): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = Linear(d_model, dim_feedforward) self.dropout = Dropout(dropout) self.linear2 = Linear(dim_feedforward, d_model) self.norm1 = BatchNorm1d(num_cov) self.norm2 = BatchNorm1d(num_cov) self.dropout1 = Dropout(dropout) self.dropout2 = Dropout(dropout) self.activation = _get_activation_fn(activation) def __setstate__(self, state): if 'activation' not in state: state['activation'] = F.relu super(TransformerEncoderLayer, self).__setstate__(state) def forward(self, src: Tensor, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None): r"""Pass the input through the encoder layer. Args: src: the sequence to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """ src = src.permute(1, 0, 2) src2 = self.self_attn(src, src, src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = src + self.dropout1(src2) src = self.norm1(src.permute(1, 0, 2)) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src class Embeddings(nn.Module): def __init__(self, emb_size, act=None, initrange=0.01, res=0): super(Embeddings, self).__init__() self.treat_weight = nn.Linear(1, emb_size) self.initrange = initrange self.res = res if res: self.emb_size = emb_size + 1 else: self.emb_size = emb_size if act == 'relu': self.act = nn.ReLU(inplace=True) elif act == 'tanh': self.act = nn.Tanh() elif act == 'sigmoid': self.act = nn.Sigmoid() else: self.act = None self.init_weights() def forward(self, tokens): ebd = self.treat_weight(tokens.unsqueeze(-1).to(torch.float32)) if self.res: ebd = torch.cat([torch.ones(ebd.shape[0],1).cuda(), ebd], dim=-1) if self.act is None: return ebd return self.act(ebd) def init_weights(self) -> None: self.treat_weight.weight.data.normal_(0, self.initrange) self.treat_weight.bias.data.zero_() class TransformerModel(nn.Module): def __init__(self, ntoken: int, d_model: int = 50, nhead: int = 5, d_hid: int = 50, nlayers: int = 1, dropout: float = 0.1): super().__init__() self.model_type = 'Transformer' encoder_layers = TransformerEncoderLayer(d_model, nhead, d_hid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) self.encoder = nn.Embedding(ntoken, d_model) self.d_model = d_model self.decoder = nn.Linear(d_model, ntoken) self.init_weights() def init_weights(self) -> None: initrange = 0.1 self.encoder.weight.data.uniform_(-initrange, initrange) self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, src: Tensor, src_mask: Tensor) -> Tensor: """ Args: src: Tensor, shape [seq_len, batch_size] src_mask: Tensor, shape [seq_len, seq_len] Returns: output Tensor of shape [seq_len, batch_size, ntoken] """ src = self.encoder(src) * math.sqrt(self.d_model) src = self.pos_encoder(src) output = self.transformer_encoder(src, src_mask) output = self.decoder(output) return output
44.416495
130
0.653003
795a50a82805e75b9e254c7503f91714c5db3370
18,166
py
Python
Lib/test/test_pkgutil.py
rng-dynamics/RustPython
6165aadcc4e80e0f48f3e784e17b3c7f80d21a8a
[ "CC-BY-4.0", "MIT" ]
null
null
null
Lib/test/test_pkgutil.py
rng-dynamics/RustPython
6165aadcc4e80e0f48f3e784e17b3c7f80d21a8a
[ "CC-BY-4.0", "MIT" ]
null
null
null
Lib/test/test_pkgutil.py
rng-dynamics/RustPython
6165aadcc4e80e0f48f3e784e17b3c7f80d21a8a
[ "CC-BY-4.0", "MIT" ]
null
null
null
from test.support import run_unittest from test.support.import_helper import unload, CleanImport from test.support.warnings_helper import check_warnings import unittest import sys import importlib from importlib.util import spec_from_file_location import pkgutil import os import os.path import tempfile import shutil import zipfile # Note: pkgutil.walk_packages is currently tested in test_runpy. This is # a hack to get a major issue resolved for 3.3b2. Longer term, it should # be moved back here, perhaps by factoring out the helper code for # creating interesting package layouts to a separate module. # Issue #15348 declares this is indeed a dodgy hack ;) class PkgutilTests(unittest.TestCase): def setUp(self): self.dirname = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.dirname) sys.path.insert(0, self.dirname) def tearDown(self): del sys.path[0] def test_getdata_filesys(self): pkg = 'test_getdata_filesys' # Include a LF and a CRLF, to test that binary data is read back RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources package_dir = os.path.join(self.dirname, pkg) os.mkdir(package_dir) # Empty init.py f = open(os.path.join(package_dir, '__init__.py'), "wb") f.close() # Resource files, res.txt, sub/res.txt f = open(os.path.join(package_dir, 'res.txt'), "wb") f.write(RESOURCE_DATA) f.close() os.mkdir(os.path.join(package_dir, 'sub')) f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb") f.write(RESOURCE_DATA) f.close() # Check we can read the resources res1 = pkgutil.get_data(pkg, 'res.txt') self.assertEqual(res1, RESOURCE_DATA) res2 = pkgutil.get_data(pkg, 'sub/res.txt') self.assertEqual(res2, RESOURCE_DATA) del sys.modules[pkg] def test_getdata_zipfile(self): zip = 'test_getdata_zipfile.zip' pkg = 'test_getdata_zipfile' # Include a LF and a CRLF, to test that binary data is read back RESOURCE_DATA = b'Hello, world!\nSecond line\r\nThird line' # Make a package with some resources zip_file = os.path.join(self.dirname, zip) z = zipfile.ZipFile(zip_file, 'w') # Empty init.py z.writestr(pkg + '/__init__.py', "") # Resource files, res.txt, sub/res.txt z.writestr(pkg + '/res.txt', RESOURCE_DATA) z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA) z.close() # Check we can read the resources sys.path.insert(0, zip_file) res1 = pkgutil.get_data(pkg, 'res.txt') self.assertEqual(res1, RESOURCE_DATA) res2 = pkgutil.get_data(pkg, 'sub/res.txt') self.assertEqual(res2, RESOURCE_DATA) names = [] for moduleinfo in pkgutil.iter_modules([zip_file]): self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) names.append(moduleinfo.name) self.assertEqual(names, ['test_getdata_zipfile']) del sys.path[0] del sys.modules[pkg] def test_unreadable_dir_on_syspath(self): # issue7367 - walk_packages failed if unreadable dir on sys.path package_name = "unreadable_package" d = os.path.join(self.dirname, package_name) # this does not appear to create an unreadable dir on Windows # but the test should not fail anyway os.mkdir(d, 0) self.addCleanup(os.rmdir, d) for t in pkgutil.walk_packages(path=[self.dirname]): self.fail("unexpected package found") def test_walkpackages_filesys(self): pkg1 = 'test_walkpackages_filesys' pkg1_dir = os.path.join(self.dirname, pkg1) os.mkdir(pkg1_dir) f = open(os.path.join(pkg1_dir, '__init__.py'), "wb") f.close() os.mkdir(os.path.join(pkg1_dir, 'sub')) f = open(os.path.join(pkg1_dir, 'sub', '__init__.py'), "wb") f.close() f = open(os.path.join(pkg1_dir, 'sub', 'mod.py'), "wb") f.close() # Now, to juice it up, let's add the opposite packages, too. pkg2 = 'sub' pkg2_dir = os.path.join(self.dirname, pkg2) os.mkdir(pkg2_dir) f = open(os.path.join(pkg2_dir, '__init__.py'), "wb") f.close() os.mkdir(os.path.join(pkg2_dir, 'test_walkpackages_filesys')) f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', '__init__.py'), "wb") f.close() f = open(os.path.join(pkg2_dir, 'test_walkpackages_filesys', 'mod.py'), "wb") f.close() expected = [ 'sub', 'sub.test_walkpackages_filesys', 'sub.test_walkpackages_filesys.mod', 'test_walkpackages_filesys', 'test_walkpackages_filesys.sub', 'test_walkpackages_filesys.sub.mod', ] actual= [e[1] for e in pkgutil.walk_packages([self.dirname])] self.assertEqual(actual, expected) for pkg in expected: if pkg.endswith('mod'): continue del sys.modules[pkg] def test_walkpackages_zipfile(self): """Tests the same as test_walkpackages_filesys, only with a zip file.""" zip = 'test_walkpackages_zipfile.zip' pkg1 = 'test_walkpackages_zipfile' pkg2 = 'sub' zip_file = os.path.join(self.dirname, zip) z = zipfile.ZipFile(zip_file, 'w') z.writestr(pkg2 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/__init__.py', "") z.writestr(pkg2 + '/' + pkg1 + '/mod.py', "") z.writestr(pkg1 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/__init__.py', "") z.writestr(pkg1 + '/' + pkg2 + '/mod.py', "") z.close() sys.path.insert(0, zip_file) expected = [ 'sub', 'sub.test_walkpackages_zipfile', 'sub.test_walkpackages_zipfile.mod', 'test_walkpackages_zipfile', 'test_walkpackages_zipfile.sub', 'test_walkpackages_zipfile.sub.mod', ] actual= [e[1] for e in pkgutil.walk_packages([zip_file])] self.assertEqual(actual, expected) del sys.path[0] for pkg in expected: if pkg.endswith('mod'): continue del sys.modules[pkg] # TODO: RUSTPYTHON @unittest.expectedFailure def test_walk_packages_raises_on_string_or_bytes_input(self): str_input = 'test_dir' with self.assertRaises((TypeError, ValueError)): list(pkgutil.walk_packages(str_input)) bytes_input = b'test_dir' with self.assertRaises((TypeError, ValueError)): list(pkgutil.walk_packages(bytes_input)) class PkgutilPEP302Tests(unittest.TestCase): class MyTestLoader(object): def create_module(self, spec): return None def exec_module(self, mod): # Count how many times the module is reloaded mod.__dict__['loads'] = mod.__dict__.get('loads', 0) + 1 def get_data(self, path): return "Hello, world!" class MyTestImporter(object): def find_spec(self, fullname, path=None, target=None): loader = PkgutilPEP302Tests.MyTestLoader() return spec_from_file_location(fullname, '<%s>' % loader.__class__.__name__, loader=loader, submodule_search_locations=[]) def setUp(self): sys.meta_path.insert(0, self.MyTestImporter()) def tearDown(self): del sys.meta_path[0] def test_getdata_pep302(self): # Use a dummy finder/loader self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") del sys.modules['foo'] def test_alreadyloaded(self): # Ensure that get_data works without reloading - the "loads" module # variable in the example loader should count how many times a reload # occurs. import foo self.assertEqual(foo.loads, 1) self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!") self.assertEqual(foo.loads, 1) del sys.modules['foo'] # These tests, especially the setup and cleanup, are hideous. They # need to be cleaned up once issue 14715 is addressed. class ExtendPathTests(unittest.TestCase): def create_init(self, pkgname): dirname = tempfile.mkdtemp() sys.path.insert(0, dirname) pkgdir = os.path.join(dirname, pkgname) os.mkdir(pkgdir) with open(os.path.join(pkgdir, '__init__.py'), 'w') as fl: fl.write('from pkgutil import extend_path\n__path__ = extend_path(__path__, __name__)\n') return dirname def create_submodule(self, dirname, pkgname, submodule_name, value): module_name = os.path.join(dirname, pkgname, submodule_name + '.py') with open(module_name, 'w') as fl: print('value={}'.format(value), file=fl) def test_simple(self): pkgname = 'foo' dirname_0 = self.create_init(pkgname) dirname_1 = self.create_init(pkgname) self.create_submodule(dirname_0, pkgname, 'bar', 0) self.create_submodule(dirname_1, pkgname, 'baz', 1) import foo.bar import foo.baz # Ensure we read the expected values self.assertEqual(foo.bar.value, 0) self.assertEqual(foo.baz.value, 1) # Ensure the path is set up correctly self.assertEqual(sorted(foo.__path__), sorted([os.path.join(dirname_0, pkgname), os.path.join(dirname_1, pkgname)])) # Cleanup shutil.rmtree(dirname_0) shutil.rmtree(dirname_1) del sys.path[0] del sys.path[0] del sys.modules['foo'] del sys.modules['foo.bar'] del sys.modules['foo.baz'] # Another awful testing hack to be cleaned up once the test_runpy # helpers are factored out to a common location def test_iter_importers(self): iter_importers = pkgutil.iter_importers get_importer = pkgutil.get_importer pkgname = 'spam' modname = 'eggs' dirname = self.create_init(pkgname) pathitem = os.path.join(dirname, pkgname) fullname = '{}.{}'.format(pkgname, modname) sys.modules.pop(fullname, None) sys.modules.pop(pkgname, None) try: self.create_submodule(dirname, pkgname, modname, 0) importlib.import_module(fullname) importers = list(iter_importers(fullname)) expected_importer = get_importer(pathitem) for finder in importers: spec = pkgutil._get_spec(finder, fullname) loader = spec.loader try: loader = loader.loader except AttributeError: # For now we still allow raw loaders from # find_module(). pass self.assertIsInstance(finder, importlib.machinery.FileFinder) self.assertEqual(finder, expected_importer) self.assertIsInstance(loader, importlib.machinery.SourceFileLoader) self.assertIsNone(pkgutil._get_spec(finder, pkgname)) with self.assertRaises(ImportError): list(iter_importers('invalid.module')) with self.assertRaises(ImportError): list(iter_importers('.spam')) finally: shutil.rmtree(dirname) del sys.path[0] try: del sys.modules['spam'] del sys.modules['spam.eggs'] except KeyError: pass def test_mixed_namespace(self): pkgname = 'foo' dirname_0 = self.create_init(pkgname) dirname_1 = self.create_init(pkgname) self.create_submodule(dirname_0, pkgname, 'bar', 0) # Turn this into a PEP 420 namespace package os.unlink(os.path.join(dirname_0, pkgname, '__init__.py')) self.create_submodule(dirname_1, pkgname, 'baz', 1) import foo.bar import foo.baz # Ensure we read the expected values self.assertEqual(foo.bar.value, 0) self.assertEqual(foo.baz.value, 1) # Ensure the path is set up correctly self.assertEqual(sorted(foo.__path__), sorted([os.path.join(dirname_0, pkgname), os.path.join(dirname_1, pkgname)])) # Cleanup shutil.rmtree(dirname_0) shutil.rmtree(dirname_1) del sys.path[0] del sys.path[0] del sys.modules['foo'] del sys.modules['foo.bar'] del sys.modules['foo.baz'] # XXX: test .pkg files class NestedNamespacePackageTest(unittest.TestCase): def setUp(self): self.basedir = tempfile.mkdtemp() self.old_path = sys.path[:] def tearDown(self): sys.path[:] = self.old_path shutil.rmtree(self.basedir) def create_module(self, name, contents): base, final = name.rsplit('.', 1) base_path = os.path.join(self.basedir, base.replace('.', os.path.sep)) os.makedirs(base_path, exist_ok=True) with open(os.path.join(base_path, final + ".py"), 'w') as f: f.write(contents) def test_nested(self): pkgutil_boilerplate = ( 'import pkgutil; ' '__path__ = pkgutil.extend_path(__path__, __name__)') self.create_module('a.pkg.__init__', pkgutil_boilerplate) self.create_module('b.pkg.__init__', pkgutil_boilerplate) self.create_module('a.pkg.subpkg.__init__', pkgutil_boilerplate) self.create_module('b.pkg.subpkg.__init__', pkgutil_boilerplate) self.create_module('a.pkg.subpkg.c', 'c = 1') self.create_module('b.pkg.subpkg.d', 'd = 2') sys.path.insert(0, os.path.join(self.basedir, 'a')) sys.path.insert(0, os.path.join(self.basedir, 'b')) import pkg self.addCleanup(unload, 'pkg') self.assertEqual(len(pkg.__path__), 2) import pkg.subpkg self.addCleanup(unload, 'pkg.subpkg') self.assertEqual(len(pkg.subpkg.__path__), 2) from pkg.subpkg.c import c from pkg.subpkg.d import d self.assertEqual(c, 1) self.assertEqual(d, 2) class ImportlibMigrationTests(unittest.TestCase): # With full PEP 302 support in the standard import machinery, the # PEP 302 emulation in this module is in the process of being # deprecated in favour of importlib proper def check_deprecated(self): return check_warnings( ("This emulation is deprecated, use 'importlib' instead", DeprecationWarning)) def test_importer_deprecated(self): with self.check_deprecated(): pkgutil.ImpImporter("") def test_loader_deprecated(self): with self.check_deprecated(): pkgutil.ImpLoader("", "", "", "") def test_get_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.get_loader("sys")) self.assertIsNotNone(pkgutil.get_loader("os")) self.assertIsNotNone(pkgutil.get_loader("test.support")) self.assertEqual(len(w.warnings), 0) @unittest.skipIf(__name__ == '__main__', 'not compatible with __main__') def test_get_loader_handles_missing_loader_attribute(self): global __loader__ this_loader = __loader__ del __loader__ try: with check_warnings() as w: self.assertIsNotNone(pkgutil.get_loader(__name__)) self.assertEqual(len(w.warnings), 0) finally: __loader__ = this_loader def test_get_loader_handles_missing_spec_attribute(self): name = 'spam' mod = type(sys)(name) del mod.__spec__ with CleanImport(name): sys.modules[name] = mod loader = pkgutil.get_loader(name) self.assertIsNone(loader) def test_get_loader_handles_spec_attribute_none(self): name = 'spam' mod = type(sys)(name) mod.__spec__ = None with CleanImport(name): sys.modules[name] = mod loader = pkgutil.get_loader(name) self.assertIsNone(loader) def test_get_loader_None_in_sys_modules(self): name = 'totally bogus' sys.modules[name] = None try: loader = pkgutil.get_loader(name) finally: del sys.modules[name] self.assertIsNone(loader) def test_find_loader_missing_module(self): name = 'totally bogus' loader = pkgutil.find_loader(name) self.assertIsNone(loader) def test_find_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.find_loader("sys")) self.assertIsNotNone(pkgutil.find_loader("os")) self.assertIsNotNone(pkgutil.find_loader("test.support")) self.assertEqual(len(w.warnings), 0) def test_get_importer_avoids_emulation(self): # We use an illegal path so *none* of the path hooks should fire with check_warnings() as w: self.assertIsNone(pkgutil.get_importer("*??")) self.assertEqual(len(w.warnings), 0) def test_iter_importers_avoids_emulation(self): with check_warnings() as w: for importer in pkgutil.iter_importers(): pass self.assertEqual(len(w.warnings), 0) def test_main(): run_unittest(PkgutilTests, PkgutilPEP302Tests, ExtendPathTests, NestedNamespacePackageTest, ImportlibMigrationTests) # this is necessary if test is run repeated (like when finding leaks) import zipimport import importlib zipimport._zip_directory_cache.clear() importlib.invalidate_caches() if __name__ == '__main__': test_main()
35.972277
101
0.613564
795a524760b05d544d0c40a4462f847b574b64c0
1,706
py
Python
app/core/migrations/0001_initial.py
utkj97/recipe-app-api
9379a921480b904a1bfd2eb5a20f7f4bed473860
[ "MIT" ]
null
null
null
app/core/migrations/0001_initial.py
utkj97/recipe-app-api
9379a921480b904a1bfd2eb5a20f7f4bed473860
[ "MIT" ]
null
null
null
app/core/migrations/0001_initial.py
utkj97/recipe-app-api
9379a921480b904a1bfd2eb5a20f7f4bed473860
[ "MIT" ]
null
null
null
# Generated by Django 2.2.1 on 2019-05-31 15:51 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='UserModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=255, unique=True)), ('name', models.CharField(max_length=255)), ('is_active', models.BooleanField(default=True)), ('is_staff', models.BooleanField(default=False)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'abstract': False, }, ), ]
50.176471
266
0.638335
795a5286b40fc4660e9a6cc6189c0d1aa07dc5ac
7,352
py
Python
venv/lib/python3.6/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_lldp_interface.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_lldp_interface.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_lldp_interface.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
#!/usr/bin/python # # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: onyx_lldp_interface author: "Samer Deeb (@samerd)" short_description: Manage LLDP interfaces configuration on Mellanox ONYX network devices description: - This module provides declarative management of LLDP interfaces configuration on Mellanox ONYX network devices. options: name: description: - Name of the interface LLDP should be configured on. aggregate: description: List of interfaces LLDP should be configured on. purge: description: - Purge interfaces not defined in the aggregate parameter. type: bool default: false state: description: - State of the LLDP configuration. default: present choices: ['present', 'absent', 'enabled', 'disabled'] ''' EXAMPLES = """ - name: Configure LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: present - name: Disable LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: disabled - name: Enable LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: enabled - name: Delete LLDP on specific interfaces onyx_lldp_interface: name: Eth1/1 state: absent - name: Create aggregate of LLDP interface configurations onyx_lldp_interface: aggregate: - { name: Eth1/1 } - { name: Eth1/2 } state: present - name: Delete aggregate of LLDP interface configurations onyx_lldp_interface: aggregate: - { name: Eth1/1 } - { name: Eth1/2 } state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always. type: list sample: - interface ethernet 1/1 lldp transmit - interface ethernet 1/1 lldp receive """ import re from copy import deepcopy from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import remove_default_spec from ansible_collections.mellanox.onyx.plugins.module_utils.network.onyx.onyx import BaseOnyxModule from ansible_collections.mellanox.onyx.plugins.module_utils.network.onyx.onyx import show_cmd class OnyxLldpInterfaceModule(BaseOnyxModule): IF_NAME_REGEX = re.compile(r"^(Eth\d+\/\d+|Eth\d+\/\d+\d+)$") _purge = False @classmethod def _get_element_spec(cls): return dict( name=dict(type='str'), state=dict(default='present', choices=['present', 'absent', 'enabled', 'disabled']), ) @classmethod def _get_aggregate_spec(cls, element_spec): aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) return aggregate_spec def init_module(self): """ module initialization """ element_spec = self._get_element_spec() aggregate_spec = self._get_aggregate_spec(element_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), purge=dict(default=False, type='bool'), ) argument_spec.update(element_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] self._module = AnsibleModule( argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) def get_required_config(self): self._required_config = list() module_params = self._module.params aggregate = module_params.get('aggregate') self._purge = module_params.get('purge', False) if aggregate: for item in aggregate: for key in item: if item.get(key) is None: item[key] = module_params[key] self.validate_param_values(item, item) req_item = item.copy() self._required_config.append(req_item) else: params = { 'name': module_params['name'], 'state': module_params['state'], } self.validate_param_values(params) self._required_config.append(params) def _create_if_lldp_data(self, if_name, if_lldp_data): return { 'name': if_name, 'receive': self.get_config_attr(if_lldp_data, 'Receive'), 'transmit': self.get_config_attr(if_lldp_data, 'Transmit'), } def _get_lldp_config(self): return show_cmd(self._module, "show lldp interfaces") def load_current_config(self): # called in base class in run function self._current_config = dict() lldp_config = self._get_lldp_config() if not lldp_config: return for if_name, if_lldp_data in iteritems(lldp_config): match = self.IF_NAME_REGEX.match(if_name) if not match: continue if if_lldp_data: if_lldp_data = if_lldp_data[0] self._current_config[if_name] = \ self._create_if_lldp_data(if_name, if_lldp_data) def _get_interface_cmd_name(self, if_name): return if_name.replace("Eth", "ethernet ") def _add_if_lldp_commands(self, if_name, flag, enable): cmd_prefix = "interface %s " % self._get_interface_cmd_name(if_name) lldp_cmd = "lldp %s" % flag if not enable: lldp_cmd = 'no %s' % lldp_cmd self._commands.append(cmd_prefix + lldp_cmd) def _gen_lldp_commands(self, if_name, req_state, curr_conf): curr_receive = curr_conf.get('receive') curr_transmit = curr_conf.get('transmit') enable = (req_state == 'Enabled') if curr_receive != req_state: flag = 'receive' self._add_if_lldp_commands(if_name, flag, enable) if curr_transmit != req_state: flag = 'transmit' self._add_if_lldp_commands(if_name, flag, enable) def generate_commands(self): req_interfaces = set() for req_conf in self._required_config: state = req_conf['state'] if_name = req_conf['name'] if state in ('absent', 'disabled'): req_state = 'Disabled' else: req_interfaces.add(if_name) req_state = 'Enabled' curr_conf = self._current_config.get(if_name, {}) self._gen_lldp_commands(if_name, req_state, curr_conf) if self._purge: for if_name, curr_conf in iteritems(self._current_config): if if_name not in req_interfaces: req_state = 'Disabled' self._gen_lldp_commands(if_name, req_state, curr_conf) def main(): """ main entry point for module execution """ OnyxLldpInterfaceModule.main() if __name__ == '__main__': main()
32.675556
111
0.642002
795a52f438de5631d67d31e7432ba5f5d15e705d
3,655
py
Python
nets/components/bidir_text_net.py
acvander/kaggle_real_or_not
737d949b1f8446e734ed5113b84b5b199a7aee3c
[ "MIT" ]
null
null
null
nets/components/bidir_text_net.py
acvander/kaggle_real_or_not
737d949b1f8446e734ed5113b84b5b199a7aee3c
[ "MIT" ]
10
2020-02-11T19:07:36.000Z
2022-02-09T23:35:13.000Z
nets/components/bidir_text_net.py
acvander/kaggle_real_or_not
737d949b1f8446e734ed5113b84b5b199a7aee3c
[ "MIT" ]
null
null
null
from typing import Dict import numpy as np import tensorflow as tf from tensorflow.keras import layers def _add_multiple_lstms(input_layer, num_lstms: int, size: int): lstm_layers = [] # initial layer lstm_layers.append( layers.Bidirectional(layers.LSTM(size, return_sequences=True))(input_layer)) for i in range(1, num_lstms - 1): lstm_layers.append( layers.Bidirectional(layers.LSTM(size, return_sequences=True))( lstm_layers[-1])) # last layer output_layer = layers.Bidirectional(layers.LSTM(size))(lstm_layers[-1]) return output_layer def bidir_text_net(embedding_matrix, max_lens: Dict, tokenizer_len: int = 100, net_scale: int = 64, lstm_depth: int = 6): embedding_size = 100 embedding_dropout = 0.5 mask_zero = False base_sizes = np.array([4, 2, 1]) lstm_sizes = base_sizes * net_scale input_text = layers.Input(shape=(max_lens['text'], ), name='text') embedding_text = layers.Embedding(tokenizer_len, embedding_size, weights=[embedding_matrix], input_length=max_lens['text'], trainable=False, mask_zero=mask_zero)(input_text) dropout_text = layers.Dropout(embedding_dropout)(embedding_text) lstm_text = _add_multiple_lstms(dropout_text, lstm_depth, lstm_sizes[0]) input_ky = layers.Input(shape=(max_lens['keyword'], ), name='keyword') embedding_ky = layers.Embedding(tokenizer_len, embedding_size, weights=[embedding_matrix], input_length=max_lens['keyword'], trainable=False, mask_zero=mask_zero)(input_ky) dropout_ky = layers.Dropout(embedding_dropout)(embedding_ky) lstm_ky = _add_multiple_lstms(dropout_ky, lstm_depth, lstm_sizes[1]) input_loc = layers.Input(shape=(max_lens['location'], ), name='location') embedding_loc = layers.Embedding(tokenizer_len, embedding_size, weights=[embedding_matrix], input_length=max_lens['location'], trainable=False, mask_zero=mask_zero)(input_loc) dropout_loc = layers.Dropout(embedding_dropout)(embedding_loc) lstm_loc = _add_multiple_lstms(dropout_loc, lstm_depth, lstm_sizes[2]) # hashtag branch input_hashtag = layers.Input(shape=(max_lens['hashtags'], ), name='hashtags') embedding_hashtag = layers.Embedding(tokenizer_len, embedding_size, weights=[embedding_matrix], input_length=max_lens['hashtags'], trainable=False, mask_zero=mask_zero)(input_hashtag) dropout_hashtag = layers.Dropout(embedding_dropout)(embedding_hashtag) lstm_hashtag = _add_multiple_lstms(dropout_hashtag, lstm_depth, lstm_sizes[1]) merge = layers.concatenate([lstm_text, lstm_ky, lstm_loc, lstm_hashtag]) input_layers = [input_text, input_loc, input_ky, input_hashtag] return (input_layers, merge)
46.265823
78
0.555951
795a52f974123d50aafb1af1d2d91aa8b5604008
1,881
py
Python
src/django_delayed_union/union.py
roverdotcom/django-delayed-union
b4faae250b1d4755691fb0fd20ff59a3e67c0984
[ "BSD-3-Clause" ]
8
2018-12-10T17:00:30.000Z
2021-11-15T09:52:54.000Z
src/django_delayed_union/union.py
andrew-cybsafe/django-delayed-union
b4faae250b1d4755691fb0fd20ff59a3e67c0984
[ "BSD-3-Clause" ]
20
2018-03-19T15:55:16.000Z
2022-01-17T12:06:22.000Z
src/django_delayed_union/union.py
andrew-cybsafe/django-delayed-union
b4faae250b1d4755691fb0fd20ff59a3e67c0984
[ "BSD-3-Clause" ]
4
2018-09-04T11:16:47.000Z
2021-07-29T14:12:08.000Z
from .base import DelayedQuerySet class DelayedUnionQuerySet(DelayedQuerySet): def __init__(self, *querysets, **kwargs): kwargs.setdefault('all', False) unexpected_kwarg = next((k for k in kwargs.keys() if k != 'all'), None) if unexpected_kwarg: raise TypeError( "received an unexpected keyword argument '{}'".format( unexpected_kwarg ) ) # Handle the case when a DelayedUnionQuerySet is passed in expanded_querysets = [] for queryset in querysets: if isinstance(queryset, DelayedUnionQuerySet): if queryset._kwargs.get('all', False) != kwargs.get('all', False): raise ValueError('incompatible kwargs') expanded_querysets.extend(queryset._querysets) else: expanded_querysets.append(queryset) return super(DelayedUnionQuerySet, self).__init__( *expanded_querysets, **kwargs ) def _apply_operation(self): """ Returs the union of all of the component querysets. """ return self._querysets[0].union(*self._querysets[1:], **self._kwargs) def distinct(self): """ Returns a new :class:`DelayedUnionQuerySet` instance that will select only distinct results. """ clone = self._clone() clone._kwargs['all'] = False return clone def update(self, **kwargs): """ Updates all elements in the component querysets, setting all the given fields to the appropriate values. Returns the total number of (not-necessarily distinct) rows updated. """ total_count = 0 for queryset in self._querysets: total_count += queryset.update(**kwargs) return total_count
34.2
82
0.592238
795a5447e3fec1af3fad27c2fc3b53d312f894f3
96
py
Python
src/robots/concurrency/signals.py
severin-lemaignan/pyrobots
d5dd3bd54375e85802de7225556ad519b8b4e89d
[ "0BSD" ]
11
2017-03-06T17:19:59.000Z
2021-11-04T07:45:33.000Z
src/robots/concurrency/signals.py
severin-lemaignan/pyrobots
d5dd3bd54375e85802de7225556ad519b8b4e89d
[ "0BSD" ]
2
2018-08-18T12:43:47.000Z
2019-04-23T13:03:26.000Z
src/robots/concurrency/signals.py
severin-lemaignan/pyrobots
d5dd3bd54375e85802de7225556ad519b8b4e89d
[ "0BSD" ]
3
2018-04-24T10:25:53.000Z
2021-08-25T04:34:35.000Z
# coding=utf-8 class ActionCancelled(UserWarning): pass class ActionPaused(UserWarning): pass
16
40
0.802083
795a54ced94851d86bdf85ee9e55f7a38e84457b
7,939
py
Python
tests/unit/baskerville_tests/features_tests/test_feature_unique_query_rate.py
equalitie/baskerville
433551d03aee85d5c983ff6b25b388155b54190d
[ "CC-BY-4.0" ]
25
2020-05-19T11:20:47.000Z
2021-09-20T03:15:28.000Z
tests/unit/baskerville_tests/features_tests/test_feature_unique_query_rate.py
mkaranasou/baskerville
433551d03aee85d5c983ff6b25b388155b54190d
[ "CC-BY-4.0" ]
29
2020-05-26T13:21:48.000Z
2021-09-21T06:52:28.000Z
tests/unit/baskerville_tests/features_tests/test_feature_unique_query_rate.py
deflect-ca/baskerville
9659f4b39ab66fcf5329a4eccff15e97245b04f0
[ "CC-BY-4.0" ]
4
2020-06-11T07:00:16.000Z
2021-05-07T09:10:36.000Z
# Copyright (c) 2020, eQualit.ie inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from pyspark.sql import functions as F, types as T from baskerville.util.enums import FeatureComputeType from baskerville.features.feature_unique_query_rate import \ FeatureUniqueQueryRate, FeatureMinutesTotal, FeatureUniqueQueryTotal from tests.unit.baskerville_tests.helpers.spark_testing_base import \ FeatureSparkTestCase class TestSparkUniqueQueryRate(FeatureSparkTestCase): def setUp(self): super(TestSparkUniqueQueryRate, self).setUp() self.feature = FeatureUniqueQueryRate() def test_instance(self): self.assertTrue(hasattr(self.feature, 'feature_name')) self.assertTrue(hasattr(self.feature, 'COLUMNS')) self.assertTrue(hasattr(self.feature, 'DEPENDENCIES')) self.assertTrue(hasattr(self.feature, 'DEFAULT_VALUE')) self.assertTrue(hasattr(self.feature, 'compute_type')) self.assertTrue(self.feature.feature_name == 'unique_query_rate') self.assertTrue( self.feature.columns == ['querystring', '@timestamp']) self.assertTrue(self.feature.dependencies == [FeatureMinutesTotal, FeatureUniqueQueryTotal]) self.assertTrue(self.feature.DEFAULT_VALUE == 1.) self.assertTrue(self.feature.compute_type == FeatureComputeType.rate) self.assertIsNotNone(self.feature.feature_name) self.assertIsNotNone(self.feature.feature_default) self.assertTrue(isinstance(self.feature.feature_name, str)) self.assertTrue(isinstance(self.feature.feature_default, float)) def test_compute_single_record(self): ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:30:00.000Z', "first_ever_request": '2018-01-17T08:30:00.000Z', "content_type": 'html', "client_url": 'page1/page2/page3?query', "querystring": '' } first_ever_request = '2018-01-17T08:30:00.000Z' sub_df = self.get_df_with_extra_cols( self.feature, [ats_record], extra_cols={ 'first_ever_request': F.lit(first_ever_request).cast( 'timestamp' ) } ) result = self.feature.compute(sub_df) expected_df = sub_df.withColumn( self.feature.feature_name, F.lit(self.feature.feature_default).cast('float') ) result.show() expected_df.show() self.assertDataFrameEqual( result, expected_df ) def test_compute_different_queries_first_subset(self): first_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:30:00.000Z', "content_type": 'html', "client_url": 'page1/page2', "querystring": '?a=b', } second_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:40:00.000Z', "content_type": 'html', "client_url": 'page1/page2', "querystring": '?c=d', } third_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:50:00.000Z', "content_type": 'html', "client_url": 'page1/page2', "querystring": '?e=f', } sub_df = self.get_df_with_extra_cols( self.feature, [first_ats_record, second_ats_record, third_ats_record], extra_cols={ 'first_ever_request': F.lit(None).cast('timestamp') } ) result = self.feature.compute(sub_df) expected_df = sub_df.withColumn( self.feature.feature_name, F.lit(3./20.).cast('float') ) result.show() expected_df.show() self.assertDataFrameEqual( result, expected_df ) def test_compute_different_queries_subsequent_subset(self): first_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:30:00.000Z', "first_ever_request": '2018-01-17T08:20:00.000Z', "content_type": 'html', "client_url": 'page1/page2', "querystring": '?a=b', } second_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:30:00.000Z', "first_ever_request": '2018-01-17T08:20:00.000Z', "content_type": 'html', "client_url": 'page1/page2', "querystring": '?c=d', } third_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:40:00.000Z', "first_ever_request": '2018-01-17T08:20:00.000Z', "content_type": 'html', "client_url": 'page3', "querystring": '?e=f', } fourth_ats_record = { "client_ip": '55.555.55.55', "@timestamp": '2018-01-17T08:50:00.000Z', "first_ever_request": '2018-01-17T08:20:00.000Z', "content_type": 'html', "client_url": 'page4', "querystring": '?e=f', } first_ever_request = '2018-01-17T08:20:00.000Z' sub_df = self.get_df_with_extra_cols( self.feature, [ first_ats_record, second_ats_record, third_ats_record, fourth_ats_record ], extra_cols={ 'first_ever_request': F.lit(first_ever_request).cast('timestamp') } ) result = self.feature.compute(sub_df) expected_df = sub_df.withColumn( self.feature.feature_name, F.lit(3./30.).cast('float') ) result.show() expected_df.show() self.assertDataFrameEqual( result, expected_df ) def test_update_row(self): total = FeatureUniqueQueryTotal() minutes = FeatureMinutesTotal() test_current = {total.feature_name: 6., minutes.feature_name: 3.} test_past = {total.feature_name: 2., minutes.feature_name: 1.} value = self.feature.update_row( test_current, test_past ) expected_value = (6. + 2.)/3. self.assertAlmostEqual(value, expected_value, places=2) def test_update(self): denominator = FeatureMinutesTotal.feature_name_from_class() numerator = FeatureUniqueQueryTotal.feature_name_from_class() schema = T.StructType([ T.StructField( self.feature.current_features_column, T.MapType(T.StringType(), T.FloatType()) ), T.StructField( self.feature.past_features_column, T.MapType(T.StringType(), T.FloatType()) ), ]) sub_df = self.session.createDataFrame( [{ self.feature.current_features_column: { numerator: 6., denominator: 3., }, self.feature.past_features_column: { numerator: 2., denominator: 1., } }], schema=schema ) result_df = self.feature.update( sub_df ) result_df.show() value = result_df.select( self.feature.updated_feature_col_name ).collect()[0][self.feature.updated_feature_col_name] expected_value = (6. + 2.)/3. self.assertAlmostEqual(value, expected_value, places=2)
33.92735
81
0.557627
795a54d7d0dc99dbc510d61c493c71017f4f63d9
259
py
Python
lib/oeqa/runtime/cases/rubygems_rubygems_gssapi.py
tuxable-ltd/meta-rubygems
e80630e79b64e1be8339e1add0ab07644ec99425
[ "BSD-2-Clause" ]
null
null
null
lib/oeqa/runtime/cases/rubygems_rubygems_gssapi.py
tuxable-ltd/meta-rubygems
e80630e79b64e1be8339e1add0ab07644ec99425
[ "BSD-2-Clause" ]
141
2021-02-04T16:22:13.000Z
2022-03-27T08:29:40.000Z
lib/oeqa/runtime/cases/rubygems_rubygems_gssapi.py
tuxable-ltd/meta-rubygems
e80630e79b64e1be8339e1add0ab07644ec99425
[ "BSD-2-Clause" ]
3
2021-02-04T14:02:01.000Z
2022-02-02T16:46:52.000Z
from rubygems_utils import RubyGemsTestUtils class RubyGemsTestrubygems_gssapi(RubyGemsTestUtils): def test_gem_list_rubygems_gssapi(self): self.gem_is_installed("gssapi") def test_load_gssapi(self): self.gem_is_loadable("gssapi")
23.545455
53
0.772201
795a54e770b276bf976cfd6b2540a944b855a2eb
587
py
Python
rxbp/typing.py
MichaelSchneeberger/rx_backpressure
16173827498bf1bbee3344933cb9efbfd19699f5
[ "Apache-2.0" ]
24
2018-11-22T21:04:49.000Z
2021-11-08T11:18:09.000Z
rxbp/typing.py
MichaelSchneeberger/rx_backpressure
16173827498bf1bbee3344933cb9efbfd19699f5
[ "Apache-2.0" ]
1
2019-02-06T15:58:46.000Z
2019-02-12T20:31:50.000Z
rxbp/typing.py
MichaelSchneeberger/rx_backpressure
16173827498bf1bbee3344933cb9efbfd19699f5
[ "Apache-2.0" ]
1
2021-01-26T12:41:37.000Z
2021-01-26T12:41:37.000Z
from typing import TypeVar, Union, Iterator, List # value send over a Flowable ValueType = TypeVar('ValueType') # Instead of calling on_next method for each value in a sequence, rxbp # sends these values in a batch. This can be done either by putting them in a # list or in an iterator. Putting the values in an iterator is sometimes more # preferable as the data does not need to be copied from one location to the other. # But sometimes you cannot avoid buffering data in a list. # A batch consists of zero or more elements. ElementType = Union[Iterator[ValueType], List[ValueType]]
45.153846
83
0.773424
795a56dff1dd8b1d54914c9b7ae391fa276294e7
1,722
py
Python
Code/odooerp/odoo-8.0/openerp/addons/sale/res_partner.py
zhupangithub/WEBERP
714512082ec5c6db07cbf6af0238ceefe2d2c1a5
[ "MIT" ]
1
2019-12-29T11:53:56.000Z
2019-12-29T11:53:56.000Z
odoo/addons/sale/res_partner.py
tuanquanghpvn/odoo8-tutorial
52d25f1ca5f233c431cb9d3b24b79c3b4fb5127e
[ "MIT" ]
null
null
null
odoo/addons/sale/res_partner.py
tuanquanghpvn/odoo8-tutorial
52d25f1ca5f233c431cb9d3b24b79c3b4fb5127e
[ "MIT" ]
3
2020-10-08T14:42:10.000Z
2022-01-28T14:12:29.000Z
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields,osv class res_partner(osv.osv): _inherit = 'res.partner' def _sale_order_count(self, cr, uid, ids, field_name, arg, context=None): res = dict(map(lambda x: (x,0), ids)) # The current user may not have access rights for sale orders try: for partner in self.browse(cr, uid, ids, context): res[partner.id] = len(partner.sale_order_ids) + len(partner.mapped('child_ids.sale_order_ids')) except: pass return res _columns = { 'sale_order_count': fields.function(_sale_order_count, string='# of Sales Order', type='integer'), 'sale_order_ids': fields.one2many('sale.order','partner_id','Sales Order') }
41
111
0.61324
795a56fd2fff4af62fd84a6faf7235a1a8d1a66f
43,544
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_04_01/aio/operations/_public_ip_addresses_operations.py
praveenkuttappan/azure-sdk-for-python
4b79413667b7539750a6c7dde15737013a3d4bd5
[ "MIT" ]
2,728
2015-01-09T10:19:32.000Z
2022-03-31T14:50:33.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_04_01/aio/operations/_public_ip_addresses_operations.py
v-xuto/azure-sdk-for-python
9c6296d22094c5ede410bc83749e8df8694ccacc
[ "MIT" ]
17,773
2015-01-05T15:57:17.000Z
2022-03-31T23:50:25.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_04_01/aio/operations/_public_ip_addresses_operations.py
v-xuto/azure-sdk-for-python
9c6296d22094c5ede410bc83749e8df8694ccacc
[ "MIT" ]
1,916
2015-01-19T05:05:41.000Z
2022-03-31T19:36:44.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PublicIPAddressesOperations: """PublicIPAddressesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2018_04_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, public_ip_address_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def begin_delete( self, resource_group_name: str, public_ip_address_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified public IP address. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_address_name: The name of the subnet. :type public_ip_address_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, public_ip_address_name=public_ip_address_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def get( self, resource_group_name: str, public_ip_address_name: str, expand: Optional[str] = None, **kwargs: Any ) -> "_models.PublicIPAddress": """Gets the specified public IP address in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_address_name: The name of the subnet. :type public_ip_address_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PublicIPAddress, or the result of cls(response) :rtype: ~azure.mgmt.network.v2018_04_01.models.PublicIPAddress :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, public_ip_address_name: str, parameters: "_models.PublicIPAddress", **kwargs: Any ) -> "_models.PublicIPAddress": cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'PublicIPAddress') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('PublicIPAddress', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, public_ip_address_name: str, parameters: "_models.PublicIPAddress", **kwargs: Any ) -> AsyncLROPoller["_models.PublicIPAddress"]: """Creates or updates a static or dynamic public IP address. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_address_name: The name of the public IP address. :type public_ip_address_name: str :param parameters: Parameters supplied to the create or update public IP address operation. :type parameters: ~azure.mgmt.network.v2018_04_01.models.PublicIPAddress :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PublicIPAddress or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_04_01.models.PublicIPAddress] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, public_ip_address_name=public_ip_address_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def _update_tags_initial( self, resource_group_name: str, public_ip_address_name: str, parameters: "_models.TagsObject", **kwargs: Any ) -> "_models.PublicIPAddress": cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._update_tags_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _update_tags_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore async def begin_update_tags( self, resource_group_name: str, public_ip_address_name: str, parameters: "_models.TagsObject", **kwargs: Any ) -> AsyncLROPoller["_models.PublicIPAddress"]: """Updates public IP address tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_address_name: The name of the public IP address. :type public_ip_address_name: str :param parameters: Parameters supplied to update public IP address tags. :type parameters: ~azure.mgmt.network.v2018_04_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PublicIPAddress or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2018_04_01.models.PublicIPAddress] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._update_tags_initial( resource_group_name=resource_group_name, public_ip_address_name=public_ip_address_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}'} # type: ignore def list_all( self, **kwargs: Any ) -> AsyncIterable["_models.PublicIPAddressListResult"]: """Gets all the public IP addresses in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPAddressListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_04_01.models.PublicIPAddressListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddressListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { '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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPAddressListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses'} # type: ignore def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.PublicIPAddressListResult"]: """Gets all public IP addresses in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPAddressListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_04_01.models.PublicIPAddressListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddressListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore 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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPAddressListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses'} # type: ignore def list_virtual_machine_scale_set_public_ip_addresses( self, resource_group_name: str, virtual_machine_scale_set_name: str, **kwargs: Any ) -> AsyncIterable["_models.PublicIPAddressListResult"]: """Gets information about all public IP addresses on a virtual machine scale set level. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_machine_scale_set_name: The name of the virtual machine scale set. :type virtual_machine_scale_set_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPAddressListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_04_01.models.PublicIPAddressListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddressListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-03-30" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_virtual_machine_scale_set_public_ip_addresses.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPAddressListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_virtual_machine_scale_set_public_ip_addresses.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/publicipaddresses'} # type: ignore def list_virtual_machine_scale_set_vm_public_ip_addresses( self, resource_group_name: str, virtual_machine_scale_set_name: str, virtualmachine_index: str, network_interface_name: str, ip_configuration_name: str, **kwargs: Any ) -> AsyncIterable["_models.PublicIPAddressListResult"]: """Gets information about all public IP addresses in a virtual machine IP configuration in a virtual machine scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_machine_scale_set_name: The name of the virtual machine scale set. :type virtual_machine_scale_set_name: str :param virtualmachine_index: The virtual machine index. :type virtualmachine_index: str :param network_interface_name: The network interface name. :type network_interface_name: str :param ip_configuration_name: The IP configuration name. :type ip_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PublicIPAddressListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2018_04_01.models.PublicIPAddressListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddressListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-03-30" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_virtual_machine_scale_set_vm_public_ip_addresses.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_set_name, 'str'), 'virtualmachineIndex': self._serialize.url("virtualmachine_index", virtualmachine_index, 'str'), 'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'), 'ipConfigurationName': self._serialize.url("ip_configuration_name", ip_configuration_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('PublicIPAddressListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_virtual_machine_scale_set_vm_public_ip_addresses.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses'} # type: ignore async def get_virtual_machine_scale_set_public_ip_address( self, resource_group_name: str, virtual_machine_scale_set_name: str, virtualmachine_index: str, network_interface_name: str, ip_configuration_name: str, public_ip_address_name: str, expand: Optional[str] = None, **kwargs: Any ) -> "_models.PublicIPAddress": """Get the specified public IP address in a virtual machine scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_machine_scale_set_name: The name of the virtual machine scale set. :type virtual_machine_scale_set_name: str :param virtualmachine_index: The virtual machine index. :type virtualmachine_index: str :param network_interface_name: The name of the network interface. :type network_interface_name: str :param ip_configuration_name: The name of the IP configuration. :type ip_configuration_name: str :param public_ip_address_name: The name of the public IP Address. :type public_ip_address_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PublicIPAddress, or the result of cls(response) :rtype: ~azure.mgmt.network.v2018_04_01.models.PublicIPAddress :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PublicIPAddress"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2017-03-30" accept = "application/json" # Construct URL url = self.get_virtual_machine_scale_set_public_ip_address.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_set_name, 'str'), 'virtualmachineIndex': self._serialize.url("virtualmachine_index", virtualmachine_index, 'str'), 'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'), 'ipConfigurationName': self._serialize.url("ip_configuration_name", ip_configuration_name, 'str'), 'publicIpAddressName': self._serialize.url("public_ip_address_name", public_ip_address_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 = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_virtual_machine_scale_set_public_ip_address.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}/ipconfigurations/{ipConfigurationName}/publicipaddresses/{publicIpAddressName}'} # type: ignore
51.714964
395
0.675202
795a5716f468fb828fe6e92bf021f430022907ff
1,386
py
Python
distro/src/bin/atlas_admin.py
mario-renau-alstom/atlas
05b27be8b8bccddc2c2d0c4d11dca2c97bd7ee8d
[ "Apache-2.0" ]
1,248
2017-07-24T09:56:27.000Z
2022-03-30T01:19:24.000Z
distro/src/bin/atlas_admin.py
mario-renau-alstom/atlas
05b27be8b8bccddc2c2d0c4d11dca2c97bd7ee8d
[ "Apache-2.0" ]
89
2017-09-27T00:06:49.000Z
2022-03-31T19:11:28.000Z
distro/src/bin/atlas_admin.py
mario-renau-alstom/atlas
05b27be8b8bccddc2c2d0c4d11dca2c97bd7ee8d
[ "Apache-2.0" ]
757
2017-07-24T10:01:06.000Z
2022-03-31T06:48:47.000Z
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import atlas_config as mc import atlas_client_cmdline as cmdline def main(): conf_dir = cmdline.setup_conf_dir() jvm_opts_list = cmdline.setup_jvm_opts_list(conf_dir, 'atlas_admin.log') atlas_classpath = cmdline.get_atlas_classpath(conf_dir) process = mc.java("org.apache.atlas.AtlasAdminClient", sys.argv[1:], atlas_classpath, jvm_opts_list) return process.wait() if __name__ == '__main__': try: returncode = main() except Exception as e: print("Exception: %s " % str(e)) returncode = -1 sys.exit(returncode)
33.804878
104
0.743146
795a58c4e050f65936c48229d107cba0c3a87619
1,165
py
Python
setup.py
ccin2p3/tmux2html
20fb2409e7350d45814135a7421df35a98a61834
[ "MIT" ]
695
2016-03-30T03:18:44.000Z
2022-03-15T12:00:06.000Z
setup.py
ccin2p3/tmux2html
20fb2409e7350d45814135a7421df35a98a61834
[ "MIT" ]
17
2016-03-30T16:53:17.000Z
2022-03-11T19:22:34.000Z
setup.py
ccin2p3/tmux2html
20fb2409e7350d45814135a7421df35a98a61834
[ "MIT" ]
16
2016-03-31T01:43:22.000Z
2020-10-11T08:35:29.000Z
from setuptools import setup, find_packages desc = ''' tmux2html captures full tmux windows or individual panes then parses their contents into HTML. '''.strip() setup( name='tmux2html', version='0.1.11', author='Tommy Allen', author_email='tommy@esdf.io', description=desc, packages=find_packages(), url='https://github.com/tweekmonster/tmux2html', install_requires=[], include_package_data=True, entry_points={ 'console_scripts': [ 'tmux2html=tmux2html.main:main', ] }, keywords='tmux html cool hip neat rad', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'Topic :: Terminals :: Terminal Emulators/X Terminals', 'Topic :: Utilities', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ] )
29.871795
63
0.620601
795a5903e285f999416224d24f8f070b5204b5ff
5,531
py
Python
exporter/exp/gltf2_blender_batch_export.py
rhammond17/Blender2MSFS2
51ed5e6624e6e072ee03bb7123013ccce4159fbd
[ "Apache-2.0" ]
25
2021-07-01T04:48:08.000Z
2022-03-15T00:20:55.000Z
exporter/exp/gltf2_blender_batch_export.py
rhammond17/Blender2MSFS2
51ed5e6624e6e072ee03bb7123013ccce4159fbd
[ "Apache-2.0" ]
9
2021-10-14T12:58:11.000Z
2022-03-22T05:10:05.000Z
exporter/exp/gltf2_blender_batch_export.py
rhammond17/Blender2MSFS2
51ed5e6624e6e072ee03bb7123013ccce4159fbd
[ "Apache-2.0" ]
4
2021-12-18T22:26:00.000Z
2022-03-16T14:00:27.000Z
################################################################################################### # # Copyright 2020 Otmar Nitsche # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################################### # # This is the modified exporter for the Blender2MSFS addon. # The only purpose of the modification is to allow for extensions # in the "asset" section of the glTF file. # ################################################################################################### import bpy import time import re import os from ..com.gltf2_io_debug import print_console, print_newline from .gltf2_blender_gltf2_exporter import GlTF2Exporter from . import gltf2_io_draco_compression_extension from .gltf2_io_user_extensions import export_user_extensions def save_ext_gltf(context, export_settings): """Go through the collections and find the lods, export them one by one.""" from . import gltf2_blender_export lods = [] lod_pattern = re.compile("^x(\d+)", re.IGNORECASE) filename_base, extension = os.path.splitext(export_settings['gltf_filepath']) filename, extension = os.path.splitext(os.path.basename(export_settings['gltf_filepath'])) lod_model_export_settings = export_settings.copy() for collection in bpy.data.collections: match = lod_pattern.match(collection.name) if match: #save collection name in export settings: lod_model_export_settings['gltf_current_collection'] = collection.name lod_id = "_LOD" + match.group(1) lod_filename = filename_base+lod_id+extension lods.append(lod_filename) lod_model_export_settings['gltf_filepath'] = lod_filename lod_model_export_settings['gltf_binaryfilename'] = filename+lod_id+'.bin' # Begin export process: original_frame = bpy.context.scene.frame_current if not lod_model_export_settings['gltf_current_frame']: bpy.context.scene.frame_set(0) gltf2_blender_export.__notify_start_ext_gltf(context) start_time = time.time() pre_export_callbacks = lod_model_export_settings["pre_export_callbacks"] for callback in pre_export_callbacks: callback(lod_model_export_settings) json, buffer = __export_ext_gltf(lod_model_export_settings) post_export_callbacks = lod_model_export_settings["post_export_callbacks"] for callback in post_export_callbacks: callback(lod_model_export_settings) gltf2_blender_export.__write_file_ext_gltf(json, buffer, lod_model_export_settings) end_time = time.time() gltf2_blender_export.__notify_end_ext_gltf(context, end_time - start_time) if not lod_model_export_settings['gltf_current_frame']: bpy.context.scene.frame_set(original_frame) #save XML file if required: if export_settings['gltf_msfs_xml'] == True: from .msfs_xml_export import save_xml save_xml(context,export_settings,lods) if len(lods) == 1: msg = "Exported one lod model." print(msg) for filename in lods: print("<%s>"%filename) return{'FINISHED'} elif len(lods) > 1: msg = "Exported %i lod models."%len(lods) print(msg) for filename in lods: print("<%s>"%filename) return{'FINISHED'} else: msg = "ERROR: Could not find LODs in the scene. Collection names should be: 'X00','X01', 'X02', and so on." print(msg) return{'CANCELLED'} def __export_ext_gltf(export_settings): from . import gltf2_blender_export exporter = GlTF2Exporter(export_settings) __gather_ext_gltf(exporter, export_settings) buffer = gltf2_blender_export.__create_buffer_ext_gltf(exporter, export_settings) exporter.finalize_images() json = gltf2_blender_export.__fix_json_ext_gltf(exporter.glTF.to_dict()) return json, buffer def __gather_ext_gltf(exporter, export_settings): from . import gltf2_blender_batch_gather active_scene_idx, scenes, animations = gltf2_blender_batch_gather.gather_gltf2(export_settings) #active_scene_idx, scenes, animations = gltf2_blender_gather.gather_gltf2(export_settings) plan = {'active_scene_idx': active_scene_idx, 'scenes': scenes, 'animations': animations} export_user_extensions('gather_gltf_hook', export_settings, plan) active_scene_idx, scenes, animations = plan['active_scene_idx'], plan['scenes'], plan['animations'] if export_settings['gltf_draco_mesh_compression']: gltf2_io_draco_compression_extension.compress_scene_primitives(scenes, export_settings) exporter.add_draco_extension() for idx, scene in enumerate(scenes): exporter.add_scene(scene, idx==active_scene_idx) for animation in animations: exporter.add_animation(animation)
40.669118
115
0.67203
795a5a565aad2fc266a0bb8e3454b51811d3e717
1,115
py
Python
python-package/polymnie/vcf.py
BioShock38/Parser
ef1a2503a36e66148effe88bad6c178c8dc8d5a2
[ "Apache-2.0" ]
null
null
null
python-package/polymnie/vcf.py
BioShock38/Parser
ef1a2503a36e66148effe88bad6c178c8dc8d5a2
[ "Apache-2.0" ]
null
null
null
python-package/polymnie/vcf.py
BioShock38/Parser
ef1a2503a36e66148effe88bad6c178c8dc8d5a2
[ "Apache-2.0" ]
null
null
null
import numpy as np import vcfnp def vcf2snp(filename, missing=3, cache=True): """ Return a SNP matrix based on a VCF file. This take a VCF file and create a SNP matrix. It will keep only the SNP with 2 variants. This function is based on the vcfnp package. :param filename: The path of the VCF file :param missing: How to annotate missing data :param cache: Use cache :type filename: string :type missing: np.int8 :type cache: boolean :return: The genotype matrix containing SNP :rtype: np.array of np.int8 :Example: >>> G = vcf2snp('file.vcf') ... warnings:: This function is not maintain. """ c = vcfnp.calldata_2d(filename, cache=cache).view(np.recarray) G = c.genotype ## create a mask to keep only 0/0, 1/0, 0/1, 1/1 and missing datas mask = np.logical_and.reduce(np.logical_and(G >= -1, G <= 1), axis = 2) mask = np.logical_and.reduce(mask, axis=1) G = G[mask, :] mask_missing = np.logical_and.reduce(G == -1, axis=2) G = np.sum(G.T, axis=0, dtype=np.int8) G[mask_missing.T] = missing return G
27.195122
82
0.64574
795a5b33a0979bd600ffa97e2fd30e5fdb0d633b
8,819
py
Python
vpn_critic.py
christsa/hide-rl
47dc3dfd93b817831473c07137a6a6e7f2eda549
[ "Apache-2.0" ]
3
2021-09-17T15:16:17.000Z
2021-12-15T14:24:39.000Z
vpn_critic.py
christsa/hide-rl
47dc3dfd93b817831473c07137a6a6e7f2eda549
[ "Apache-2.0" ]
null
null
null
vpn_critic.py
christsa/hide-rl
47dc3dfd93b817831473c07137a6a6e7f2eda549
[ "Apache-2.0" ]
null
null
null
from torch.nn import functional as F from torch import nn import torch import numpy as np from utils import layer from radam import RAdam from vpn import MVProp import utils from torch_critic import Critic as ClassicCritic class CriticModel(nn.Module): def __init__(self, env, layer_number, FLAGS): super().__init__() self.q_limit = -FLAGS.time_scale # Set parameters to give critic optimistic initialization near q_init self.q_init = -0.067 self.q_offset = -np.log(self.q_limit/self.q_init - 1) self.no_target_net = FLAGS.no_target_net self.time_scale = FLAGS.time_scale self.no_attention = FLAGS.no_attention self.gaussian_attention = FLAGS.gaussian_attention self.covariance = FLAGS.covariance self.offset = FLAGS.window_offset # Dimensions of goal placeholder will differ depending on layer level if layer_number == FLAGS.layers - 1 or (layer_number == FLAGS.layers -2 and FLAGS.oracle): self.goal_dim = env.end_goal_dim else: self.goal_dim = env.subgoal_dim self.loss_val = 0 self.state_dim = env.state_dim # Dimensions of action placeholder will differ depending on layer level if layer_number == 0: action_dim = env.action_dim else: action_dim = env.subgoal_dim def forward(self, v_image, actor_pixel_selection): # v_image shape [batch_size, height, width] x_coords = actor_pixel_selection[:, 0] y_coords = actor_pixel_selection[:, 1] assert (x_coords >= 0).all() assert (x_coords < v_image.shape[-1]).all(), (torch.min(x_coords), torch.max(x_coords), v_image.shape) assert (y_coords >= 0).all() assert (y_coords < v_image.shape[-2]).all() x_slice = x_coords.long().unsqueeze(1).unsqueeze(2).expand(-1, v_image.shape[1], -1) value = v_image.gather(2, x_slice) y_slice = y_coords.long().unsqueeze(1).unsqueeze(2) values = value.gather(1, y_slice) return values * self.time_scale def actor(self, v_image, pos_coords, probs_grid, sigma=None): if self.gaussian_attention: assert sigma is not None if self.covariance: masked_v = utils.multivariate_gaussian_attention(v_image, pos_coords, cov=sigma)[0] else: masked_v = utils.gaussian_attention(v_image, pos_coords, sigma=sigma)[0] elif self.no_attention: masked_v = v_image else: # Crop V. masked_v, x_coords, y_coords = utils.attention(v_image, pos_coords, offset=self.offset) assert masked_v.shape == probs_grid.shape, (v_image.shape, masked_v.shape, probs_grid.shape) return (masked_v * probs_grid).sum(dim=[1,2]) * self.time_scale class Critic(): def __init__(self, device, env, layer_number, FLAGS, learning_rate=0.001, gamma=0.98, tau=0.05): self.device = device # Session in its TF equivalent self.critic_name = 'vpn_critic_' + str(layer_number) self.learning_rate = learning_rate self.q_limit = -FLAGS.time_scale self.gamma = gamma self.tau = tau self.sac = FLAGS.sac self.td3 = FLAGS.td3 self.vpn = MVProp(self.gamma, FLAGS, env).to(self.device) self.no_target_net = FLAGS.no_target_net # Create critic network graph self.infer_net = CriticModel(env, layer_number, FLAGS).to(device=self.device) self.no_weights = FLAGS.no_vpn_weights self.vpn_masking = FLAGS.vpn_masking self.classic_critic = None if FLAGS.boost_vpn: self.classic_critic = ClassicCritic(device, env, layer_number, FLAGS, learning_rate, gamma, tau) if not self.no_weights: opt_class = RAdam if FLAGS.radam else torch.optim.Adam self.optimizer = opt_class(self.vpn.parameters(), learning_rate) if FLAGS.no_target_net: self.target_net = self.infer_net self.vpn_target = self.vpn else: self.target_net = self.infer_net self.vpn_target = MVProp(self.gamma, FLAGS, env).to(self.device) self.vpn_target.load_state_dict(self.vpn.state_dict()) self.get_pos_image = lambda states, images: env.pos_image(states[..., :2], images[:, 0]) self.get_image_pos = lambda states, images: torch.stack(env.get_image_position(states[..., :2], images), dim=-1) def get_Q_value(self,state, goal, action, image): with torch.no_grad(): q = self.infer_net(self.vpn.critic(image), self.get_image_pos(action, image)) return q def get_target_Q_value(self,state, goal, action, image): assert not self.no_target_net with torch.no_grad(): q = self.infer_net(self.target_net.critic(image), self.get_image_pos(action, image)) return q def update_target_weights(self): for source, target in zip(self.vpn.parameters(), self.vpn_target.parameters()): target.data.copy_(self.tau * source + (1.0 - self.tau) * target) def _value(self, net, vpn_net, images, states, actions, get_extra_loss=False): pos_image = self.get_pos_image(states, images) action_image_position = self.get_image_pos(actions, images) agent_image_position = self.get_image_pos(states, images) vpn_values, vpn_probs = vpn_net.actor(images, pos_image) if self.vpn_masking: vpn_values, extra_loss = vpn_net.mask_image(vpn_values, vpn_probs, pos_image, agent_image_position) if get_extra_loss: return net(vpn_values, action_image_position).squeeze(), extra_loss return net(vpn_values, action_image_position).squeeze() def update(self, old_states, old_actions, rewards, new_states, old_goals, new_goals, new_actions, is_terminals, is_weights, next_entropy, images, metrics, total_steps_taken=None): if self.no_weights: return torch.ones_like(rewards) if self.classic_critic is not None: self.classic_critic.update(old_states, old_actions, rewards, new_states, old_goals, new_actions, is_terminals, is_weights, next_entropy, None, metrics) with torch.no_grad(): wanted_qs = self._value(self.target_net, self.vpn_target, images, new_states, new_actions) if self.classic_critic is not None: alpha = 1 - (min(total_steps_taken, 1e-6) / 1e-6) wanted_qs_classic = torch.stack([net(new_states, new_goals, new_actions) for net in self.classic_critic.target_nets], dim=0) wanted_qs_classic = torch.min(wanted_qs_classic, dim=0)[0].detach().squeeze() alpha*(wanted_qs_classic) + (1-alpha)*wanted_qs wanted_qs = rewards + (1 - is_terminals) * (self.gamma * wanted_qs) if next_entropy is not None: wanted_qs -= next_entropy wanted_qs = torch.clamp(wanted_qs, max=0, min=self.q_limit) infered_Qs, extra_loss = self._value(self.infer_net, self.vpn, images, old_states, old_actions, get_extra_loss=True) if is_weights is None: is_weights = torch.ones_like(wanted_qs) abs_errors = torch.abs(wanted_qs - infered_Qs).detach() self.optimizer.zero_grad() difference = (wanted_qs - infered_Qs) loss = torch.mean(is_weights * torch.mul(difference, difference), dim=0) + extra_loss loss.backward() self.optimizer.step() metrics[self.critic_name + '/Q_loss'] = loss.item() metrics[self.critic_name + '/Q_val'] = torch.mean(wanted_qs).item() return abs_errors def get_gradients_for_actions(self, state, goal, actor, images): action, image_location, vpn_values, sigma = actor._action_with_intermediate_results( actor.infer_net, state, images, pixel_probs=True) Q = self.infer_net.actor(vpn_values, image_location, action, sigma) return Q def state_dict(self): result = {} if self.no_weights: return result result['target_net'] = self.target_net.state_dict() result['infer_net'] = self.infer_net.state_dict() result['optimizer'] = self.optimizer.state_dict() result['vpn'] = self.vpn.state_dict() result['vpn_target'] = self.vpn_target.state_dict() return result def load_state_dict(self, state_dict): if self.no_weights: return self.target_net.load_state_dict(state_dict['target_net']) self.infer_net.load_state_dict(state_dict['infer_net']) self.optimizer.load_state_dict(state_dict['optimizer']) self.vpn.load_state_dict(state_dict['vpn']) self.vpn_target.load_state_dict(state_dict['vpn_target'])
46.415789
183
0.66198
795a5b51529def4f6f915ae9e46bc564de7e2bd6
3,391
py
Python
RestApi/settings.py
Lovekesh-GH/Restapi
e66c057b67356545564f348f1d067e2eb5f89e66
[ "MIT" ]
null
null
null
RestApi/settings.py
Lovekesh-GH/Restapi
e66c057b67356545564f348f1d067e2eb5f89e66
[ "MIT" ]
null
null
null
RestApi/settings.py
Lovekesh-GH/Restapi
e66c057b67356545564f348f1d067e2eb5f89e66
[ "MIT" ]
null
null
null
""" Django settings for RestApi project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # Environment SECRET_KEY = os.getenv("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'rest_framework.authtoken', 'drf', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "RestApi.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "RestApi.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "/static/" # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' :[ 'rest_framework.authentication.TokenAuthentication' ] }
24.751825
91
0.700678
795a5b714c8a05faad47fe157204198f09ac97e8
576
py
Python
decorators.py
EvertonAlauk/flask-restplus-users
d07554659d5229ce2a67e4770e42f85166682192
[ "Apache-2.0" ]
null
null
null
decorators.py
EvertonAlauk/flask-restplus-users
d07554659d5229ce2a67e4770e42f85166682192
[ "Apache-2.0" ]
null
null
null
decorators.py
EvertonAlauk/flask-restplus-users
d07554659d5229ce2a67e4770e42f85166682192
[ "Apache-2.0" ]
1
2020-07-03T06:26:12.000Z
2020-07-03T06:26:12.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import jwt from flask import request from flask import jsonify from flask_restplus import abort from functools import wraps from config import SECRET_KEY def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.args.get('token') if not token: abort(404, message="Token is missing!") try: data = jwt.decode(token, SECRET_KEY) except: abort(404, message="Token is invalid!") return f(*args, **kwargs) return decorated
25.043478
51
0.631944
795a5be14c23b2cb103061869e0e451b1a40782e
5,085
py
Python
tests/unit/lms/services/course_test.py
mattdricker/lms
40b8a04f95e69258c6c0d7ada543f4b527918ecf
[ "BSD-2-Clause" ]
null
null
null
tests/unit/lms/services/course_test.py
mattdricker/lms
40b8a04f95e69258c6c0d7ada543f4b527918ecf
[ "BSD-2-Clause" ]
null
null
null
tests/unit/lms/services/course_test.py
mattdricker/lms
40b8a04f95e69258c6c0d7ada543f4b527918ecf
[ "BSD-2-Clause" ]
null
null
null
import datetime from unittest.mock import sentinel import pytest from lms.models import Course, CourseGroupsExportedFromH, LegacyCourse from lms.services.course import course_service_factory from tests import factories pytestmark = pytest.mark.usefixtures("application_instance_service") class TestCourseService: @pytest.mark.parametrize("canvas_sections_enabled", [True, False]) def test_inserting_True_and_False( self, application_instance_service, db_session, svc, canvas_sections_enabled ): application_instance_service.get.return_value.settings.set( "canvas", "sections_enabled", canvas_sections_enabled ) svc.get_or_create("test_authority_provided_id") course = db_session.query(LegacyCourse).one() assert ( course.settings.get("canvas", "sections_enabled") == canvas_sections_enabled ) def test_it_does_nothing_if_theres_already_a_matching_row( self, application_instance_service, application_instance, pyramid_request, svc ): existing_course = factories.LegacyCourse( application_instance=application_instance, authority_provided_id="test_authority_provided_id", settings={}, ) existing_course.settings.set("canvas", "sections_enabled", False) application_instance_service.get.return_value.settings.set( "canvas", "sections_enabled", True ) svc.get_or_create("test_authority_provided_id") existing_course = pyramid_request.db.query(LegacyCourse).one() assert not existing_course.settings.get("canvas", "sections_enabled") @pytest.mark.parametrize("canvas_sections_enabled", [True, False]) def test_it_inserts_False_if_theres_a_matching_row_in_course_groups_exported_from_h( self, application_instance_service, db_session, svc, canvas_sections_enabled ): db_session.add( CourseGroupsExportedFromH( authority_provided_id="test_authority_provided_id", created=datetime.datetime.utcnow(), ) ) application_instance_service.get.return_value.settings.set( "canvas", "sections_enabled", canvas_sections_enabled ) svc.get_or_create("test_authority_provided_id") course = db_session.query(LegacyCourse).one() assert not course.settings.get("canvas", "sections_enabled") @pytest.mark.parametrize( "settings_set,value,expected", ( ([], "any", False), ([{"group": {"key": "match"}}], "match", True), ([{"group": {"key": "no_match"}}], "match", False), ( [{"group": {"key": "no_match"}}, {"group": {"key": "match"}}], "match", True, ), ), ) def test_any_with_setting( self, svc, settings_set, value, expected, add_courses_with_settings ): add_courses_with_settings(settings_set) # Add a matching course with a different consumer key add_courses_with_settings( [{"group": {"key": value}}], application_instance=factories.ApplicationInstance(), ) assert svc.any_with_setting("group", "key", value) is expected def test_upsert_returns_existing(self, svc, application_instance, db_session): existing_course = factories.Course(application_instance=application_instance) course = svc.upsert( existing_course.authority_provided_id, "context_id", "new course name", {} ) # No new courses created assert db_session.query(Course).count() == 1 # And existing course has been updated assert course.lms_name == "new course name" def test_upsert_creates_new(self, svc, db_session): # Starting with a fresh DB assert not db_session.query(Course).count() course = svc.upsert( "new authority_provided_id", "context_id", "new course name", {} ) assert db_session.query(Course).count() == 1 assert course.authority_provided_id == "new authority_provided_id" @pytest.fixture def add_courses_with_settings(self, application_instance): def add_courses_with_settings( settings_set, application_instance=application_instance ): for settings in settings_set: factories.LegacyCourse( application_instance=application_instance, settings=settings ) return add_courses_with_settings @pytest.fixture def svc(self, pyramid_request, application_instance_service, application_instance): application_instance_service.get.return_value = application_instance return course_service_factory(sentinel.context, pyramid_request) @pytest.fixture(autouse=True) def application_instance(self, pyramid_request): return factories.ApplicationInstance( consumer_key=pyramid_request.lti_user.oauth_consumer_key, settings={} )
37.116788
88
0.670993
795a5d29712969348381266fb7f630e288eda13c
4,771
py
Python
devernaysubpix/edge_detector.py
mostlyuseful/devernaysubpix
cfd0bfe3308e70a66d758988259bb2f176bea12b
[ "MIT" ]
null
null
null
devernaysubpix/edge_detector.py
mostlyuseful/devernaysubpix
cfd0bfe3308e70a66d758988259bb2f176bea12b
[ "MIT" ]
null
null
null
devernaysubpix/edge_detector.py
mostlyuseful/devernaysubpix
cfd0bfe3308e70a66d758988259bb2f176bea12b
[ "MIT" ]
2
2018-08-20T01:54:27.000Z
2019-04-09T03:22:12.000Z
import numpy as np from scipy.ndimage import filters from bidict import bidict def image_gradient(image, sigma): image = np.asfarray(image) gx = filters.gaussian_filter(image, sigma, order=[0, 1]) gy = filters.gaussian_filter(image, sigma, order=[1, 0]) return gx, gy class CurvePoint(object): __slots__ = ['x', 'y', 'valid'] def __init__(self, x, y, valid): self.x = x self.y = y self.valid = valid def __hash__(self): return hash((self.x, self.y)) def compute_edge_points(partial_gradients, min_magnitude=0): gx, gy = partial_gradients rows, cols = gx.shape edges = [] def mag(y, x): return np.hypot(gx[y, x], gy[y, x]) for y in range(1, rows - 1): for x in range(1, cols - 1): center_mag = mag(y, x) if center_mag < min_magnitude: continue left_mag = mag(y, x - 1) right_mag = mag(y, x + 1) top_mag = mag(y - 1, x) bottom_mag = mag(y + 1, x) theta_x, theta_y = 0, 0 if (left_mag < center_mag >= right_mag) and abs(gx[y, x]) >= abs(gy[y, x]): theta_x = 1 elif (top_mag < center_mag >= bottom_mag) and abs(gx[y, x]) <= abs(gy[y, x]): theta_y = 1 if theta_x != 0 or theta_y != 0: a = mag(y - theta_y, x - theta_x) b = mag(y, x) c = mag(y + theta_y, x + theta_x) lamda = (a - c) / (2 * (a - 2 * b + c)) ex = x + lamda * theta_x ey = y + lamda * theta_y edges.append(CurvePoint(ex, ey, valid=False)) return np.asarray(edges) def chain_edge_points(edges, g): gx, gy = g def neighborhood(p, max_dist): px, py = p.x, p.y for e in edges: ex, ey = e.x, e.y if abs(ex - px) <= max_dist and abs(ey - py) <= max_dist: yield e def gval(p): px, py = int(p.x), int(p.y) return [gx[py, px], gy[py, px]] def envec(e, n): return np.asanyarray([n.x, n.y]) - np.asanyarray([e.x, e.y]) def perp(v): x, y = gval(e) return np.asanyarray([y, -x]) def dist(a, b): a = [a.x, a.y] b = [b.x, b.y] return np.hypot(*(np.subtract(b, a))) links = bidict() for e in edges: nhood = [ n for n in neighborhood(e, 2) if np.dot(gval(e), gval(n)) > 0] nf = [n for n in nhood if np.dot(envec(e, n), perp(gval(e))) > 0] nb = [n for n in nhood if np.dot(envec(e, n), perp(gval(e))) < 0] if nf: f_idx = np.argmin([dist(e, n) for n in nf]) f = nf[f_idx] if f not in links.inv or dist(e,f) < dist(links.inv[f], f): if f in links.inv: del links.inv[f] if e in links: del links[e] links[e] = f if nb: b_idx = np.argmin([dist(e, n) for n in nb]) b = nb[b_idx] if b not in links or dist(b, e) < dist(b, links[b]): if b in links: del links[b] if e in links.inv: del links.inv[e] links[b] = e return links def thresholds_with_hysteresis(edges, links, grads, high_threshold, low_threshold): gx, gy = grads def mag(p): x, y = int(p.x), int(p.y) return np.hypot(gx[y, x], gy[y, x]) chains = [] for e in edges: if not e.valid and mag(e) >= high_threshold: forward = [] backward = [] e.valid = True f = e while f in links and not links[f].valid and mag(links[f]) >= low_threshold: n = links[f] n.valid = True f = n forward.append(f) b = e while b in links.inv and not links.inv[b].valid and mag(links.inv[f]) >= low_threshold: n = links.inv[b] n.valid = True b = n backward.insert(0, b) chain = backward + [e] + forward chains.append(np.asarray([(c.x, c.y) for c in chain])) return chains if __name__ == '__main__': import numpy as np from scipy.ndimage import filters import cv2 pad = 20 circle = cv2.imread("./kreis.png", 0) I = np.zeros((circle.shape[0] + 2 * pad, circle.shape[1] + 2 * pad), dtype=np.uint8) + 255 I[pad:circle.shape[0] + pad, pad:circle.shape[1] + pad] = circle I = I.astype(np.float32) I[20, 20] = 0 I[10:13, 10:40] = 0 grads = image_gradient(I, 2.0) edges = compute_edge_points(grads) links = chain_edge_points(edges, grads) chains = thresholds_with_hysteresis(edges, links, grads, 1, 0.1)
30.006289
99
0.501153
795a5d3d7db4f587ed70e5199fd3a5959c5992d9
1,074
py
Python
flask/testsuite/deprecations.py
Khan/flask
e78e2a1641e5b7ad538d93154ee59445f4d4eaf7
[ "BSD-3-Clause" ]
137
2015-01-12T19:29:04.000Z
2022-02-25T04:51:02.000Z
flask/testsuite/deprecations.py
Khan/flask
e78e2a1641e5b7ad538d93154ee59445f4d4eaf7
[ "BSD-3-Clause" ]
24
2015-01-06T08:36:13.000Z
2019-04-08T13:59:05.000Z
flask/testsuite/deprecations.py
Khan/flask
e78e2a1641e5b7ad538d93154ee59445f4d4eaf7
[ "BSD-3-Clause" ]
57
2015-01-01T00:42:44.000Z
2022-03-10T20:54:41.000Z
# -*- coding: utf-8 -*- """ flask.testsuite.deprecations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests deprecation support. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import flask import unittest from flask.testsuite import FlaskTestCase, catch_warnings class DeprecationsTestCase(FlaskTestCase): def test_init_jinja_globals(self): class MyFlask(flask.Flask): def init_jinja_globals(self): self.jinja_env.globals['foo'] = '42' with catch_warnings() as log: app = MyFlask(__name__) @app.route('/') def foo(): return app.jinja_env.globals['foo'] c = app.test_client() self.assert_equal(c.get('/').data, '42') self.assert_equal(len(log), 1) self.assert_('init_jinja_globals' in str(log[0]['message'])) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DeprecationsTestCase)) return suite
25.571429
72
0.608939
795a5d4c7ea461b751d848f57b8c756d54419bd4
879
py
Python
src/foreign_if/python/UT/src/eigen/test_015.py
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
src/foreign_if/python/UT/src/eigen/test_015.py
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
src/foreign_if/python/UT/src/eigen/test_015.py
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#!/usr/bin/env python import sys import numpy as np from frovedis.exrpc.server import FrovedisServer from frovedis.linalg import eigsh desc = "Testing eigsh() for which = 'LM': " # initializing the Frovedis server argvs = sys.argv argc = len(argvs) if argc < 2: print ('Please give frovedis_server calling command as the first argument \n' '(e.g. "mpirun -np 2 /opt/nec/frovedis/ve/bin/frovedis_server")') quit() FrovedisServer.initialize(argvs[1]) # sample numpy array square symmetric dense data (6x6) mat = np.asarray([[2.,-1.,0.,0.,-1.,0.], [-1.,3.,-1.,0.,-1.,0.], [0.,-1.,2.,-1.,0.,0.], [0.,0.,-1.,3.,-1.,-1], [-1.,-1.,0.,-1.,3.,0.], [0.,0.,0.,-1.,0.,1.]]) try: eigen_vals, eigen_vecs = eigsh(mat, k = 3, which = 'LM') print(desc, "Passed") except: print(desc, "Failed") FrovedisServer.shut_down()
29.3
81
0.60182
795a5d50eab9d23a088ce3b31219daf2dbff0f6a
20,803
py
Python
many_constraints/intersectional_fairness.py
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
23,901
2018-10-04T19:48:53.000Z
2022-03-31T21:27:42.000Z
many_constraints/intersectional_fairness.py
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
891
2018-11-10T06:16:13.000Z
2022-03-31T10:42:34.000Z
many_constraints/intersectional_fairness.py
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
6,047
2018-10-12T06:31:02.000Z
2022-03-31T13:59:28.000Z
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Intersectional fairness with many constraint.""" import random from absl import app from absl import flags import numpy as np import pandas as pd from sklearn import model_selection import tensorflow.compat.v1 as tf import tensorflow_constrained_optimization as tfco flags.DEFINE_boolean("constrained", True, "Perform constrained optimization?") flags.DEFINE_float("dual_scale", 0.01, "Dual scale for gamma-updates.") flags.DEFINE_float("epsilon", 0.01, "Slack.") flags.DEFINE_integer("loops", 100000, "No. of loops.") flags.DEFINE_integer("num_layers", 2, "No. of hidden layers for multiplier model.") flags.DEFINE_integer("num_nodes", 100, "No. of hidden nodes for multiplier model.") FLAGS = flags.FLAGS def load_data(): """Loads and returns data.""" # List of column names in the dataset. column_names = ["state", "county", "community", "communityname", "fold", "population", "householdsize", "racepctblack", "racePctWhite", "racePctAsian", "racePctHisp", "agePct12t21", "agePct12t29", "agePct16t24", "agePct65up", "numbUrban", "pctUrban", "medIncome", "pctWWage", "pctWFarmSelf", "pctWInvInc", "pctWSocSec", "pctWPubAsst", "pctWRetire", "medFamInc", "perCapInc", "whitePerCap", "blackPerCap", "indianPerCap", "AsianPerCap", "OtherPerCap", "HispPerCap", "NumUnderPov", "PctPopUnderPov", "PctLess9thGrade", "PctNotHSGrad", "PctBSorMore", "PctUnemployed", "PctEmploy", "PctEmplManu", "PctEmplProfServ", "PctOccupManu", "PctOccupMgmtProf", "MalePctDivorce", "MalePctNevMarr", "FemalePctDiv", "TotalPctDiv", "PersPerFam", "PctFam2Par", "PctKids2Par", "PctYoungKids2Par", "PctTeen2Par", "PctWorkMomYoungKids", "PctWorkMom", "NumIlleg", "PctIlleg", "NumImmig", "PctImmigRecent", "PctImmigRec5", "PctImmigRec8", "PctImmigRec10", "PctRecentImmig", "PctRecImmig5", "PctRecImmig8", "PctRecImmig10", "PctSpeakEnglOnly", "PctNotSpeakEnglWell", "PctLargHouseFam", "PctLargHouseOccup", "PersPerOccupHous", "PersPerOwnOccHous", "PersPerRentOccHous", "PctPersOwnOccup", "PctPersDenseHous", "PctHousLess3BR", "MedNumBR", "HousVacant", "PctHousOccup", "PctHousOwnOcc", "PctVacantBoarded", "PctVacMore6Mos", "MedYrHousBuilt", "PctHousNoPhone", "PctWOFullPlumb", "OwnOccLowQuart", "OwnOccMedVal", "OwnOccHiQuart", "RentLowQ", "RentMedian", "RentHighQ", "MedRent", "MedRentPctHousInc", "MedOwnCostPctInc", "MedOwnCostPctIncNoMtg", "NumInShelters", "NumStreet", "PctForeignBorn", "PctBornSameState", "PctSameHouse85", "PctSameCity85", "PctSameState85", "LemasSwornFT", "LemasSwFTPerPop", "LemasSwFTFieldOps", "LemasSwFTFieldPerPop", "LemasTotalReq", "LemasTotReqPerPop", "PolicReqPerOffic", "PolicPerPop", "RacialMatchCommPol", "PctPolicWhite", "PctPolicBlack", "PctPolicHisp", "PctPolicAsian", "PctPolicMinor", "OfficAssgnDrugUnits", "NumKindsDrugsSeiz", "PolicAveOTWorked", "LandArea", "PopDens", "PctUsePubTrans", "PolicCars", "PolicOperBudg", "LemasPctPolicOnPatr", "LemasGangUnitDeploy", "LemasPctOfficDrugUn", "PolicBudgPerPop", "ViolentCrimesPerPop"] dataset_url = "http://archive.ics.uci.edu/ml/machine-learning-databases/communities/communities.data" # Read dataset from the UCI web repository and assign column names. data_df = pd.read_csv(dataset_url, sep=",", names=column_names, na_values="?") # Make sure there are no missing values in the "ViolentCrimesPerPop" column. assert not data_df["ViolentCrimesPerPop"].isna().any() # Binarize the "ViolentCrimesPerPop" column and obtain labels. crime_rate_70_percentile = data_df["ViolentCrimesPerPop"].quantile(q=0.7) labels_df = (data_df["ViolentCrimesPerPop"] >= crime_rate_70_percentile) # Now that we have assigned binary labels, # we drop the "ViolentCrimesPerPop" column from the data frame. data_df.drop(columns="ViolentCrimesPerPop", inplace=True) # Group features. groups_df = pd.concat( [data_df["racepctblack"], data_df["racePctAsian"], data_df["racePctHisp"]], axis=1) # Drop categorical features. data_df.drop( columns=["state", "county", "community", "communityname", "fold"], inplace=True) # Handle missing features. feature_names = data_df.columns for feature_name in feature_names: missing_rows = data_df[feature_name].isna() if missing_rows.any(): data_df[feature_name].fillna(0.0, inplace=True) # Fill NaN with 0. missing_rows.rename(feature_name + "_is_missing", inplace=True) # Append boolean "is_missing" feature. data_df = data_df.join(missing_rows) labels = labels_df.values.astype(np.float32) groups = groups_df.values.astype(np.float32) features = data_df.values.astype(np.float32) # Set random seed so that the results are reproducible. np.random.seed(121212) # Train, vali and test indices. train_indices, test_indices = model_selection.train_test_split( range(features.shape[0]), test_size=0.25) train_indices, vali_indices = model_selection.train_test_split( train_indices, test_size=1./3.) # Train features, labels and protected groups. x_train = features[train_indices, :] y_train = labels[train_indices] z_train = groups[train_indices] # Vali features, labels and protected groups. x_vali = features[vali_indices, :] y_vali = labels[vali_indices] z_vali = groups[vali_indices] # Test features, labels and protected groups. x_test = features[test_indices, :] y_test = labels[test_indices] z_test = groups[test_indices] return (x_train, y_train, z_train, x_vali, y_vali, z_vali, x_test, y_test, z_test) def error_rate(labels, predictions, groups=None): # Returns the error rate for given labels and predictions. if groups is not None: if np.sum(groups) == 0.0: return 0.0 predictions = predictions[groups] labels = labels[groups] signed_labels = labels - 0.5 return np.mean(signed_labels * predictions <= 0.0) def group_membership_thresholds( group_feature_train, group_feature_vali, group_feature_test, thresholds): """Returns the group membership vectors on train, test and vali sets.""" group_memberships_list_train_ = [] group_memberships_list_vali_ = [] group_memberships_list_test_ = [] group_thresholds_list = [] for t1 in thresholds[0]: for t2 in thresholds[1]: for t3 in thresholds[2]: group_membership_train = (group_feature_train[:, 0] > t1) & ( group_feature_train[:, 1] > t2) & (group_feature_train[:, 2] > t3) group_membership_vali = (group_feature_vali[:, 0] > t1) & ( group_feature_vali[:, 1] > t2) & (group_feature_vali[:, 2] > t3) group_membership_test = (group_feature_test[:, 0] > t1) & ( group_feature_test[:, 1] > t2) & (group_feature_test[:, 2] > t3) if (np.mean(group_membership_train) <= 0.01) or ( np.mean(group_membership_vali) <= 0.01) or ( np.mean(group_membership_test) <= 0.01): # Only consider groups that are at least 1% in size. continue group_memberships_list_train_.append(group_membership_train) group_memberships_list_vali_.append(group_membership_vali) group_memberships_list_test_.append(group_membership_test) group_thresholds_list.append([t1, t2, t3]) group_memberships_list_train_ = np.array(group_memberships_list_train_) group_memberships_list_vali_ = np.array(group_memberships_list_vali_) group_memberships_list_test_ = np.array(group_memberships_list_test_) group_thresholds_list = np.array(group_thresholds_list) return (group_memberships_list_train_, group_memberships_list_vali_, group_memberships_list_test_, group_thresholds_list) def violation( labels, predictions, epsilon, group_memberships_list): # Returns violations across different group feature thresholds. viol_list = [] overall_error = error_rate(labels, predictions) for kk in range(group_memberships_list.shape[0]): group_err = error_rate( labels, predictions, group_memberships_list[kk, :].reshape(-1,)) viol_list += [group_err - overall_error - epsilon] return np.max(viol_list), viol_list def evaluate( features, labels, model, epsilon, group_membership_list): # Evaluates and prints stats. predictions = model(features).numpy().reshape(-1,) print("Error %.3f" % error_rate(labels, predictions)) _, viol_list = violation(labels, predictions, epsilon, group_membership_list) print("99p Violation %.3f" % np.quantile(viol_list, 0.99)) print() def create_model(dimension): # Creates linear Keras model with no hidden layers. layers = [] layers.append(tf.keras.Input(shape=(dimension,))) layers.append(tf.keras.layers.Dense(1)) model = tf.keras.Sequential(layers) return model def create_multiplier_model( feature_dependent_multiplier=True, dim=1, hidden_layers=None): """Creates Lagrange multipler model with specified hidden layers.""" if feature_dependent_multiplier: layers = [] layers.append(tf.keras.Input(shape=dim)) for num_nodes in hidden_layers: layers.append(tf.keras.layers.Dense(num_nodes, activation="relu")) layers.append(tf.keras.layers.Dense(1, bias_initializer="ones")) # Keras model. multiplier_model = tf.keras.Sequential(layers) multiplier_weights = multiplier_model.trainable_weights else: common_multiplier = tf.Variable(1.0, name="common_multiplier") # Ignore feature input, and return common multiplier. multiplier_model = lambda x: common_multiplier multiplier_weights = [common_multiplier] return multiplier_model, multiplier_weights def train_unconstrained( dataset, group_info, epsilon=0.01, loops=10000, skip_steps=400): """Train unconstrained classifier. Args: dataset: train, vali and test sets group_info: group memberships on train, vali and test sets and thresholds epsilon: constraint slack loops: number of gradient steps skip_steps: steps to skip before snapshotting metrics """ tf.set_random_seed(121212) np.random.seed(212121) random.seed(333333) x_train, y_train, _, x_vali, y_vali, _, x_test, y_test, _ = dataset (group_memberships_list_train, group_memberships_list_vali, group_memberships_list_test, _) = group_info model = create_model(x_train.shape[-1]) features_tensor = tf.constant(x_train) labels_tensor = tf.constant(y_train) predictions = lambda: model(features_tensor) predictions_vali = lambda: model(x_vali) predictions_test = lambda: model(x_test) context = tfco.rate_context(predictions, labels=lambda: labels_tensor) overall_error = tfco.error_rate(context, penalty_loss=tfco.HingeLoss()) problem = tfco.RateMinimizationProblem(overall_error) loss_fn, update_ops_fn, _ = tfco.create_lagrangian_loss(problem) optimizer = tf.keras.optimizers.Adagrad(0.1) objectives_list = [] objectives_list_test = [] objectives_list_vali = [] violations_list = [] violations_list_test = [] violations_list_vali = [] model_weights = [] for ii in range(loops): update_ops_fn() optimizer.minimize(loss_fn, var_list=model.trainable_weights) # Snapshot iterate once in 1000 loops. if ii % skip_steps == 0: pred = np.reshape(predictions(), (-1,)) err = error_rate(y_train, pred) max_viol, viol_list = violation( y_train, pred, epsilon, group_memberships_list_train) pred_test = np.reshape(predictions_test(), (-1,)) err_test = error_rate(y_test, pred_test) _, viol_list_test = violation( y_test, pred_test, epsilon, group_memberships_list_test) pred_vali = np.reshape(predictions_vali(), (-1,)) err_vali = error_rate(y_vali, pred_vali) max_viol_vali, viol_list_vali = violation( y_vali, pred_vali, epsilon, group_memberships_list_vali) objectives_list.append(err) objectives_list_test.append(err_test) objectives_list_vali.append(err_vali) violations_list.append(viol_list) violations_list_test.append(viol_list_test) violations_list_vali.append(viol_list_vali) model_weights.append(model.get_weights()) if ii % 1000 == 0: print("Epoch %d | Error = %.3f | Viol = %.3f | Viol_vali = %.3f" % (ii, err, max_viol, max_viol_vali), flush=True) # Best candidate index. best_ind = np.argmin(objectives_list) model.set_weights(model_weights[best_ind]) print("Train:") evaluate(x_train, y_train, model, epsilon, group_memberships_list_train) print("\nVali:") evaluate(x_vali, y_vali, model, epsilon, group_memberships_list_vali) print("\nTest:") evaluate(x_test, y_test, model, epsilon, group_memberships_list_test) def train_constrained( dataset, group_info, epsilon=0.01, learning_rate=0.1, dual_scale=5.0, loops=10000, feature_dependent_multiplier=True, hidden_layers=None, skip_steps=400): """Train constrained classifier wth Lagrangian model. Args: dataset: train, vali and test sets group_info: group memberships on train, vali and test sets and thresholds epsilon: constraint slack learning_rate: learning rate for theta dual_scale: learning rate for gamma = dual_scale * learning_rate loops: number of gradient steps feature_dependent_multiplier: should the multiplier model be feature dependent. If False, a common multipler is used for all constraints hidden_layers: list of hidden layer nodes to be used for multiplier model skip_steps: steps to skip before snapshotting metrics """ tf.set_random_seed(121212) np.random.seed(212121) random.seed(333333) x_train, y_train, z_train, x_vali, y_vali, _, x_test, y_test, _ = dataset (group_memberships_list_train, group_memberships_list_vali, group_memberships_list_test, group_memberships_thresholds_train) = group_info # Models and group thresholds tensor. model = create_model(x_train.shape[-1]) multiplier_model, multiplier_weights = create_multiplier_model( feature_dependent_multiplier=feature_dependent_multiplier, dim=3, hidden_layers=hidden_layers) group_thresholds = tf.Variable(np.ones(3) * 0.1, dtype=tf.float32) # Features, labels, predictions, multipliers. features_tensor = tf.constant(x_train) labels_tensor = tf.constant(y_train) features_tensor_vali = tf.constant(x_vali) predictions = lambda: model(features_tensor) predictions_vali = lambda: model(features_tensor_vali) predictions_test = lambda: model(x_test) def multiplier_values(): return tf.abs(multiplier_model(tf.reshape(group_thresholds, shape=(1, -1)))) # Lagrangian loss function. def lagrangian_loss(): # Separate out objective, constraints and proxy constraints. objective = problem.objective() constraints = problem.constraints() proxy_constraints = problem.proxy_constraints() # Set-up custom Lagrangian loss. primal = objective multipliers = multiplier_values() primal += tf.stop_gradient(multipliers) * proxy_constraints dual = dual_scale * multipliers * tf.stop_gradient(constraints) return primal - dual # Objective. context = tfco.rate_context( predictions, labels=lambda: labels_tensor) overall_error = tfco.error_rate(context) # Slice and subset group predictions and labels. def group_membership(): return (z_train[:, 0] > group_thresholds[0]) & ( z_train[:, 1] > group_thresholds[1]) & ( z_train[:, 2] > group_thresholds[2]) def group_predictions(): pred = predictions() groups = tf.reshape(group_membership(), (-1, 1)) return pred[groups] def group_labels(): groups = tf.reshape(group_membership(), (-1,)) return labels_tensor[groups] # Constraint. group_context = tfco.rate_context( group_predictions, labels=group_labels) group_error = tfco.error_rate(group_context) constraints = [group_error <= overall_error + epsilon] # Set up constrained optimization problem and optimizer. problem = tfco.RateMinimizationProblem(overall_error, constraints) optimizer = tf.keras.optimizers.Adagrad(learning_rate) var_list = model.trainable_weights + multiplier_weights objectives_list = [] objectives_list_test = [] objectives_list_vali = [] violations_list = [] violations_list_test = [] violations_list_vali = [] model_weights = [] # Training for ii in range(loops): # Sample a group membership at random. random_index = np.random.randint( group_memberships_thresholds_train.shape[0]) group_thresholds.assign(group_memberships_thresholds_train[random_index, :]) # Gradient op. problem.update_ops() optimizer.minimize(lagrangian_loss, var_list=var_list) # Snapshot iterate once in 1000 loops. if ii % skip_steps == 0: pred = np.reshape(predictions(), (-1,)) err = error_rate(y_train, pred) max_viol, viol_list = violation( y_train, pred, epsilon, group_memberships_list_train) pred_test = np.reshape(predictions_test(), (-1,)) err_test = error_rate(y_test, pred_test) _, viol_list_test = violation( y_test, pred_test, epsilon, group_memberships_list_test) pred_vali = np.reshape(predictions_vali(), (-1,)) err_vali = error_rate(y_vali, pred_vali) max_viol_vali, viol_list_vali = violation( y_vali, pred_vali, epsilon, group_memberships_list_vali) objectives_list.append(err) objectives_list_test.append(err_test) objectives_list_vali.append(err_vali) violations_list.append(viol_list) violations_list_test.append(viol_list_test) violations_list_vali.append(viol_list_vali) model_weights.append(model.get_weights()) if ii % 1000 == 0: print("Epoch %d | Error = %.3f | Viol = %.3f | Viol_vali = %.3f" % (ii, err, max_viol, max_viol_vali), flush=True) # Best candidate index. best_ind = tfco.find_best_candidate_index( np.array(objectives_list), np.array(violations_list), rank_objectives=False) model.set_weights(model_weights[best_ind]) print("Train:") evaluate(x_train, y_train, model, epsilon, group_memberships_list_train) print("\nVali:") evaluate(x_vali, y_vali, model, epsilon, group_memberships_list_vali) print("\nTest:") evaluate(x_test, y_test, model, epsilon, group_memberships_list_test) def main(argv): del argv tf.compat.v1.enable_eager_execution() # Load data. dataset = load_data() _, _, z_train, _, _, z_vali, _, _, z_test = dataset # Group Thresholds for 3 Groups group_threshold_range = [] for jj in range(3): group_threshold_range.append([np.quantile( z_train[:, jj], kk) for kk in np.arange(0.05, 1.0, 0.1)]) # Group memberships based on group thresholds. group_info = group_membership_thresholds( z_train, z_vali, z_test, group_threshold_range) if FLAGS.constrained: if FLAGS.num_layers < 0: train_constrained( dataset, group_info, feature_dependent_multiplier=False, epsilon=FLAGS.epsilon, dual_scale=FLAGS.dual_scale, loops=FLAGS.loops) else: train_constrained( dataset, group_info, feature_dependent_multiplier=True, hidden_layers=[FLAGS.num_nodes] * FLAGS.num_layers, epsilon=FLAGS.epsilon, dual_scale=FLAGS.dual_scale, loops=FLAGS.loops) else: train_unconstrained( dataset, group_info, epsilon=FLAGS.epsilon, loops=FLAGS.loops) if __name__ == "__main__": app.run(main)
38.381919
103
0.700812
795a5ddb857141b583c7f3a8e54a079cd107ef23
1,293
py
Python
core/urls.py
thirawr/django-datafreezer-sample
ef007e9ea583c963c012224fbab133154214cf0c
[ "MIT" ]
null
null
null
core/urls.py
thirawr/django-datafreezer-sample
ef007e9ea583c963c012224fbab133154214cf0c
[ "MIT" ]
null
null
null
core/urls.py
thirawr/django-datafreezer-sample
ef007e9ea583c963c012224fbab133154214cf0c
[ "MIT" ]
null
null
null
"""core URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.http import HttpResponseRedirect from django.conf import settings from django.conf.urls.static import static as serve_static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^datafreezer/', include('datafreezer.urls'), name='datafreezer_root'), url(r'^$', RedirectView.as_view(url='datafreezer/')), ] + serve_static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
36.942857
80
0.723898
795a5e12e78abf9e16c87926f1c66013b10b9e95
707
py
Python
serpapi_async/walmart_search.py
pualien/google-search-results-python
a7e013194fa14ea9d2e077b41f1d25da0440ecb5
[ "MIT" ]
null
null
null
serpapi_async/walmart_search.py
pualien/google-search-results-python
a7e013194fa14ea9d2e077b41f1d25da0440ecb5
[ "MIT" ]
null
null
null
serpapi_async/walmart_search.py
pualien/google-search-results-python
a7e013194fa14ea9d2e077b41f1d25da0440ecb5
[ "MIT" ]
null
null
null
from serpapi_async.serp_api_client import * from serpapi_async.serp_api_client_exception import SerpApiClientException from serpapi_async.constant import * class WalmartSearch(SerpApiClient): """WalmartSearch enables to search google scholar and parse the result. ```python from serpapi import WalmartSearch search = WalmartSearch({"query": "chair"}) data = search.get_dict() ``` doc: https://serpapi.com/walmart-search-api """ def __init__(self, params_dict): super(WalmartSearch, self).__init__(params_dict, WALMART_ENGINE) def get_location(self, q, limit = 5): raise SerpApiClientException("location is not supported by walmart search engine")
33.666667
90
0.738331
795a5e2a164192967de5a43ef8592e96fd899e9d
5,289
py
Python
ppcls/engine/evaluation/classification.py
BurrowsWang/PaddleClas
c30b72c867c648bdd460c6bfcb062f561a0f312e
[ "Apache-2.0" ]
2
2020-09-16T12:33:50.000Z
2021-04-12T12:25:39.000Z
ppcls/engine/evaluation/classification.py
dyning/PaddleClas
c30b72c867c648bdd460c6bfcb062f561a0f312e
[ "Apache-2.0" ]
null
null
null
ppcls/engine/evaluation/classification.py
dyning/PaddleClas
c30b72c867c648bdd460c6bfcb062f561a0f312e
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import platform import paddle from ppcls.utils.misc import AverageMeter from ppcls.utils import logger def classification_eval(engine, epoch_id=0): output_info = dict() time_info = { "batch_cost": AverageMeter( "batch_cost", '.5f', postfix=" s,"), "reader_cost": AverageMeter( "reader_cost", ".5f", postfix=" s,"), } print_batch_step = engine.config["Global"]["print_batch_step"] metric_key = None tic = time.time() accum_samples = 0 total_samples = len( engine.eval_dataloader. dataset) if not engine.use_dali else engine.eval_dataloader.size max_iter = len(engine.eval_dataloader) - 1 if platform.system( ) == "Windows" else len(engine.eval_dataloader) for iter_id, batch in enumerate(engine.eval_dataloader): if iter_id >= max_iter: break if iter_id == 5: for key in time_info: time_info[key].reset() if engine.use_dali: batch = [ paddle.to_tensor(batch[0]['data']), paddle.to_tensor(batch[0]['label']) ] time_info["reader_cost"].update(time.time() - tic) batch_size = batch[0].shape[0] batch[0] = paddle.to_tensor(batch[0]).astype("float32") if not engine.config["Global"].get("use_multilabel", False): batch[1] = batch[1].reshape([-1, 1]).astype("int64") # image input out = engine.model(batch[0]) # calc loss if engine.eval_loss_func is not None: loss_dict = engine.eval_loss_func(out, batch[1]) for key in loss_dict: if key not in output_info: output_info[key] = AverageMeter(key, '7.5f') output_info[key].update(loss_dict[key].numpy()[0], batch_size) # just for DistributedBatchSampler issue: repeat sampling current_samples = batch_size * paddle.distributed.get_world_size() accum_samples += current_samples # calc metric if engine.eval_metric_func is not None: if paddle.distributed.get_world_size() > 1: pred_list = [] label_list = [] if isinstance(out, dict): out = out["logits"] paddle.distributed.all_gather(pred_list, out) paddle.distributed.all_gather(label_list, batch[1]) pred = paddle.concat(pred_list, 0) labels = paddle.concat(label_list, 0) if accum_samples > total_samples: pred = pred[:total_samples + current_samples - accum_samples] labels = labels[:total_samples + current_samples - accum_samples] current_samples = total_samples + current_samples - accum_samples metric_dict = engine.eval_metric_func(pred, labels) else: metric_dict = engine.eval_metric_func(out, batch[1]) for key in metric_dict: if metric_key is None: metric_key = key if key not in output_info: output_info[key] = AverageMeter(key, '7.5f') output_info[key].update(metric_dict[key].numpy()[0], current_samples) time_info["batch_cost"].update(time.time() - tic) if iter_id % print_batch_step == 0: time_msg = "s, ".join([ "{}: {:.5f}".format(key, time_info[key].avg) for key in time_info ]) ips_msg = "ips: {:.5f} images/sec".format( batch_size / time_info["batch_cost"].avg) metric_msg = ", ".join([ "{}: {:.5f}".format(key, output_info[key].val) for key in output_info ]) logger.info("[Eval][Epoch {}][Iter: {}/{}]{}, {}, {}".format( epoch_id, iter_id, len(engine.eval_dataloader), metric_msg, time_msg, ips_msg)) tic = time.time() if engine.use_dali: engine.eval_dataloader.reset() metric_msg = ", ".join([ "{}: {:.5f}".format(key, output_info[key].avg) for key in output_info ]) logger.info("[Eval][Epoch {}][Avg]{}".format(epoch_id, metric_msg)) # do not try to save best eval.model if engine.eval_metric_func is None: return -1 # return 1st metric in the dict return output_info[metric_key].avg
39.470149
85
0.585744
795a5f2d56cf388dcce9971fff4fbc43708154dc
1,451
py
Python
RBDtector/util/settings.py
aroethen/RBDtector
7c9c73d231a29d8ccf56d7eec69ae117ae781c0c
[ "MIT" ]
null
null
null
RBDtector/util/settings.py
aroethen/RBDtector
7c9c73d231a29d8ccf56d7eec69ae117ae781c0c
[ "MIT" ]
null
null
null
RBDtector/util/settings.py
aroethen/RBDtector
7c9c73d231a29d8ccf56d7eec69ae117ae781c0c
[ "MIT" ]
null
null
null
# Internally used sample rate RATE = 256 # Signal names of EMG channels in EDF files to be evaluated for RSWA SIGNALS_TO_EVALUATE = ['EMG', 'PLM l', 'PLM r', 'AUX', 'Akti.'] CHIN = 0 LEGS = [1, 2] ARMS = [3, 4] # Artifact types to be excluded from evaluation FLOW = False HUMAN_ARTIFACTS = False SNORE = True # Use manually defined static baselines from a baseline file instead of calculating adaptive baseline levels HUMAN_BASELINE = False # Internal calculation variables - change default values only in case of optimization study COUNT_BASED_ACTIVITY = False MIN_SUSTAINED = 0.1 MAX_GAP_SIZE = 0.25 CHUNK_SIZE = '30L' WITH_OFFSET = True OFFSET_SIZE = '15L' def settings_as_string(): return str(f'RATE = {RATE}\n' + f'FLOW = {FLOW}\n' + f'HUMAN_ARTIFACTS = {HUMAN_ARTIFACTS}\n' + f'HUMAN_BASELINE = {HUMAN_BASELINE}\n' + f'SNORE = {SNORE}\n' + f'COUNT_BASED_ACTIVITY = {COUNT_BASED_ACTIVITY}\n' + f'MIN_SUSTAINED = {MIN_SUSTAINED}\n' + f'MAX_GAP_SIZE = {MAX_GAP_SIZE}\n' + f'CHUNK_SIZE = {CHUNK_SIZE}\n' + f'WITH_OFFSET = {WITH_OFFSET}\n' + f'OFFSET_SIZE = {OFFSET_SIZE}\n' + f'SIGNALS_TO_EVALUATE = {str(SIGNALS_TO_EVALUATE)}\n' + f'CHIN = {str(CHIN)}\n' + f'LEGS = {str(LEGS)}\n' + f'ARMS = {str(ARMS)}\n' )
30.229167
108
0.600965
795a5f5f78f3fd5f920db4546dfe0d82c667d9d5
2,216
py
Python
core/src/trezor/ui/num_pad.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
null
null
null
core/src/trezor/ui/num_pad.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
1
2019-02-08T00:22:42.000Z
2019-02-13T09:41:54.000Z
core/src/trezor/ui/num_pad.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
2
2019-02-07T23:57:09.000Z
2020-10-21T07:07:27.000Z
from trezor import res, ui from trezor.ui import display from trezor.ui.button import BTN_CLICKED, Button ITEMS_PER_PAGE = 10 PLUS_BUTTON_POSITION = 11 BACK_BUTTON_POSITION = 9 def digit_area(i): return ui.grid(i + 3) # skip the first line class NumPad(ui.Widget): def __init__(self, label: str, start: int, end: int): """ Generates a numpad with numbers from `start` to `end` excluding. """ self.label = label self.start = start self.end = end self.page = 0 self._generate_buttons() def render(self): for btn in self.buttons: btn.render() # header label display.text_center(ui.WIDTH // 2, 36, self.label, ui.BOLD, ui.GREY, ui.BG) def touch(self, event, pos): for btn in self.buttons: if btn.touch(event, pos) == BTN_CLICKED: if "+" in btn.content: self.page += 1 self._generate_buttons() elif isinstance(btn.content, bytes): self.page -= 1 self._generate_buttons() else: return btn.content def _generate_buttons(self): display.clear() # we need to clear old buttons start = self.start + (ITEMS_PER_PAGE + 1) * self.page - self.page end = min(self.end, (ITEMS_PER_PAGE + 1) * (self.page + 1) - self.page) digits = list(range(start, end)) self.buttons = [Button(digit_area(i), str(d)) for i, d in enumerate(digits)] if len(digits) == ITEMS_PER_PAGE: more = Button( digit_area(PLUS_BUTTON_POSITION), str(end) + "+", style=ui.BTN_KEY_DARK ) self.buttons.append(more) # move the tenth button to its proper place and make place for the back button self.buttons[BACK_BUTTON_POSITION].area = digit_area( BACK_BUTTON_POSITION + 1 ) back = Button( digit_area(BACK_BUTTON_POSITION), res.load(ui.ICON_BACK), style=ui.BTN_KEY_DARK, ) if self.page == 0: back.disable() self.buttons.append(back)
31.657143
90
0.561823
795a5f8f6b37a2c5ffa0ee2084aeff2c4f0e2ba9
477
py
Python
test/test_jump.py
mind-owner/Cyberbrain
07dcfc0b910558420e61a7a2ff687703c0bd7aeb
[ "MIT" ]
2,440
2019-09-21T04:21:55.000Z
2022-03-30T09:47:47.000Z
test/test_jump.py
laike9m/cb-experimental
ef92fee10e3fd4ff4bcee38bf8356b0d645519e3
[ "MIT" ]
103
2019-09-21T15:19:59.000Z
2022-03-28T06:27:40.000Z
test/test_jump.py
laike9m/cb-experimental
ef92fee10e3fd4ff4bcee38bf8356b0d645519e3
[ "MIT" ]
162
2019-07-16T08:03:18.000Z
2022-03-30T02:51:21.000Z
from cyberbrain import Binding, InitialValue, Symbol def test_jump(tracer, check_golden_file): a = [] b = "b" c = "c" tracer.start() if a: # POP_JUMP_IF_FALSE pass # JUMP_FORWARD else: x = 1 if not a: # POP_JUMP_IF_TRUE x = 2 x = a != b != c # JUMP_IF_FALSE_OR_POP x = a == b or c # JUMP_IF_TRUE_OR_POP # TODO: Test JUMP_ABSOLUTE. This requires loop instructions to be Implemented. tracer.stop()
19.08
82
0.597484
795a5fa768d6fa3c4752d4cf7afbd1dab9c73e7b
42,023
py
Python
fairseq/models/transformer.py
xfdywy/fairseq
a914bb46c9ba4cca8eb9d32bef2a1ae770954d97
[ "BSD-3-Clause" ]
117
2019-07-05T04:37:01.000Z
2022-02-17T04:32:31.000Z
fairseq/models/transformer.py
xfdywy/fairseq
a914bb46c9ba4cca8eb9d32bef2a1ae770954d97
[ "BSD-3-Clause" ]
16
2019-07-30T07:12:29.000Z
2021-01-18T03:52:55.000Z
fairseq/models/transformer.py
xfdywy/fairseq
a914bb46c9ba4cca8eb9d32bef2a1ae770954d97
[ "BSD-3-Clause" ]
31
2019-07-05T12:09:27.000Z
2022-03-03T05:41:27.000Z
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options from fairseq import utils from fairseq.modules import ( AdaptiveInput, AdaptiveSoftmax, CharacterTokenEmbedder, LearnedPositionalEmbedding, MultiheadAttention, SinusoidalPositionalEmbedding ) from . import ( FairseqIncrementalDecoder, FairseqEncoder, FairseqLanguageModel, FairseqModel, register_model, register_model_architecture, ) @register_model('transformer') class TransformerModel(FairseqModel): """ Transformer model from `"Attention Is All You Need" (Vaswani, et al, 2017) <https://arxiv.org/abs/1706.03762>`_. Args: encoder (TransformerEncoder): the encoder decoder (TransformerDecoder): the decoder The Transformer model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.transformer_parser :prog: """ def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" # fmt: off parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N', help='encoder embedding dimension for FFN') parser.add_argument('--encoder-layers', type=int, metavar='N', help='num encoder layers') parser.add_argument('--encoder-attention-heads', type=int, metavar='N', help='num encoder attention heads') parser.add_argument('--encoder-normalize-before', action='store_true', help='apply layernorm before each encoder block') parser.add_argument('--encoder-learned-pos', action='store_true', help='use learned positional embeddings in the encoder') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-learned-pos', action='store_true', help='use learned positional embeddings in the decoder') parser.add_argument('--decoder-normalize-before', action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--share-decoder-input-output-embed', action='store_true', help='share decoder input and output embeddings') parser.add_argument('--share-all-embeddings', action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true', help='if set, disables positional embeddings (outside self attention)') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion'), parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') # fmt: on @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_architecture(args) if not hasattr(args, 'max_source_positions'): args.max_source_positions = 1024 if not hasattr(args, 'max_target_positions'): args.max_target_positions = 1024 src_dict, tgt_dict = task.source_dictionary, task.target_dictionary def build_embedding(dictionary, embed_dim, path=None): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) # if provided, load from preloaded dictionaries if path: embed_dict = utils.parse_embedding(path) utils.load_embedding(embed_dict, dictionary, emb) return emb if args.share_all_embeddings: if src_dict != tgt_dict: raise ValueError('--share-all-embeddings requires a joined dictionary') if args.encoder_embed_dim != args.decoder_embed_dim: raise ValueError( '--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim') if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path): raise ValueError('--share-all-embeddings not compatible with --decoder-embed-path') encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = encoder_embed_tokens args.share_decoder_input_output_embed = True else: encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = build_embedding( tgt_dict, args.decoder_embed_dim, args.decoder_embed_path ) encoder = TransformerEncoder(args, src_dict, encoder_embed_tokens) decoder = TransformerDecoder(args, tgt_dict, decoder_embed_tokens) return TransformerModel(encoder, decoder) @register_model('transformer_lm') class TransformerLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" # fmt: off parser.add_argument('--dropout', default=0.1, type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', default=0., type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', default=0., type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-output-dim', type=int, metavar='N', help='decoder output dimension') parser.add_argument('--decoder-input-dim', type=int, metavar='N', help='decoder input dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-normalize-before', default=False, action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--adaptive-softmax-factor', type=float, metavar='N', help='adaptive input factor') parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true', help='if set, disables positional embeddings (outside self attention)') parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true', help='share decoder input and output embeddings') parser.add_argument('--character-embeddings', default=False, action='store_true', help='if set, uses character embedding convolutions to produce token embeddings') parser.add_argument('--character-filters', type=str, metavar='LIST', default='[(1, 64), (2, 128), (3, 192), (4, 256), (5, 256), (6, 256), (7, 256)]', help='size of character embeddings') parser.add_argument('--character-embedding-dim', type=int, metavar='N', default=4, help='size of character embeddings') parser.add_argument('--char-embedder-highway-layers', type=int, metavar='N', default=2, help='number of highway layers for character token embeddder') parser.add_argument('--adaptive-input', default=False, action='store_true', help='if set, uses adaptive input') parser.add_argument('--adaptive-input-factor', type=float, metavar='N', help='adaptive input factor') parser.add_argument('--adaptive-input-cutoff', metavar='EXPR', help='comma separated list of adaptive input cutoff points.') parser.add_argument('--tie-adaptive-weights', action='store_true', help='if set, ties the weights of adaptive softmax and adaptive input') parser.add_argument('--tie-adaptive-proj', action='store_true', help='if set, ties the projection weights of adaptive softmax and adaptive input') parser.add_argument('--decoder-learned-pos', action='store_true', help='use learned positional embeddings in the decoder') # fmt: on @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_lm_architecture(args) if hasattr(args, 'no_tie_adaptive_proj') and args.no_tie_adaptive_proj is False: # backward compatibility args.tie_adaptive_proj = True if not hasattr(args, 'max_source_positions'): args.max_source_positions = args.tokens_per_sample if not hasattr(args, 'max_target_positions'): args.max_target_positions = args.tokens_per_sample if args.character_embeddings: embed_tokens = CharacterTokenEmbedder( task.dictionary, eval(args.character_filters), args.character_embedding_dim, args.decoder_embed_dim, args.char_embedder_highway_layers, ) elif args.adaptive_input: embed_tokens = AdaptiveInput( len(task.dictionary), task.dictionary.pad(), args.decoder_input_dim, args.adaptive_input_factor, args.decoder_embed_dim, options.eval_str_list(args.adaptive_input_cutoff, type=int), ) else: embed_tokens = Embedding(len(task.dictionary), args.decoder_input_dim, task.dictionary.pad()) if args.tie_adaptive_weights: assert args.adaptive_input assert args.adaptive_input_factor == args.adaptive_softmax_factor assert args.adaptive_softmax_cutoff == args.adaptive_input_cutoff, '{} != {}'.format( args.adaptive_softmax_cutoff, args.adaptive_input_cutoff) assert args.decoder_input_dim == args.decoder_output_dim decoder = TransformerDecoder( args, task.output_dictionary, embed_tokens, no_encoder_attn=True, final_norm=False, ) return TransformerLanguageModel(decoder) class TransformerEncoder(FairseqEncoder): """ Transformer encoder consisting of *args.encoder_layers* layers. Each layer is a :class:`TransformerEncoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): encoding dictionary embed_tokens (torch.nn.Embedding): input embedding left_pad (bool, optional): whether the input is left-padded (default: True). """ def __init__(self, args, dictionary, embed_tokens, left_pad=True): super().__init__(dictionary) self.dropout = args.dropout embed_dim = embed_tokens.embedding_dim self.padding_idx = embed_tokens.padding_idx self.max_source_positions = args.max_source_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) self.embed_positions = PositionalEmbedding( args.max_source_positions, embed_dim, self.padding_idx, left_pad=left_pad, learned=args.encoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerEncoderLayer(args) for i in range(args.encoder_layers) ]) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.encoder_normalize_before if self.normalize: self.layer_norm = LayerNorm(embed_dim) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_scale * self.embed_tokens(src_tokens) if self.embed_positions is not None: x += self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # compute padding mask encoder_padding_mask = src_tokens.eq(self.padding_idx) if not encoder_padding_mask.any(): encoder_padding_mask = None # encoder layers for layer in self.layers: x = layer(x, encoder_padding_mask) if self.normalize: x = self.layer_norm(x) return { 'encoder_out': x, # T x B x C 'encoder_padding_mask': encoder_padding_mask, # B x T } def reorder_encoder_out(self, encoder_out, new_order): """ Reorder encoder output according to *new_order*. Args: encoder_out: output from the ``forward()`` method new_order (LongTensor): desired order Returns: *encoder_out* rearranged according to *new_order* """ if encoder_out['encoder_out'] is not None: encoder_out['encoder_out'] = \ encoder_out['encoder_out'].index_select(1, new_order) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(0, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" if self.embed_positions is None: return self.max_source_positions return min(self.max_source_positions, self.embed_positions.max_positions()) def upgrade_state_dict_named(self, state_dict, name): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): weights_key = '{}.embed_positions.weights'.format(name) if weights_key in state_dict: del state_dict[weights_key] state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1) version_key = '{}.version'.format(name) if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict[version_key] = torch.Tensor([1]) return state_dict class TransformerDecoder(FairseqIncrementalDecoder): """ Transformer decoder consisting of *args.decoder_layers* layers. Each layer is a :class:`TransformerDecoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): decoding dictionary embed_tokens (torch.nn.Embedding): output embedding no_encoder_attn (bool, optional): whether to attend to encoder outputs (default: False). left_pad (bool, optional): whether the input is left-padded (default: False). final_norm (bool, optional): apply layer norm to the output of the final decoder layer (default: True). """ def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, left_pad=False, final_norm=True): super().__init__(dictionary) self.dropout = args.dropout self.share_input_output_embed = args.share_decoder_input_output_embed input_embed_dim = embed_tokens.embedding_dim embed_dim = args.decoder_embed_dim output_embed_dim = args.decoder_output_dim padding_idx = embed_tokens.padding_idx self.max_target_positions = args.max_target_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim self.project_in_dim = Linear(input_embed_dim, embed_dim, bias=False) if embed_dim != input_embed_dim else None self.embed_positions = PositionalEmbedding( args.max_target_positions, embed_dim, padding_idx, left_pad=left_pad, learned=args.decoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerDecoderLayer(args, no_encoder_attn) for _ in range(args.decoder_layers) ]) self.adaptive_softmax = None self.project_out_dim = Linear(embed_dim, output_embed_dim, bias=False) \ if embed_dim != output_embed_dim and not args.tie_adaptive_weights else None if args.adaptive_softmax_cutoff is not None: self.adaptive_softmax = AdaptiveSoftmax( len(dictionary), output_embed_dim, options.eval_str_list(args.adaptive_softmax_cutoff, type=int), dropout=args.adaptive_softmax_dropout, adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None, factor=args.adaptive_softmax_factor, tie_proj=args.tie_adaptive_proj, ) elif not self.share_input_output_embed: self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), output_embed_dim)) nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim ** -0.5) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.decoder_normalize_before and final_norm if self.normalize: self.layer_norm = LayerNorm(embed_dim) def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ # embed positions positions = self.embed_positions( prev_output_tokens, incremental_state=incremental_state, ) if self.embed_positions is not None else None if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] if positions is not None: positions = positions[:, -1:] # embed tokens and positions x = self.embed_scale * self.embed_tokens(prev_output_tokens) if self.project_in_dim is not None: x = self.project_in_dim(x) if positions is not None: x += positions x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) attn = None inner_states = [x] # decoder layers for layer in self.layers: x, attn = layer( x, encoder_out['encoder_out'] if encoder_out is not None else None, encoder_out['encoder_padding_mask'] if encoder_out is not None else None, incremental_state, self_attn_mask=self.buffered_future_mask(x) if incremental_state is None else None, ) inner_states.append(x) if self.normalize: x = self.layer_norm(x) # T x B x C -> B x T x C x = x.transpose(0, 1) if self.project_out_dim is not None: x = self.project_out_dim(x) if self.adaptive_softmax is None: # project back to size of vocabulary if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = F.linear(x, self.embed_out) return x, {'attn': attn, 'inner_states': inner_states} def max_positions(self): """Maximum output length supported by the decoder.""" if self.embed_positions is None: return self.max_target_positions return min(self.max_target_positions, self.embed_positions.max_positions()) def buffered_future_mask(self, tensor): dim = tensor.size(0) if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device: self._future_mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1) if self._future_mask.size(0) < dim: self._future_mask = torch.triu(utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1) return self._future_mask[:dim, :dim] def upgrade_state_dict_named(self, state_dict, name): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): weights_key = '{}.embed_positions.weights'.format(name) if weights_key in state_dict: del state_dict[weights_key] state_dict['{}.embed_positions._float_tensor'.format(name)] = torch.FloatTensor(1) for i in range(len(self.layers)): # update layer norms layer_norm_map = { '0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm' } for old, new in layer_norm_map.items(): for m in ('weight', 'bias'): k = '{}.layers.{}.layer_norms.{}.{}'.format(name, i, old, m) if k in state_dict: state_dict['{}.layers.{}.{}.{}'.format(name, i, new, m)] = state_dict[k] del state_dict[k] if utils.item(state_dict.get('{}.version'.format(name), torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict['{}.version'.format(name)] = torch.Tensor([1]) return state_dict class TransformerEncoderLayer(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args): super().__init__() self.embed_dim = args.encoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.encoder_normalize_before self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim) self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(2)]) def forward(self, x, encoder_padding_mask): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ residual = x x = self.maybe_layer_norm(0, x, before=True) x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(0, x, after=True) residual = x x = self.maybe_layer_norm(1, x, before=True) x = F.relu(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(1, x, after=True) return x def maybe_layer_norm(self, i, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return self.layer_norms[i](x) else: return x class TransformerDecoderLayer(nn.Module): """Decoder layer block. In the original paper each operation (multi-head attention, encoder attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.decoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments no_encoder_attn (bool, optional): whether to attend to encoder outputs (default: False). """ def __init__(self, args, no_encoder_attn=False): super().__init__() self.embed_dim = args.decoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.decoder_normalize_before self.self_attn_layer_norm = LayerNorm(self.embed_dim) if no_encoder_attn: self.encoder_attn = None self.encoder_attn_layer_norm = None else: self.encoder_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.encoder_attn_layer_norm = LayerNorm(self.embed_dim) self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim) self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim) self.final_layer_norm = LayerNorm(self.embed_dim) self.need_attn = True self.onnx_trace = False def prepare_for_onnx_export_(self): self.onnx_trace = True def forward(self, x, encoder_out, encoder_padding_mask, incremental_state, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ residual = x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True) if prev_self_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_self_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.self_attn._set_input_buffer(incremental_state, saved_state) x, _ = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask, ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True) attn = None if self.encoder_attn is not None: residual = x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True) if prev_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.encoder_attn._set_input_buffer(incremental_state, saved_state) x, attn = self.encoder_attn( query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=(not self.training and self.need_attn), ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True) residual = x x = self.maybe_layer_norm(self.final_layer_norm, x, before=True) x = F.relu(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.final_layer_norm, x, after=True) if self.onnx_trace: saved_state = self.self_attn._get_input_buffer(incremental_state) self_attn_state = saved_state["prev_key"], saved_state["prev_value"] return x, attn, self_attn_state return x, attn def maybe_layer_norm(self, layer_norm, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return layer_norm(x) else: return x def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) return m def LayerNorm(embedding_dim): m = nn.LayerNorm(embedding_dim) return m def Linear(in_features, out_features, bias=True): m = nn.Linear(in_features, out_features, bias) nn.init.xavier_uniform_(m.weight) if bias: nn.init.constant_(m.bias, 0.) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False): if learned: m = LearnedPositionalEmbedding(num_embeddings + padding_idx + 1, embedding_dim, padding_idx, left_pad) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) else: m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings + padding_idx + 1) return m @register_model_architecture('transformer_lm', 'transformer_lm') def base_lm_architecture(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.adaptive_softmax_factor = getattr(args, 'adaptive_softmax_factor', 4) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.character_embeddings = getattr(args, 'character_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) # The model training is not stable without this args.decoder_normalize_before = True args.adaptive_input = getattr(args, 'adaptive_input', False) args.adaptive_input_factor = getattr(args, 'adaptive_input_factor', 4) args.adaptive_input_cutoff = getattr(args, 'adaptive_input_cutoff', None) args.tie_adaptive_weights = getattr(args, 'tie_adaptive_weights', False) args.tie_adaptive_proj = getattr(args, 'tie_adaptive_proj', False) @register_model_architecture('transformer_lm', 'transformer_lm_big') def transformer_lm_big(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) base_lm_architecture(args) @register_model_architecture('transformer_lm', 'transformer_lm_wiki103') def transformer_lm_wiki103(args): args.dropout = getattr(args, 'dropout', 0.3) transformer_lm_big(args) @register_model_architecture('transformer_lm', 'transformer_lm_gbw') def transformer_lm_gbw(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_lm_big(args) @register_model_architecture('transformer', 'transformer') def base_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) @register_model_architecture('transformer', 'transformer_iwslt_de_en') def transformer_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 4) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 1024) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 4) args.decoder_layers = getattr(args, 'decoder_layers', 6) base_architecture(args) @register_model_architecture('transformer', 'transformer_wmt_en_de') def transformer_wmt_en_de(args): base_architecture(args) # parameters used in the "Attention Is All You Need" paper (Vaswani, et al, 2017) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_de_big') def transformer_vaswani_wmt_en_de_big(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.dropout = getattr(args, 'dropout', 0.3) base_architecture(args) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_fr_big') def transformer_vaswani_wmt_en_fr_big(args): args.dropout = getattr(args, 'dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_big') def transformer_wmt_en_de_big(args): args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) # default parameters used in tensor2tensor implementation @register_model_architecture('transformer', 'transformer_wmt_en_de_big_t2t') def transformer_wmt_en_de_big_t2t(args): args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args)
45.578091
119
0.652119
795a60557f5c77b0aca1473e3227ea51e6f2961e
1,154
py
Python
stor/consensus/coinbase.py
Stor-Network/stor-blockchain
3c3cd1a3b99592e88160107ca5b81afc0937b992
[ "Apache-2.0" ]
19
2021-06-29T20:06:09.000Z
2022-02-09T04:33:00.000Z
stor/consensus/coinbase.py
Stor-Network/stor-blockchain
3c3cd1a3b99592e88160107ca5b81afc0937b992
[ "Apache-2.0" ]
8
2021-07-04T03:21:51.000Z
2021-12-27T07:56:09.000Z
stor/consensus/coinbase.py
Stor-Network/stor-blockchain
3c3cd1a3b99592e88160107ca5b81afc0937b992
[ "Apache-2.0" ]
6
2021-10-04T17:15:30.000Z
2022-03-15T08:40:01.000Z
from blspy import G1Element from stor.types.blockchain_format.coin import Coin from stor.types.blockchain_format.sized_bytes import bytes32 from stor.util.ints import uint32, uint64 from stor.wallet.puzzles.p2_delegated_puzzle_or_hidden_puzzle import puzzle_for_pk def create_puzzlehash_for_pk(pub_key: G1Element) -> bytes32: return puzzle_for_pk(pub_key).get_tree_hash() def pool_parent_id(block_height: uint32, genesis_challenge: bytes32) -> bytes32: return bytes32(genesis_challenge[:16] + block_height.to_bytes(16, "big")) def farmer_parent_id(block_height: uint32, genesis_challenge: bytes32) -> uint32: return bytes32(genesis_challenge[16:] + block_height.to_bytes(16, "big")) def create_pool_coin(block_height: uint32, puzzle_hash: bytes32, reward: uint64, genesis_challenge: bytes32): parent_id = pool_parent_id(block_height, genesis_challenge) return Coin(parent_id, puzzle_hash, reward) def create_farmer_coin(block_height: uint32, puzzle_hash: bytes32, reward: uint64, genesis_challenge: bytes32): parent_id = farmer_parent_id(block_height, genesis_challenge) return Coin(parent_id, puzzle_hash, reward)
39.793103
111
0.805893
795a606a3905f97e2ba80e23b414c121eb65ebfd
11,391
py
Python
main.py
nymann/BlackBoard-Course-Downloader
36bfee64ef87ac7d372596e7c69ae155068fad4a
[ "MIT" ]
1
2020-03-24T09:06:16.000Z
2020-03-24T09:06:16.000Z
main.py
nymann/BlackBoard-Course-Downloader
36bfee64ef87ac7d372596e7c69ae155068fad4a
[ "MIT" ]
null
null
null
main.py
nymann/BlackBoard-Course-Downloader
36bfee64ef87ac7d372596e7c69ae155068fad4a
[ "MIT" ]
null
null
null
from blackboard import BlackBoardContent, BlackBoardClient, BlackBoardAttachment, BlackBoardEndPoints, \ BlackBoardCourse, BlackBoardInstitute import argparse import sys import json import os import getpass def get_arguments(): parser = argparse.ArgumentParser(description='') parser.add_argument( "-v", "--version", help="Displays Application Version", action="store_true") parser.add_argument( "-g", "--gui", help="Use GUI instead of CLI", action="store_true") parser.add_argument("-m", "--mass-download", help="Download All Course Documents", action="store_true") parser.add_argument("-u", "--username", help="Username to Login With") parser.add_argument("-p", "--password", help="Password to Login With") parser.add_argument( "-s", "--site", help="Base Website Where Institute Black Board is Located") parser.add_argument("-l", "--location", help="Local Path To Save Content", default='.') parser.add_argument("-c", "--course", help="Course ID to Download") parser.add_argument("-r", "--record", help="Create A Manifest For Downloaded Data", action="store_true", default=True) parser.add_argument( "-V", "--verbose", help="Print Program Runtime Information", action="store_true") parser.add_argument( "-C", "--config", help="Location of Configuration File", default='./config.json') parser.add_argument("-i", "--ignore-input", help="Ignore Input at Runtime", action="store_true") return parser.parse_args() def handle_arguments(debug=False): args = get_arguments() os.chdir(os.path.dirname(os.path.abspath(__file__))) if args.version: print("Application Version: v{}".format("1.0.0")) sys.exit(0) config_content = {} if os.path.isfile(args.config): try: with open(args.config) as json_file: config_content = json.load(json_file) except IOError: print("Unable to Read File at Location: {}".format(args.config)) except json.JSONDecodeError: print("Unable to Parse Configuration File: {}".format(args.config)) # Command Line Arg -> Config File -> Input if args.username is None: possible_username = config_content.get('username', '') if not args.ignore_input: args.username = input( "Enter Username [{}]: ".format(possible_username)) if not args.username or not args.username.strip(): if possible_username: args.username = possible_username else: print("No Username Supplied!") sys.exit(0) if args.password is None: possible_password = config_content.get('password', '') if not args.ignore_input: args.password = getpass.getpass("Enter Password{}: " .format(" [Config Password]" if possible_password else "")) if not args.password or not args.password.strip(): if possible_password: args.password = possible_password else: print("No Password Supplied!") sys.exit(0) if args.site is None: possible_site = config_content.get('site', '') if not args.ignore_input: args.site = input( "Enter Black Board Host Website [{} or 'c' to Search]: ".format(possible_site)) if ((not args.site or not args.site.strip()) and not possible_site and not args.ignore_input) or \ args.site == 'c': args.site = navigation(options=BlackBoardInstitute.find(input("Institute Name: ")), attribute='name', sort=True).display_lms_host if args.site is None: print("No Site Supplied!") sys.exit(0) else: args.site = possible_site if debug: args.institute = BlackBoardInstitute.find(args.site)[0] if args.record: pass # if args.dump: # pass args.additional_courses = config_content.get("additionalCourses", []) # Run Actual Program if args.gui: # Insert GUI Function Here print("No GUI Currently Implemented") sys.exit(0) else: if debug: return args return main(args) ARGS = object() def main(args): global ARGS ARGS = args bbc = BlackBoardClient(username=args.username, password=args.password, site=args.site) if bbc.login(): if not bbc.use_rest_api: input("Your Blackboard Learn Service Doesnt Support the use of the rest API.\nXML request development is " "currently being worked on and should be available soon") sys.exit(0) save_config(args) if args.mass_download: courses = bbc.courses() # get all Courses for course in ARGS.additional_courses: courses.appened(BlackBoardCourse(bbc, course)) for course in courses: if args.course is None or course.id == args.course: # Download only Specified Course course.download_all_attachments(ARGS.location) else: navigate(bbc) else: if input("Failed to Login [Enter 'r' to Retry]") == 'r': main(args) return def navigate(selected_item, path: list = None, error_message=''): # Selecting New Item Based On Current Item global ARGS clear_console() if selected_item is None: raise Exception("Unknown Error") next_item = None if path is None: path = [] current_path(path, str(selected_item)) print("{}\n{}".format('/'.join(path), "Error: " + error_message + "\n" if error_message else "")) error_message = '' item_class_name = type(selected_item).__name__ if item_class_name == "BlackBoardClient": courses = selected_item.courses() for course in ARGS.additional_courses: courses.append(BlackBoardCourse(selected_item, course)) # Going Forwards next_item = navigation( options=courses, attribute='name', sort=True, title='Course') # Going Backwards if next_item is None: sys.exit(0) elif item_class_name == "BlackBoardCourse": # Sub Selection -> New Item options = ["Get Content", "Download All Content"] sub_selection = navigation(options=options, title="Option") # Going Forwards if sub_selection is not None: selected_index = options.index(sub_selection) if selected_index == 0: # Content next_item = navigation(options=selected_item.contents(), attribute='title', sort=True, title='Content') elif selected_index == 1: # Download selected_item.download_all_attachments( ARGS.location) # Returns None else: # Go Back (Not Required) next_item = None # Going Backwards if next_item is None: current_path(path) next_item = selected_item.client elif item_class_name == "BlackBoardContent": # Get Child Content or Attachments options = ["Get Child Content", "Get Attachments"] sub_selection = navigation(options=options, title="Option") # Going Forward if sub_selection is not None: selected_index = options.index(sub_selection) if selected_index == 0: # Child Content next_item = navigation(options=selected_item.children(), attribute='title', sort=True, title='Child') elif selected_index == 1: # Attachments next_item = navigation(options=selected_item.attachments(), attribute='file_name', sort=True, title='Attachment') else: next_item = None if next_item is None: next_item = selected_item current_path(path, '', -1) error_message = "No Content" # Going Backwards if next_item is None: current_path(path) # Has No Parent Content (Return Course) if selected_item.parent_id is None: next_item = selected_item.course else: # Has Parent Content (Return Content) parent_content = BlackBoardContent(selected_item.course, course_id=selected_item.course.id, content_id=selected_item.parent_id) next_item = parent_content elif item_class_name == "BlackBoardAttachment": options = ["Download", "Back"] sub_selection = navigation(options=options, title="Option") if sub_selection is not None: selected_index = options.index(sub_selection) if selected_index == 0: # Download selected_item.download(ARGS.location) # Always Go Back to Attachments Parent current_path(path) # Originally was navigate(selected_item.content) next_item = selected_item.content error_message = "Successfully Downloaded: {}".format( selected_item.file_name) if next_item is not None: # current_path(path) navigate(next_item, path, error_message) else: # Somehow not a specified Class raise Exception("Unknown Error") def navigation(**kwargs): # Handle kwargs options = kwargs.get('options', list()) attribute = kwargs.get('attribute', None) title = kwargs.get('title', '') input_text = kwargs.get('input', "Enter {} Number to Select ['c' to Exit]: ".format(title)) sort = kwargs.get('sort', False) if sort and attribute is not None: options = sorted( options, key=lambda element: getattr(element, attribute)) if not options: return None # No Options to Chose From while True: for i in range(len(options)): print("[{}] {}".format(i + 1, getattr(options[i], attribute) if attribute is not None else str(options[i]))) choice = input(input_text + "\n") if choice.isalpha(): return None # No Choice Made try: choice = int(choice) if choice > len(options) or choice <= 0: raise ValueError return options[choice - 1] except TypeError: print("Invalid Selection") except ValueError: print("Invalid Selection") def current_path(path: list = None, addition: str = '', step: int = -2): if addition: path.append(addition) else: del path[step:] def save_config(args): config = { 'username': args.username, # 'password': args.password, 'site': args.site, 'additionalCourses': args.additional_courses } with open(args.config, 'w') as save: json.dump(config, save) def clear_console(): os.system('cls' if os.name == 'nt' else 'clear') if __name__ == "__main__": handle_arguments()
37.470395
118
0.588359
795a60daa3fea4af0f505d9ce73f9436f32951c8
2,618
py
Python
tests/rules/test_git_push_pull.py
WorkInProgress-Development/theplease
9b9a2dcee3efa0e1b4f197fc55904c9327dc13ba
[ "MIT" ]
null
null
null
tests/rules/test_git_push_pull.py
WorkInProgress-Development/theplease
9b9a2dcee3efa0e1b4f197fc55904c9327dc13ba
[ "MIT" ]
null
null
null
tests/rules/test_git_push_pull.py
WorkInProgress-Development/theplease
9b9a2dcee3efa0e1b4f197fc55904c9327dc13ba
[ "MIT" ]
null
null
null
import pytest from theplease.rules.git_push_pull import match, get_new_command from theplease.types import Command git_err = ''' To /tmp/foo ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to '/tmp/bar' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ''' git_err2 = ''' To /tmp/foo ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to '/tmp/bar' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ''' git_uptodate = 'Everything up-to-date' git_ok = ''' Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 282 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To /tmp/bar 514eed3..f269c79 master -> master ''' @pytest.mark.parametrize('command', [ Command('git push', git_err), Command('git push nvbn', git_err), Command('git push nvbn master', git_err), Command('git push', git_err2), Command('git push nvbn', git_err2), Command('git push nvbn master', git_err2)]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git push', git_ok), Command('git push', git_uptodate), Command('git push nvbn', git_ok), Command('git push nvbn master', git_uptodate), Command('git push nvbn', git_ok), Command('git push nvbn master', git_uptodate)]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, output', [ (Command('git push', git_err), 'git pull && git push'), (Command('git push nvbn', git_err), 'git pull nvbn && git push nvbn'), (Command('git push nvbn master', git_err), 'git pull nvbn master && git push nvbn master'), (Command('git push', git_err2), 'git pull && git push'), (Command('git push nvbn', git_err2), 'git pull nvbn && git push nvbn'), (Command('git push nvbn master', git_err2), 'git pull nvbn master && git push nvbn master')]) def test_get_new_command(command, output): assert get_new_command(command) == output
35.378378
77
0.689076
795a60efe41d4cf2010b80549736f97b27549fe9
17,815
py
Python
xd_xd/aa/road_networks/wkt_to_graph.py
SpaceNetChallenge/SpaceNet_Optimized_Routing_Solutions
3fbc215de6b05904a5b54b2c7cde7e61074ae38d
[ "Apache-2.0" ]
27
2020-03-04T05:54:48.000Z
2022-01-05T07:07:44.000Z
xd_xd/aa/road_networks/wkt_to_graph.py
CosmiQ/SpaceNet_Optimized_Routing_Solutions
3fbc215de6b05904a5b54b2c7cde7e61074ae38d
[ "Apache-2.0" ]
1
2020-07-14T10:35:50.000Z
2020-07-14T10:35:50.000Z
xd_xd/aa/road_networks/wkt_to_graph.py
SpaceNetChallenge/SpaceNet_Optimized_Routing_Solutions
3fbc215de6b05904a5b54b2c7cde7e61074ae38d
[ "Apache-2.0" ]
7
2020-03-07T21:42:57.000Z
2022-01-07T10:49:50.000Z
import os import time import utm import numpy as np import networkx as nx import osmnx as ox import shapely from shapely.geometry import mapping, Point, LineString from osgeo import gdal, ogr, osr import matplotlib.pyplot as plt def wkt_to_graph(wkt_list, im_file, conf, out_graph_file): min_subgraph_length_pix = 300 verbose = False super_verbose = False make_plots = False save_shapefiles = False pickle_protocol = 4 if (len(wkt_list) == 0) or (wkt_list[0] == 'LINESTRING EMPTY'): return None try: G = wkt_to_G(wkt_list, im_file=im_file, min_subgraph_length_pix=min_subgraph_length_pix, verbose=super_verbose) if len(G.nodes()) == 0: return None except Exception as e: print('Exception in wkt_to_G: {}, {}'.format( str(e), out_graph_file)) return None node = list(G.nodes())[-1] if verbose: print(node, 'random node props:', G.nodes[node]) # print an edge edge_tmp = list(G.edges())[-1] if verbose: print (edge_tmp, "random edge props:", G.edges([edge_tmp[0], edge_tmp[1]])) #G.edge[edge_tmp[0]][edge_tmp[1]]) nx.write_gpickle(G, out_graph_file, protocol=pickle_protocol) # save shapefile as well? if save_shapefiles: ox.save_graph_shapefile(G, filename=image_id.split('.')[0] , folder=graph_dir, encoding='utf-8') # plot, if desired if make_plots: outfile_plot = 'debug_ox.png' if verbose: print ("Plotting graph...") print ("outfile_plot:", outfile_plot) ox.plot_graph(G, fig_height=9, fig_width=9, #save=True, filename=outfile_plot, margin=0.01) ) #plt.tight_layout() plt.savefig(outfile_plot, dpi=400) def wkt_to_G(wkt_list, im_file=None, min_subgraph_length_pix=30, simplify_graph=True, verbose=False): if verbose: print ("Running wkt_list_to_nodes_edges()...") node_loc_dic, edge_dic = wkt_list_to_nodes_edges(wkt_list) if verbose: print ("Creating G...") G0 = nodes_edges_to_G(node_loc_dic, edge_dic) if verbose: print (" len(G.nodes():", len(G0.nodes())) print (" len(G.edges():", len(G0.edges())) if verbose: print ("Clean out short subgraphs") G0 = clean_sub_graphs(G0, min_length=min_subgraph_length_pix, max_nodes_to_skip=30, weight='length_pix', verbose=False, super_verbose=False) if len(G0) == 0: return G0 # geo coords if im_file: if verbose: print ("Running get_node_geo_coords()...") G1 = get_node_geo_coords(G0, im_file, verbose=verbose) if verbose: print ("Running get_edge_geo_coords()...") G1 = get_edge_geo_coords(G1, im_file, verbose=verbose) if verbose: print ("projecting graph...") G_projected = ox.project_graph(G1) Gout = G_projected #G_simp else: Gout = G0 if simplify_graph: if verbose: print ("Simplifying graph") G0 = ox.simplify_graph(Gout.to_directed()) G0 = G0.to_undirected() Gout = ox.project_graph(G0) if verbose: print ("Merge 'geometry' linestrings...") keys_tmp = ['geometry_pix', 'geometry_latlon_wkt', 'geometry_utm_wkt'] for key_tmp in keys_tmp: if verbose: print ("Merge", key_tmp, "...") for i,(u,v,attr_dict) in enumerate(Gout.edges(data=True)): if (i % 10000) == 0: if verbose: print (i, u , v) geom = attr_dict[key_tmp] #print (i, u, v, "geom:", geom) #print (" type(geom):", type(geom)) if type(geom) == list: # check if the list items are wkt strings, if so, create # linestrigs if (type(geom[0]) == str):# or (type(geom_pix[0]) == unicode): geom = [shapely.wkt.loads(ztmp) for ztmp in geom] # merge geoms #geom = shapely.ops.linemerge(geom) #attr_dict[key_tmp] = geom attr_dict[key_tmp] = shapely.ops.linemerge(geom) elif type(geom) == str: attr_dict[key_tmp] = shapely.wkt.loads(geom) else: pass # assign 'geometry' tag to geometry_utm_wkt for i,(u,v,attr_dict) in enumerate(Gout.edges(data=True)): if verbose: print ("Create 'geometry' field in edges...") #geom_pix = attr_dict[key_tmp] line = attr_dict['geometry_utm_wkt'] if type(line) == str:# or type(line) == unicode: attr_dict['geometry'] = shapely.wkt.loads(line) else: attr_dict['geometry'] = attr_dict['geometry_utm_wkt'] # update wkt_pix? #print ("attr_dict['geometry_pix':", attr_dict['geometry_pix']) attr_dict['wkt_pix'] = attr_dict['geometry_pix'].wkt # update 'length_pix' attr_dict['length_pix'] = np.sum([attr_dict['length_pix']]) Gout = ox.project_graph(Gout) if verbose: # get a few stats (and set to graph properties) print("Number of nodes: {}".format(len(Gout.nodes()))) print("Number of edges: {}".format(len(Gout.edges()))) #print ("Number of nodes:", len(Gout.nodes())) #print ("Number of edges:", len(Gout.edges())) Gout.graph['N_nodes'] = len(Gout.nodes()) Gout.graph['N_edges'] = len(Gout.edges()) # get total length of edges tot_meters = 0 for i,(u,v,attr_dict) in enumerate(Gout.edges(data=True)): tot_meters += attr_dict['length'] if verbose: print ("Length of edges (km):", tot_meters/1000) Gout.graph['Tot_edge_km'] = tot_meters/1000 if verbose: print ("G.graph:", Gout.graph) return Gout def wkt_list_to_nodes_edges(wkt_list): '''Convert wkt list to nodes and edges Make an edge between each node in linestring. Since one linestring may contain multiple edges, this is the safest approach''' node_loc_set = set() # set of edge locations node_loc_dic = {} # key = node idx, val = location node_loc_dic_rev = {} # key = location, val = node idx edge_loc_set = set() # set of edge locations edge_dic = {} # edge properties node_iter = 0 edge_iter = 0 for i,lstring in enumerate(wkt_list): # get lstring properties shape = shapely.wkt.loads(lstring) xs, ys = shape.coords.xy length_orig = shape.length # iterate through coords in line to create edges between every point for j,(x,y) in enumerate(zip(xs, ys)): loc = (x,y) # for first item just make node, not edge if j == 0: # if not yet seen, create new node if loc not in node_loc_set: node_loc_set.add(loc) node_loc_dic[node_iter] = loc node_loc_dic_rev[loc] = node_iter node = node_iter node_iter += 1 # if not first node in edge, retrieve previous node and build edge else: prev_loc = (xs[j-1], ys[j-1]) #print ("prev_loc:", prev_loc) prev_node = node_loc_dic_rev[prev_loc] # if new, create new node if loc not in node_loc_set: node_loc_set.add(loc) node_loc_dic[node_iter] = loc node_loc_dic_rev[loc] = node_iter node = node_iter node_iter += 1 # if seen before, retrieve node properties else: node = node_loc_dic_rev[loc] # add edge, which is start_node to end_node edge_loc = (loc, prev_loc) edge_loc_rev = (prev_loc, loc) # shouldn't be duplicate edges, so break if we see one if (edge_loc in edge_loc_set) or (edge_loc_rev in edge_loc_set): print ("Oops, edge already seen, returning:", edge_loc) return # get distance to prev_loc and current loc proj_prev = shape.project(Point(prev_loc)) proj = shape.project(Point(loc)) # edge length is the diffence of the two projected lengths # along the linestring edge_length = abs(proj - proj_prev) # make linestring line_out = LineString([prev_loc, loc]) line_out_wkt = line_out.wkt edge_props = {'start': prev_node, 'start_loc_pix': prev_loc, 'end': node, 'end_loc_pix': loc, 'length_pix': edge_length, 'wkt_pix': line_out_wkt, 'geometry_pix': line_out, 'osmid': i} #print ("edge_props", edge_props) edge_loc_set.add(edge_loc) edge_dic[edge_iter] = edge_props edge_iter += 1 return node_loc_dic, edge_dic def nodes_edges_to_G(node_loc_dic, edge_dic, name='glurp'): '''Take output of wkt_list_to_nodes_edges(wkt_list) and create networkx graph''' G = nx.MultiDiGraph() # set graph crs and name G.graph = {'name': name, 'crs': {'init': 'epsg:4326'} } # add nodes #for key,val in node_loc_dic.iteritems(): for key in node_loc_dic.keys(): val = node_loc_dic[key] attr_dict = {'osmid': key, 'x_pix': val[0], 'y_pix': val[1]} G.add_node(key, **attr_dict) # add edges #for key,val in edge_dic.iteritems(): for key in edge_dic.keys(): val = edge_dic[key] attr_dict = val u = attr_dict['start'] v = attr_dict['end'] #attr_dict['osmid'] = str(i) #print ("nodes_edges_to_G:", u, v, "attr_dict:", attr_dict) if type(attr_dict['start_loc_pix']) == list: return G.add_edge(u, v, **attr_dict) ## always set edge key to zero? (for nx 1.X) ## THIS SEEMS NECESSARY FOR OSMNX SIMPLIFY COMMAND #G.add_edge(u, v, key=0, attr_dict=attr_dict) ##G.add_edge(u, v, key=key, attr_dict=attr_dict) #G1 = ox.simplify_graph(G) G2 = G.to_undirected() return G2 def clean_sub_graphs(G_, min_length=150, max_nodes_to_skip=30, weight='length_pix', verbose=True, super_verbose=False): '''Remove subgraphs with a max path length less than min_length, if the subgraph has more than max_noxes_to_skip, don't check length (this step great improves processing time)''' if len(list(G_.nodes())) == 0: return G_ if verbose: print ("Running clean_sub_graphs...") sub_graphs = list(nx.connected_component_subgraphs(G_)) bad_nodes = [] if verbose: print (" len(G_.nodes()):", len(list(G_.nodes())) ) print (" len(G_.edges()):", len(list(G_.edges())) ) if super_verbose: print ("G_.nodes:", G_.nodes()) edge_tmp = G_.edges()[np.random.randint(len(G_.edges()))] print (edge_tmp, "G.edge props:", G_.edge[edge_tmp[0]][edge_tmp[1]]) for G_sub in sub_graphs: # don't check length if too many nodes in subgraph if len(G_sub.nodes()) > max_nodes_to_skip: continue else: all_lengths = dict(nx.all_pairs_dijkstra_path_length(G_sub, weight=weight)) if super_verbose: print (" \nGs.nodes:", G_sub.nodes() ) print (" all_lengths:", all_lengths ) # get all lenghts lens = [] #for u,v in all_lengths.iteritems(): for u in all_lengths.keys(): v = all_lengths[u] #for uprime, vprime in v.iteritems(): for uprime in v.keys(): vprime = v[uprime] lens.append(vprime) if super_verbose: print (" u, v", u,v ) print (" uprime, vprime:", uprime, vprime ) max_len = np.max(lens) if super_verbose: print (" Max length of path:", max_len) if max_len < min_length: bad_nodes.extend(G_sub.nodes()) if super_verbose: print (" appending to bad_nodes:", G_sub.nodes()) # remove bad_nodes G_.remove_nodes_from(bad_nodes) if verbose: print (" num bad_nodes:", len(bad_nodes)) #print ("bad_nodes:", bad_nodes) print (" len(G'.nodes()):", len(G_.nodes())) print (" len(G'.edges()):", len(G_.edges())) if super_verbose: print (" G_.nodes:", G_.nodes()) return G_ def pixelToGeoCoord(xPix, yPix, inputRaster, sourceSR='', geomTransform='', targetSR=''): '''from spacenet geotools''' # If you want to garuntee lon lat output, specify TargetSR otherwise, geocoords will be in image geo reference # targetSR = osr.SpatialReference() # targetSR.ImportFromEPSG(4326) # Transform can be performed at the polygon level instead of pixel level if targetSR =='': performReprojection=False targetSR = osr.SpatialReference() targetSR.ImportFromEPSG(4326) else: performReprojection=True if geomTransform=='': srcRaster = gdal.Open(inputRaster) geomTransform = srcRaster.GetGeoTransform() source_sr = osr.SpatialReference() source_sr.ImportFromWkt(srcRaster.GetProjectionRef()) geom = ogr.Geometry(ogr.wkbPoint) xOrigin = geomTransform[0] yOrigin = geomTransform[3] pixelWidth = geomTransform[1] pixelHeight = geomTransform[5] xCoord = (xPix * pixelWidth) + xOrigin yCoord = (yPix * pixelHeight) + yOrigin geom.AddPoint(xCoord, yCoord) if performReprojection: if sourceSR=='': srcRaster = gdal.Open(inputRaster) sourceSR = osr.SpatialReference() sourceSR.ImportFromWkt(srcRaster.GetProjectionRef()) coord_trans = osr.CoordinateTransformation(sourceSR, targetSR) geom.Transform(coord_trans) return (geom.GetX(), geom.GetY()) def get_node_geo_coords(G, im_file, verbose=False): nn = len(G.nodes()) for i,(n,attr_dict) in enumerate(G.nodes(data=True)): if verbose: print ("node:", n) if (i % 1000) == 0: if verbose: print ("node", i, "/", nn) x_pix, y_pix = attr_dict['x_pix'], attr_dict['y_pix'] lon, lat = pixelToGeoCoord(x_pix, y_pix, im_file) [utm_east, utm_north, utm_zone, utm_letter] =\ utm.from_latlon(lat, lon) attr_dict['lon'] = lon attr_dict['lat'] = lat attr_dict['utm_east'] = utm_east attr_dict['utm_zone'] = utm_zone attr_dict['utm_letter'] = utm_letter attr_dict['utm_north'] = utm_north attr_dict['x'] = lon attr_dict['y'] = lat if verbose: print (" ", n, attr_dict) return G def convert_pix_lstring_to_geo(wkt_lstring, im_file): '''Convert linestring in pixel coords to geo coords''' shape = wkt_lstring #shapely.wkt.loads(lstring) x_pixs, y_pixs = shape.coords.xy coords_latlon = [] coords_utm = [] for (x,y) in zip (x_pixs, y_pixs): lon, lat = pixelToGeoCoord(x, y, im_file) [utm_east, utm_north, utm_zone, utm_letter] = utm.from_latlon(lat, lon) coords_utm.append([utm_east, utm_north]) coords_latlon.append([lon, lat]) lstring_latlon = LineString([Point(z) for z in coords_latlon]) lstring_utm = LineString([Point(z) for z in coords_utm]) return lstring_latlon, lstring_utm, utm_zone, utm_letter def get_edge_geo_coords(G, im_file, remove_pix_geom=True, verbose=False): ne = len(list(G.edges())) for i,(u,v,attr_dict) in enumerate(G.edges(data=True)): if verbose: print ("edge:", u,v) if (i % 1000) == 0: if verbose: print ("edge", i, "/", ne) geom_pix = attr_dict['geometry_pix'] lstring_latlon, lstring_utm, utm_zone, utm_letter = convert_pix_lstring_to_geo(geom_pix, im_file) attr_dict['geometry_latlon_wkt'] = lstring_latlon.wkt attr_dict['geometry_utm_wkt'] = lstring_utm.wkt attr_dict['length_latlon'] = lstring_latlon.length attr_dict['length_utm'] = lstring_utm.length attr_dict['length'] = lstring_utm.length attr_dict['utm_zone'] = utm_zone attr_dict['utm_letter'] = utm_letter if verbose: print (" attr_dict:", attr_dict) # geometry screws up osmnx.simplify function if remove_pix_geom: #attr_dict['geometry_wkt'] = lstring_latlon.wkt attr_dict['geometry_pix'] = geom_pix.wkt return G
35.347222
118
0.554701
795a616bdc92785f8c1d4a43d6bbaf9980eeffe8
13,368
py
Python
solo/client.py
ddrown/solo-python
34ab83d1bcdcbcecb49bdfe4d408fe2ea8be1399
[ "Apache-2.0", "MIT" ]
1
2020-03-05T21:29:38.000Z
2020-03-05T21:29:38.000Z
solo/client.py
ddrown/solo-python
34ab83d1bcdcbcecb49bdfe4d408fe2ea8be1399
[ "Apache-2.0", "MIT" ]
null
null
null
solo/client.py
ddrown/solo-python
34ab83d1bcdcbcecb49bdfe4d408fe2ea8be1399
[ "Apache-2.0", "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2019 SoloKeys Developers # # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distributed except according to those terms. import base64 import json import struct import sys import tempfile import time from cryptography import x509 from cryptography.hazmat.backends import default_backend from fido2.attestation import Attestation from fido2.client import Fido2Client from fido2.ctap import CtapError from fido2.ctap1 import CTAP1 from fido2.ctap2 import CTAP2 from fido2.hid import CTAPHID, CtapHidDevice from fido2.webauthn import PublicKeyCredentialCreationOptions from intelhex import IntelHex import solo.exceptions from solo import helpers from solo.commands import SoloBootloader, SoloExtension def find(solo_serial=None, retries=5, raw_device=None, udp=False): if udp: solo.fido2.force_udp_backend() # TODO: change `p` (for programmer) throughout p = SoloClient() # This... is not the right way to do it yet p.use_u2f() for i in range(retries): try: p.find_device(dev=raw_device, solo_serial=solo_serial) return p except RuntimeError: time.sleep(0.2) # return None raise solo.exceptions.NoSoloFoundError("no Solo found") def find_all(): hid_devices = list(CtapHidDevice.list_devices()) solo_devices = [ d for d in hid_devices if all( ( d.descriptor["vendor_id"] == 1155, d.descriptor["product_id"] == 41674, # "Solo" in d.descriptor["product_string"], ) ) ] return [find(raw_device=device) for device in solo_devices] class SoloClient: def __init__(self,): self.origin = "https://example.org" self.host = "example.org" self.user_id = b"they" self.exchange = self.exchange_hid self.do_reboot = True def use_u2f(self,): self.exchange = self.exchange_u2f def use_hid(self,): self.exchange = self.exchange_hid def set_reboot(self, val): """ option to reboot after programming """ self.do_reboot = val def reboot(self,): """ option to reboot after programming """ try: self.exchange(SoloBootloader.reboot) except OSError: pass def find_device(self, dev=None, solo_serial=None): if dev is None: devices = list(CtapHidDevice.list_devices()) if solo_serial is not None: devices = [ d for d in devices if d.descriptor["serial_number"] == solo_serial ] if len(devices) > 1: raise solo.exceptions.NonUniqueDeviceError if len(devices) == 0: raise RuntimeError("No FIDO device found") dev = devices[0] self.dev = dev self.ctap1 = CTAP1(dev) self.ctap2 = CTAP2(dev) try: self.client = Fido2Client(dev, self.origin) except CtapError: print("Not using FIDO2 interface.") self.client = None if self.exchange == self.exchange_hid: self.send_data_hid(CTAPHID.INIT, "\x11\x11\x11\x11\x11\x11\x11\x11") return self.dev @staticmethod def format_request(cmd, addr=0, data=b"A" * 16): # not sure why this is here? # arr = b"\x00" * 9 addr = struct.pack("<L", addr) cmd = struct.pack("B", cmd) length = struct.pack(">H", len(data)) return cmd + addr[:3] + SoloBootloader.TAG + length + data def send_only_hid(self, cmd, data): if not isinstance(data, bytes): data = struct.pack("%dB" % len(data), *[ord(x) for x in data]) self.dev._dev.InternalSend(0x80 | cmd, bytearray(data)) def send_data_hid(self, cmd, data): if not isinstance(data, bytes): data = struct.pack("%dB" % len(data), *[ord(x) for x in data]) with helpers.Timeout(1.0) as event: return self.dev.call(cmd, data, event) def exchange_hid(self, cmd, addr=0, data=b"A" * 16): req = SoloClient.format_request(cmd, addr, data) data = self.send_data_hid(SoloBootloader.HIDCommandBoot, req) ret = data[0] if ret != CtapError.ERR.SUCCESS: raise CtapError(ret) return data[1:] def exchange_u2f(self, cmd, addr=0, data=b"A" * 16): appid = b"A" * 32 chal = b"B" * 32 req = SoloClient.format_request(cmd, addr, data) res = self.ctap1.authenticate(chal, appid, req) ret = res.signature[0] if ret != CtapError.ERR.SUCCESS: raise CtapError(ret) return res.signature[1:] def exchange_fido2(self, cmd, addr=0, data=b"A" * 16): chal = b"B" * 32 req = SoloClient.format_request(cmd, addr, data) assertion = self.ctap2.get_assertion( self.host, chal, [{"id": req, "type": "public-key"}] ) res = assertion ret = res.signature[0] if ret != CtapError.ERR.SUCCESS: raise RuntimeError("Device returned non-success code %02x" % (ret,)) return res.signature[1:] def bootloader_version(self,): data = self.exchange(SoloBootloader.version) if len(data) > 2: return (data[0], data[1], data[2]) return (0, 0, data[0]) def solo_version(self,): try: return self.send_data_hid(0x61, b"") except CtapError: data = self.exchange(SoloExtension.version) return (data[0], data[1], data[2]) def write_flash(self, addr, data): self.exchange(SoloBootloader.write, addr, data) def get_rng(self, num=0): ret = self.send_data_hid(SoloBootloader.HIDCommandRNG, struct.pack("B", num)) return ret def verify_flash(self, sig): """ Tells device to check signature against application. If it passes, the application will boot. Exception raises if signature fails. """ self.exchange(SoloBootloader.done, 0, sig) def wink(self,): self.send_data_hid(CTAPHID.WINK, b"") def ping(self,data="pong"): return self.send_data_hid(CTAPHID.PING, data) def reset(self,): self.ctap2.reset() def change_pin(self, old_pin, new_pin): self.client.pin_protocol.change_pin(old_pin, new_pin) def set_pin(self, new_pin): self.client.pin_protocol.set_pin(new_pin) def make_credential(self, pin=None): rp = {"id": self.host, "name": "example site"} user = {"id": self.user_id, "name": "example user"} challenge = b"Y2hhbGxlbmdl" options = PublicKeyCredentialCreationOptions( rp, user, challenge, [{"type": "public-key", "alg": -8}, {"type": "public-key", "alg": -7}], ) attest, data = self.client.make_credential(options, pin=pin) try: attest.verify(data.hash) except AttributeError: verifier = Attestation.for_type(attest.fmt) verifier().verify(attest.att_statement, attest.auth_data, data.hash) print("Register valid") x5c = attest.att_statement["x5c"][0] cert = x509.load_der_x509_certificate(x5c, default_backend()) return cert def enter_solo_bootloader(self,): """ If solo is configured as solo hacker or something similar, this command will tell the token to boot directly to the bootloader so it can be reprogrammed """ if self.exchange != self.exchange_hid: self.send_data_hid(CTAPHID.INIT, "\x11\x11\x11\x11\x11\x11\x11\x11") self.send_data_hid(SoloBootloader.HIDCommandEnterBoot, "") def enter_bootloader_or_die(self): try: self.enter_solo_bootloader() # except OSError: # pass except CtapError as e: if e.code == CtapError.ERR.INVALID_COMMAND: print( "Could not switch into bootloader mode. Please hold down the button for 2s while you plug token in." ) sys.exit(1) else: raise (e) def is_solo_bootloader(self,): try: self.bootloader_version() return True except CtapError as e: if e.code == CtapError.ERR.INVALID_COMMAND: pass else: raise (e) return False def enter_st_dfu(self,): """ If solo is configured as solo hacker or something similar, this command will tell the token to boot directly to the st DFU so it can be reprogrammed. Warning, you could brick your device. """ soloboot = self.is_solo_bootloader() if soloboot or self.exchange == self.exchange_u2f: req = SoloClient.format_request(SoloBootloader.st_dfu) self.send_only_hid(SoloBootloader.HIDCommandBoot, req) else: self.send_only_hid(SoloBootloader.HIDCommandEnterSTBoot, "") def disable_solo_bootloader(self,): """ Disables the Solo bootloader. Only do this if you want to void the possibility of any updates. If you've started from a solo hacker, make you you've programmed a final/production build! """ ret = self.exchange( SoloBootloader.disable, 0, b"\xcd\xde\xba\xaa" ) # magic number if ret[0] != CtapError.ERR.SUCCESS: print("Failed to disable bootloader") return False time.sleep(0.1) self.exchange(SoloBootloader.do_reboot) return True def program_file(self, name): def parseField(f): return base64.b64decode(helpers.from_websafe(f).encode()) def isCorrectVersion(current, target): """ current is tuple (x,y,z). target is string '>=x.y.z'. Return True if current satisfies the target expression. """ if "=" in target: target = target.split("=") assert target[0] in [">", "<"] target_num = [int(x) for x in target[1].split(".")] assert len(target_num) == 3 comp = target[0] + "=" else: assert target[0] in [">", "<"] target_num = [int(x) for x in target[1:].split(".")] comp = target[0] target_num = ( (target_num[0] << 16) | (target_num[1] << 8) | (target_num[2] << 0) ) current_num = (current[0] << 16) | (current[1] << 8) | (current[2] << 0) return eval(str(current_num) + comp + str(target_num)) if name.lower().endswith(".json"): data = json.loads(open(name, "r").read()) fw = parseField(data["firmware"]) sig = None if "versions" in data: current = (0, 0, 0) try: current = self.bootloader_version() except CtapError as e: if e.code == CtapError.ERR.INVALID_COMMAND: pass else: raise (e) for v in data["versions"]: if isCorrectVersion(current, v): print("using signature version", v) sig = parseField(data["versions"][v]["signature"]) break if sig is None: raise RuntimeError( "Improperly formatted firmware file. Could not match version." ) else: sig = parseField(data["signature"]) ih = IntelHex() tmp = tempfile.NamedTemporaryFile(delete=False) tmp.write(fw) tmp.seek(0) tmp.close() ih.fromfile(tmp.name, format="hex") else: if not name.lower().endswith(".hex"): print('Warning, assuming "%s" is an Intel Hex file.' % name) sig = None ih = IntelHex() ih.fromfile(name, format="hex") if self.exchange == self.exchange_hid: chunk = 2048 else: chunk = 240 seg = ih.segments()[0] size = seg[1] - seg[0] total = 0 t1 = time.time() * 1000 print("erasing firmware...") for i in range(seg[0], seg[1], chunk): s = i e = min(i + chunk, seg[1]) data = ih.tobinarray(start=i, size=e - s) self.write_flash(i, data) total += chunk progress = total / float(size) * 100 sys.stdout.write("updating firmware %.2f%%...\r" % progress) sys.stdout.write("updated firmware 100% \r\n") t2 = time.time() * 1000 print("time: %.2f s" % ((t2 - t1) / 1000.0)) if sig is None: sig = b"A" * 64 if self.do_reboot: self.verify_flash(sig) return sig
32.764706
121
0.562837
795a617759511ae2451a3e134ef368b9dd8e0cec
13,040
py
Python
v3/v3.0/moveloot_standalone.py
gavinIRL/RHBot
1e22ae5ca7b67ebd6a72c23d9f46d5a8eb6e99cf
[ "MIT" ]
null
null
null
v3/v3.0/moveloot_standalone.py
gavinIRL/RHBot
1e22ae5ca7b67ebd6a72c23d9f46d5a8eb6e99cf
[ "MIT" ]
60
2021-03-29T14:29:49.000Z
2021-05-03T06:06:19.000Z
v3/v3.0/moveloot_standalone.py
gavinIRL/RHBot
1e22ae5ca7b67ebd6a72c23d9f46d5a8eb6e99cf
[ "MIT" ]
null
null
null
# This will be the upgraded v2 move and loot only file # But with quick restart capability and modular design # No longer meant to be used as main file import cv2 as cv import os from time import time, sleep import numpy as np from pynput.keyboard import Key, Listener, KeyCode from windowcapture import WindowCapture from vision import Vision from hsvfilter import grab_object_preset from actionsv2 import Movement_Handler, Actions class StandaloneMoveLoot(): def __init__(self, controller, loot_cd_max=5) -> None: self.controller = controller # This is the variable which prevents getting stuck picking loot self.pressx_counter = 0 # This is the variable which will track cooldown on searching for loot # After the bot has gotten stuck, format is seconds # The value assigned will correspond to time when lootsearch can recommence self.near_loot_cd = 0 # And the variable which determines the cooldown each time self.near_loot_cd_max = loot_cd_max # This will hold the relative location of the other player self.other_player_rel_coords = [0, 0] # This will hold the location of the current player self.current_player_coords = [0, 0] # The variable for ensuring momentum of player movement self.movement_frames = 0 self.momentum = 0 self.max_momentum = 2 self.momentum_accel = 10 # Variable for ensuring positive enemy detection self.enemy_detect_frames = 0 # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # XX Now time to initialise all of the required objects XX # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Initialise the movement object and pass the state object self.movement = Movement_Handler(test_mode=False) # Grab the gamename from the text file with open("gamename.txt") as f: gamename = f.readline() # The next block of code is setup for detecting the other player self.othr_plyr_filter, othr_plyr_custom_rect = grab_object_preset( object_name="other_player_map_loc") self.othr_plyr_wincap = WindowCapture( gamename, othr_plyr_custom_rect) self.othr_plyr_vision = Vision('otherplayer67.jpg') # The next block of code is setup for detecting the current player self.player_filter, player_custom_rect = grab_object_preset( object_name="player_map_loc") self.player_wincap = WindowCapture( gamename, player_custom_rect) self.player_vision = Vision('playerv2_67.jpg') # The next block of code is setup for detecting enemies on minimap self.enemy_filter, enemy_custom_rect = grab_object_preset( object_name="enemy_map_locv3") self.enemy_wincap = WindowCapture( gamename, enemy_custom_rect) self.enemy_vision = Vision('enemy67.jpg') # The next block of code is setup for detecting nearby loot self.lootnr_filter, lootnr_custom_rect = grab_object_preset( object_name="loot_near") self.lootnr_wincap = WindowCapture( gamename, lootnr_custom_rect) self.lootnr_vision = Vision('lootnear67filt.jpg') # The next block of code is setup for detecting if in a dungeon self.dunchk_filter, dunchk_custom_rect = grab_object_preset( object_name="dungeon_check") self.dunchk_wincap = WindowCapture( gamename, dunchk_custom_rect) self.dunchk_vision = Vision('dunchk_67.jpg') # The next block of code is setup for detecting if there is an x prompt self.xprompt_filter, xprompt_custom_rect = grab_object_preset( object_name="prompt_press_x_pickup") self.xprompt_wincap = WindowCapture( gamename, xprompt_custom_rect) self.xprompt_vision = Vision("xprompt67filtv2.jpg") # Start the movement bot self.movement.movement_start() def move_mainloop(self): loop_time = time() reset_time = time() + 5 while True: if self.check_if_in_dungeon(): if self.controller.combat_enabled: if self.perform_enemy_check(): self.controller.mode = "combat" break if self.controller.loot_enabled: self.check_for_loot() self.move_to_other_player() else: sleep(0.4) if (time() - reset_time) > 0: Actions.move_mouse_centre() Actions.stop_keypresses(self.movement) reset_time = time() + 5 # If loops are over 100fps, slow to 67fps if 100*(time() - loop_time) < 1: # Minimum sleep time is roughly 15ms regardless sleep(0.001) loop_time = time() # After end stop all movement self.movement.movement_stop() def check_if_in_dungeon(self): # get an updated image of the game at specified area dunchk_screenshot = self.dunchk_wincap.get_screenshot() # pre-process the image to help with detection dunchk_output_image = self.dunchk_vision.apply_hsv_filter( dunchk_screenshot, self.dunchk_filter) # do object detection, this time grab rectangles dunchk_rectangles = self.dunchk_vision.find( dunchk_output_image, threshold=0.31, epsilon=0.5) # then return answer to whether currently in dungeon if len(dunchk_rectangles) == 1: return True return False def perform_enemy_check(self): if self.check_for_enemies(): self.enemy_detect_frames += 1 if self.enemy_detect_frames >= 2: return True else: self.enemy_detect_frames = 0 return False def check_for_enemies(self): enemy_screenshot = self.enemy_wincap.get_screenshot() # pre-process the image to help with detection enemy_output_image = self.enemy_vision.apply_hsv_filter( enemy_screenshot, self.enemy_filter) # do object detection, this time grab points enemy_rectangles = self.enemy_vision.find( enemy_output_image, threshold=0.61, epsilon=0.5) # then return answer to whether enemies are detected if len(enemy_rectangles) >= 1: return True return False def check_for_loot(self): if not self.check_if_loot_cooldown(): if self.check_if_nearby_loot(): # Now need to check if there is a prompt if self.check_for_x_prompt(): # Need to stop all movement self.movement.movement_update_xy(0, 0) # Clear all button presses Actions.move_mouse_centre() Actions.stop_keypresses(self.movement) # Press x a couple times off the bat Actions.press_key_once("x") sleep(0.6) while self.check_for_x_prompt(): self.pressx_counter += 1 # Press the x button once Actions.press_key_once("x") sleep(0.6) if self.pressx_counter >= 8: self.near_loot_cd = time() + self.near_loot_cd_max break Actions.stop_keypresses(self.movement) self.pressx_counter = 0 def check_if_loot_cooldown(self): if not self.near_loot_cd == 0: if (self.near_loot_cd-time()) < 0: self.near_loot_cd = 0 return False return True def check_if_nearby_loot(self): # get an updated image of the game at specified area lootnr_screenshot = self.lootnr_wincap.get_screenshot() # pre-process the image to help with detection lootnr_output_image = self.lootnr_vision.apply_hsv_filter( lootnr_screenshot, self.lootnr_filter) # do object detection, this time grab rectangles lootnr_rectangles = self.lootnr_vision.find( lootnr_output_image, threshold=0.31, epsilon=0.5) # then return answer to whether currently in dungeon if len(lootnr_rectangles) >= 1: return True return False def check_for_x_prompt(self): # get an updated image of the game at specified area xprompt_screenshot = self.xprompt_wincap.get_screenshot() # pre-process the image to help with detection xprompt_output_image = self.xprompt_vision.apply_hsv_filter( xprompt_screenshot, self.xprompt_filter) # do object detection, this time grab rectangles xprompt_rectangles = self.xprompt_vision.find( xprompt_output_image, threshold=0.61, epsilon=0.5) # then return answer to whether currently in dungeon if len(xprompt_rectangles) == 1: return True return False # Having these be separate methods as main loop too bulky def can_find_both_players(self): # This will return true if both players could be found # Otherwise will set relative to 0,0 and return false if self.can_find_other_player(): if self.can_find_current_player(): return True # Need to use last known position otherwise return True return False def can_find_current_player(self): # Main logic for this method is below minimap_screenshot = self.player_wincap.get_screenshot() player_image = self.player_vision.apply_hsv_filter( minimap_screenshot, self.player_filter) player_rectangles = self.player_vision.find( player_image, threshold=0.41, epsilon=0.5) player_points = self.player_vision.get_click_points( player_rectangles) if len(player_points) == 1: self.current_player_coords[0] = player_points[0][0] self.current_player_coords[1] = player_points[0][1] return True else: # Should this be set to 0,0 or left as is? Come back to this later # Will leave as is for now, probably useful for enemy detect return False def can_find_other_player(self): # then try to detect the other player minimap_screenshot = self.othr_plyr_wincap.get_screenshot() output_image = self.othr_plyr_vision.apply_hsv_filter( minimap_screenshot, self.othr_plyr_filter) # do object detection, this time grab the points rectangles = self.othr_plyr_vision.find( output_image, threshold=0.41, epsilon=0.5) points = self.othr_plyr_vision.get_click_points(rectangles) if len(points) == 1: self.other_player_rel_coords[0] = points[0][0] - \ self.current_player_coords[0] self.other_player_rel_coords[1] = self.current_player_coords[1] - points[0][1] return True elif len(points) >= 2: # Will grab the point closest to the centre of the minimap and track that # Allowing some small amount of redundancy for short-range following # In event that the background is also picked up middle_x = 0 middle_y = 0 dist = 1000 for x, y in points: if (x+y) < dist: dist = x+y middle_x = x middle_y = y self.other_player_rel_coords[0] = middle_x - \ self.current_player_coords[0] self.other_player_rel_coords[1] = self.current_player_coords[1] - middle_y return True else: # Should this be set to 0,0 or left as is? Come back to this later # Maybe set it to the current player coords instead # self.other_player_rel_coords = [0, 0] return False def move_to_other_player(self): self.loot_movement_frames = 0 if self.can_find_both_players(): relx, rely = self.other_player_rel_coords self.movement.movement_update_xy(relx, rely) self.movement_frames += 1 if self.movement_frames % self.momentum_accel == 0: if not self.momentum >= self.max_momentum: self.momentum += 1 else: if self.momentum < 1: self.movement.movement_update_xy(0, 0) self.momentum = 0 # Have the consecutive move count only reset if momentum gone self.movement_frames = 0 else: self.momentum -= 1 # Only slightly remove the momentum progress self.movement_frames -= (int(self.momentum_accel/2))
43.178808
90
0.62477
795a61edcbb34a80b968f3913f92612d1361a3ed
4,993
py
Python
python/tvm/micro/build.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
4,640
2017-08-17T19:22:15.000Z
2019-11-04T15:29:46.000Z
python/tvm/micro/build.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
3,022
2020-11-24T14:02:31.000Z
2022-03-31T23:55:31.000Z
python/tvm/micro/build.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
1,352
2017-08-17T19:30:38.000Z
2019-11-04T16:09:29.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Defines top-level glue functions for building microTVM artifacts.""" import json import logging import os import pathlib import contextlib import enum from typing import Union from .._ffi import libinfo from .. import rpc as _rpc _LOG = logging.getLogger(__name__) STANDALONE_CRT_DIR = None class MicroTVMTemplateProject(enum.Enum): ZEPHYR = "zephyr" ARDUINO = "arduino" CRT = "crt" @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class CrtNotFoundError(Exception): """Raised when the standalone CRT dirtree cannot be found.""" class MicroTVMTemplateProjectNotFoundError(Exception): """Raised when the microTVM template project dirtree cannot be found.""" def get_standalone_crt_dir() -> str: """Find the standalone_crt directory. Though the C runtime source lives in the tvm tree, it is intended to be distributed with any binary build of TVM. This source tree is intended to be integrated into user projects to run models targeted with --runtime=c. Returns ------- str : The path to the standalone_crt """ global STANDALONE_CRT_DIR if STANDALONE_CRT_DIR is None: for path in libinfo.find_lib_path(): crt_path = os.path.join(os.path.dirname(path), "standalone_crt") if os.path.isdir(crt_path): STANDALONE_CRT_DIR = crt_path break else: raise CrtNotFoundError() return STANDALONE_CRT_DIR def get_microtvm_template_projects(platform: str) -> str: """Find microTVM template project directory for specific platform. Parameters ---------- platform : str Platform type which should be defined in MicroTVMTemplateProject. Returns ------- str : Path to template project directory for platform. """ if platform not in MicroTVMTemplateProject.list(): raise ValueError(f"platform {platform} is not supported.") if platform == MicroTVMTemplateProject.CRT.value: return os.path.join(get_standalone_crt_dir(), "template", "host") microtvm_template_projects = None for path in libinfo.find_lib_path(): template_path = os.path.join(os.path.dirname(path), "microtvm_template_projects") if os.path.isdir(template_path): microtvm_template_projects = template_path break else: raise MicroTVMTemplateProjectNotFoundError() return os.path.join(microtvm_template_projects, platform) class AutoTvmModuleLoader: """MicroTVM AutoTVM Module Loader Parameters ---------- template_project_dir : Union[pathlib.Path, str] project template path project_options : dict project generation option """ def __init__( self, template_project_dir: Union[pathlib.Path, str], project_options: dict = None ): self._project_options = project_options if isinstance(template_project_dir, (pathlib.Path, str)): self._template_project_dir = str(template_project_dir) elif not isinstance(template_project_dir, str): raise TypeError(f"Incorrect type {type(template_project_dir)}.") @contextlib.contextmanager def __call__(self, remote_kw, build_result): with open(build_result.filename, "rb") as build_file: build_result_bin = build_file.read() tracker = _rpc.connect_tracker(remote_kw["host"], remote_kw["port"]) remote = tracker.request( remote_kw["device_key"], priority=remote_kw["priority"], session_timeout=remote_kw["timeout"], session_constructor_args=[ "tvm.micro.compile_and_create_micro_session", build_result_bin, self._template_project_dir, json.dumps(self._project_options), ], ) system_lib = remote.get_function("runtime.SystemLib")() yield remote, system_lib def autotvm_build_func(): """A dummy build function which causes autotvm to use a different export format.""" # A sentinel value for the output format. autotvm_build_func.output_format = ".model-library-format"
30.820988
96
0.689966
795a6201ec41c913993971484313314b04d81c3c
2,608
py
Python
dialogue-engine/test/programytest/parser/template/node_tests/test_oob.py
cotobadesign/cotoba-agent-oss
3833d56e79dcd7529c3e8b3a3a8a782d513d9b12
[ "MIT" ]
104
2020-03-30T09:40:00.000Z
2022-03-06T22:34:25.000Z
dialogue-engine/test/programytest/parser/template/node_tests/test_oob.py
cotobadesign/cotoba-agent-oss
3833d56e79dcd7529c3e8b3a3a8a782d513d9b12
[ "MIT" ]
25
2020-06-12T01:36:35.000Z
2022-02-19T07:30:44.000Z
dialogue-engine/test/programytest/parser/template/node_tests/test_oob.py
cotobadesign/cotoba-agent-oss
3833d56e79dcd7529c3e8b3a3a8a782d513d9b12
[ "MIT" ]
10
2020-04-02T23:43:56.000Z
2021-05-14T13:47:01.000Z
""" Copyright (c) 2020 COTOBA DESIGN, Inc. 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 xml.etree.ElementTree as ET from programy.parser.template.nodes.base import TemplateNode from programy.parser.template.nodes.oob import TemplateOOBNode from programy.parser.template.nodes.word import TemplateWordNode from programytest.parser.base import ParserTestsBaseClass class MockTemplateOOBNode(TemplateOOBNode): def __init__(self): TemplateOOBNode.__init__(self) def resolve_to_string(self, context): raise Exception("This is an error") class TemplateOOBNodeTests(ParserTestsBaseClass): def test_node(self): root = TemplateNode() self.assertIsNotNone(root) oob = TemplateOOBNode() root.append(oob) oob.append(TemplateWordNode("hello")) self.assertEqual(len(root.children), 1) resolved = root.resolve(self._client_context) self.assertIsNotNone(resolved) self.assertEqual("<oob>hello</oob>", resolved) def test_to_xml(self): root = TemplateNode() node = TemplateOOBNode() root.append(node) node.append(TemplateWordNode("Test")) xml = root.xml_tree(self._client_context) self.assertIsNotNone(xml) xml_str = ET.tostring(xml, "utf-8").decode("utf-8") self.assertEqual("<template><oob>Test</oob></template>", xml_str) def test_node_exception_handling(self): root = TemplateNode() node = MockTemplateOOBNode() root.append(node) with self.assertRaises(Exception): root.resolve(self._client_context)
38.352941
126
0.733512
795a624eacf0c93b9fcb5e566be26540c54cb9e7
2,127
py
Python
src/pynwb/io/file.py
campagnola/pynwb
b3f1034909ac4462378e79d0e438dc5b803e5fbf
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/pynwb/io/file.py
campagnola/pynwb
b3f1034909ac4462378e79d0e438dc5b803e5fbf
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/pynwb/io/file.py
campagnola/pynwb
b3f1034909ac4462378e79d0e438dc5b803e5fbf
[ "BSD-3-Clause-LBNL" ]
null
null
null
from ..form.build import ObjectMapper from .. import register_map from ..file import NWBFile @register_map(NWBFile) class NWBFileMap(ObjectMapper): def __init__(self, spec): super(NWBFileMap, self).__init__(spec) raw_ts_spec = self.spec.get_group('acquisition').get_neurodata_type('NWBDataInterface') self.map_spec('acquisition', raw_ts_spec) stimulus_spec = self.spec.get_group('stimulus') presentation_ts_spec = stimulus_spec.get_group('presentation')\ .get_neurodata_type('TimeSeries') self.map_spec('stimulus', presentation_ts_spec) stimulus_ts_spec = stimulus_spec.get_group('templates').get_neurodata_type('TimeSeries') self.map_spec('stimulus_template', stimulus_ts_spec) epochs_spec = self.spec.get_group('epochs') self.map_spec('epochs', epochs_spec) general_spec = self.spec.get_group('general') self.map_spec( 'ic_electrodes', general_spec.get_group('intracellular_ephys') .get_neurodata_type('IntracellularElectrode')) ecephys_spec = general_spec.get_group('extracellular_ephys') self.map_spec('ec_electrodes', ecephys_spec.get_dataset('electrodes')) self.map_spec('ec_electrode_groups', ecephys_spec.get_neurodata_type('ElectrodeGroup')) self.map_spec( 'optogenetic_sites', general_spec.get_group('optogenetics').get_neurodata_type('OptogeneticStimulusSite')) self.map_spec( 'imaging_planes', general_spec.get_group('optophysiology').get_neurodata_type('ImagingPlane')) self.map_spec( 'modules', self.spec.get_group('processing').get_neurodata_type('ProcessingModule')) self.unmap(general_spec.get_dataset('stimulus')) self.map_spec('subject', general_spec.get_group('subject')) self.map_spec('devices', general_spec.get_group('devices').get_neurodata_type('Device')) @ObjectMapper.constructor_arg('file_name') def name(self, builder, manager): return builder.name
42.54
97
0.684532
795a62c977241d0ee631d23f5101da28a02d41bf
1,207
py
Python
crds/python23.py
nden/crds
b72f14cf07531ca70b61daa6b58e762e5899afa4
[ "BSD-3-Clause" ]
null
null
null
crds/python23.py
nden/crds
b72f14cf07531ca70b61daa6b58e762e5899afa4
[ "BSD-3-Clause" ]
null
null
null
crds/python23.py
nden/crds
b72f14cf07531ca70b61daa6b58e762e5899afa4
[ "BSD-3-Clause" ]
null
null
null
import sys if sys.version_info >= (3,0,0): long = int string_types = (str,) from urllib.request import urlopen from html import unescape import configparser import pickle def unicode_to_str(input): """Recursively convert .json inputs with unicode to simple Python strings.""" return input else: long = long string_types = (basestring,) import HTMLParser as _parser_mod from urllib2 import urlopen unescape = _parser_mod.HTMLParser().unescape import ConfigParser as configparser import cPickle as pickle def unicode_to_str(input): """Recursively convert .json inputs with unicode to simple Python strings.""" if isinstance(input, dict): return {unicode_to_str(key): unicode_to_str(value) for key, value in input.iteritems()} elif isinstance(input, (list, tuple)): return [unicode_to_str(element) for element in input] elif isinstance(input, unicode): return input.encode('utf-8') else: return input __all__ = [ "long", "string_types", "urlopen", "unescape", "configparser", "pickle", ]
24.632653
85
0.633803
795a634be17bee11e1525cd5ac571111710e845f
1,478
py
Python
galaxy/main/migrations/0028_auto_20151125_1231.py
SamyCoenen/galaxy
7c17ef45e53b0fc2fe8a2c70a99f3947604e0b0e
[ "Apache-2.0" ]
null
null
null
galaxy/main/migrations/0028_auto_20151125_1231.py
SamyCoenen/galaxy
7c17ef45e53b0fc2fe8a2c70a99f3947604e0b0e
[ "Apache-2.0" ]
null
null
null
galaxy/main/migrations/0028_auto_20151125_1231.py
SamyCoenen/galaxy
7c17ef45e53b0fc2fe8a2c70a99f3947604e0b0e
[ "Apache-2.0" ]
null
null
null
# NOTE(cutwater): This migration is replaced by v2_4_0 and should be # deleted once superseding migration is merged into master. from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('main', '0027_auto_20151125_0009'), ] operations = [ migrations.AddField( model_name='importtask', name='commit', field=models.CharField(max_length=256, blank=True), ), migrations.AddField( model_name='importtask', name='commit_message', field=models.CharField(max_length=256, blank=True), ), migrations.AddField( model_name='importtask', name='commit_url', field=models.CharField(max_length=256, blank=True), ), migrations.AddField( model_name='importtask', name='forks_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='importtask', name='open_issues_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='importtask', name='stargazers_count', field=models.IntegerField(default=0), ), migrations.AddField( model_name='importtask', name='watchers_count', field=models.IntegerField(default=0), ), ]
30.163265
68
0.575778
795a642ff93c8024e3771894d70ca27bf092a29c
2,094
py
Python
examples/demowlcutils.py
Juniper/py-jnpr-wlc
b614c3ade0c00c50c42ec76e602151969f31faf3
[ "Apache-2.0", "BSD-3-Clause" ]
2
2015-04-14T10:35:18.000Z
2017-02-13T05:12:01.000Z
examples/demowlcutils.py
Juniper/py-jnpr-wlc
b614c3ade0c00c50c42ec76e602151969f31faf3
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
examples/demowlcutils.py
Juniper/py-jnpr-wlc
b614c3ade0c00c50c42ec76e602151969f31faf3
[ "Apache-2.0", "BSD-3-Clause" ]
4
2015-07-09T12:07:05.000Z
2020-02-05T10:26:32.000Z
import sys, os from sys import argv as ARGV from jnpr.wlc import WirelessLanController as WLC from lxml import etree from pprint import pprint as pp import argparse from getpass import getpass from urllib2 import HTTPError ### --------------------------------------------------------------------------- ### parse the command line args ### --------------------------------------------------------------------------- def _parse_args(): cli = argparse.ArgumentParser( description="WLC API runner" ) cli.add_argument( '-u', '--user', action="store", dest='user', default=os.getenv('USER')) cli.add_argument( '-t', '--target', action="store", dest='target', default=None) cli.add_argument( '-p', '--password', action="store", dest='password', default=None ) cli_args = cli.parse_args() # allow for a -u <user>@<host> type of option try: user,target = cli_args.user.split('@') cli_args.user = user cli_args.target = target except ValueError: pass # ensure a target is provided if not cli_args.target: raise RuntimeError("You must specify the 'target' parameter") # ensure a password is provided if not cli_args.password: cli_args.password = getpass() if cli_args.password == '': raise RuntimeError("You must provide a password!") return cli_args ### --------------------------------------------------------------------------- ### ### --------------------------------------------------------------------------- def WLC_login(): cli_args = _parse_args() login = { 'user': cli_args.user, 'host': cli_args.target, 'password': cli_args.password } wlc = WLC( login ) try_again = 3 login_ok = False while try_again > 1: try: wlc.open() login_ok = True break; except HTTPError as err: if 401 == err.code: print "Password failed, try again." try_again -= 1 wlc.password = getpass() if not login_ok: print "Too many login failures, exiting" sys.exit(1) return wlc def ppxml(xml): print etree.tostring(xml,pretty_print=True)
25.851852
100
0.562082
795a66a4db153158a614d89a6f5acde528385253
656
py
Python
highlevel/util/clock.py
outech-robotic/code
b57acba3faae606f4d0c3cf210bc0716d7fef4e7
[ "MIT" ]
7
2020-04-15T16:42:56.000Z
2021-12-25T10:12:13.000Z
highlevel/util/clock.py
outech-robotic/code
b57acba3faae606f4d0c3cf210bc0716d7fef4e7
[ "MIT" ]
37
2020-04-15T15:49:31.000Z
2022-02-27T03:53:48.000Z
highlevel/util/clock.py
outech-robotic/code
b57acba3faae606f4d0c3cf210bc0716d7fef4e7
[ "MIT" ]
null
null
null
""" Clock to get the time. """ import time from abc import ABC, abstractmethod class Clock(ABC): """ Clock to get the time. This class can be replaced by a stub to "fake" time. """ @abstractmethod def time(self) -> float: """ Equivalent to time.time(). """ class RealClock(Clock): """ Real clock that will give you the real life time. """ def time(self) -> float: return time.time() class FakeClock(Clock): """ Fake clock where you can set the time manually. """ def __init__(self): self.fake_time = 0. def time(self): return self.fake_time
17.72973
56
0.579268
795a676cdb710e2944d458c320435a06c0ddb9b3
632
py
Python
tangram/urls.py
gutard/django-tangram
3dcde4c779feea2c8542af7716dfc8ff9c009c6a
[ "BSD-3-Clause" ]
null
null
null
tangram/urls.py
gutard/django-tangram
3dcde4c779feea2c8542af7716dfc8ff9c009c6a
[ "BSD-3-Clause" ]
2
2019-11-09T11:04:33.000Z
2019-11-09T11:08:51.000Z
tangram/urls.py
gutard/django-tangram
3dcde4c779feea2c8542af7716dfc8ff9c009c6a
[ "BSD-3-Clause" ]
null
null
null
from django.conf.urls import patterns, url urlpatterns = patterns("tangram.views", url("^respos/inscription/$", "inscription", name="inscription"), url("^respos/fiches-action/$", "fiches", name="fiches"), url("^respos/fiches-action/(?P<pk>\d+)/$", "fiche", name="fiche"), url("^respos/fiches-action/ajouter/$", "ajouter_fiche", name="ajouter_fiche"), url("^respos/fiches-action/(?P<pk>\d+)/modifier/$", "modifier_fiche", name="modifier_fiche"), url("^fichgrams/$", "fichgrams", name="fichgrams"), url("^fichgrams/(?P<numero>\d+)/$", "fichgram", name="fichgram"), url("^$", "grams", name="grams"), )
48.615385
97
0.636076
795a678c07ae25038c4790bd9c320c8d81f9f8f0
1,887
py
Python
configs/atss/atss_r50_fpn_1x_coco.py
GreysonPhoenix/mmdetection
5223e4fa62f418a3f1acd7f877bb0dfada234cdc
[ "Apache-2.0" ]
null
null
null
configs/atss/atss_r50_fpn_1x_coco.py
GreysonPhoenix/mmdetection
5223e4fa62f418a3f1acd7f877bb0dfada234cdc
[ "Apache-2.0" ]
null
null
null
configs/atss/atss_r50_fpn_1x_coco.py
GreysonPhoenix/mmdetection
5223e4fa62f418a3f1acd7f877bb0dfada234cdc
[ "Apache-2.0" ]
null
null
null
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict( type='ATSS', pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_output', num_outs=5), bbox_head=dict( type='ATSSHead', num_classes=12, in_channels=256, stacked_convs=4, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[0.1, 0.1, 0.2, 0.2]), loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=2.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), # training and testing settings train_cfg=dict( assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False), test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100)) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
29.952381
73
0.555909
795a67f3f19c775c7773919963adcee72a0bb206
57,693
py
Python
homeassistant/core.py
erogleva/core
994ae09f69afe772150a698953c0d7386a745de2
[ "Apache-2.0" ]
1
2020-10-15T10:45:39.000Z
2020-10-15T10:45:39.000Z
homeassistant/core.py
erogleva/core
994ae09f69afe772150a698953c0d7386a745de2
[ "Apache-2.0" ]
52
2020-07-14T14:12:26.000Z
2022-03-31T06:24:02.000Z
homeassistant/core.py
erogleva/core
994ae09f69afe772150a698953c0d7386a745de2
[ "Apache-2.0" ]
null
null
null
""" Core components of Home Assistant. Home Assistant is a Home Automation framework for observing the state of entities and react to changes. """ import asyncio import datetime import enum import functools from ipaddress import ip_address import logging import os import pathlib import re import threading from time import monotonic from types import MappingProxyType from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Collection, Coroutine, Dict, Iterable, List, Mapping, Optional, Set, TypeVar, Union, cast, ) import attr import voluptuous as vol import yarl from homeassistant import block_async_io, loader, util from homeassistant.const import ( ATTR_DOMAIN, ATTR_FRIENDLY_NAME, ATTR_NOW, ATTR_SECONDS, ATTR_SERVICE, ATTR_SERVICE_DATA, CONF_UNIT_SYSTEM_IMPERIAL, EVENT_CALL_SERVICE, EVENT_CORE_CONFIG_UPDATE, EVENT_HOMEASSISTANT_CLOSE, EVENT_HOMEASSISTANT_FINAL_WRITE, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STARTED, EVENT_HOMEASSISTANT_STOP, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, EVENT_TIMER_OUT_OF_SYNC, LENGTH_METERS, MATCH_ALL, __version__, ) from homeassistant.exceptions import ( HomeAssistantError, InvalidEntityFormatError, InvalidStateError, ServiceNotFound, Unauthorized, ) from homeassistant.util import location, network from homeassistant.util.async_ import fire_coroutine_threadsafe, run_callback_threadsafe import homeassistant.util.dt as dt_util from homeassistant.util.thread import fix_threading_exception_logging from homeassistant.util.timeout import TimeoutManager from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM, UnitSystem import homeassistant.util.uuid as uuid_util # Typing imports that create a circular dependency if TYPE_CHECKING: from homeassistant.auth import AuthManager from homeassistant.components.http import HomeAssistantHTTP from homeassistant.config_entries import ConfigEntries block_async_io.enable() fix_threading_exception_logging() T = TypeVar("T") _UNDEF: dict = {} # pylint: disable=invalid-name CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) CALLBACK_TYPE = Callable[[], None] # pylint: enable=invalid-name CORE_STORAGE_KEY = "core.config" CORE_STORAGE_VERSION = 1 DOMAIN = "homeassistant" # How long to wait to log tasks that are blocking BLOCK_LOG_TIMEOUT = 60 # How long we wait for the result of a service call SERVICE_CALL_LIMIT = 10 # seconds # Source of core configuration SOURCE_DISCOVERED = "discovered" SOURCE_STORAGE = "storage" SOURCE_YAML = "yaml" # How long to wait until things that run on startup have to finish. TIMEOUT_EVENT_START = 15 _LOGGER = logging.getLogger(__name__) def split_entity_id(entity_id: str) -> List[str]: """Split a state entity_id into domain, object_id.""" return entity_id.split(".", 1) VALID_ENTITY_ID = re.compile(r"^(?!.+__)(?!_)[\da-z_]+(?<!_)\.(?!_)[\da-z_]+(?<!_)$") def valid_entity_id(entity_id: str) -> bool: """Test if an entity ID is a valid format. Format: <domain>.<entity> where both are slugs. """ return VALID_ENTITY_ID.match(entity_id) is not None def valid_state(state: str) -> bool: """Test if a state is valid.""" return len(state) < 256 def callback(func: CALLABLE_T) -> CALLABLE_T: """Annotation to mark method as safe to call from within the event loop.""" setattr(func, "_hass_callback", True) return func def is_callback(func: Callable[..., Any]) -> bool: """Check if function is safe to be called in the event loop.""" return getattr(func, "_hass_callback", False) is True @enum.unique class HassJobType(enum.Enum): """Represent a job type.""" Coroutine = 1 Coroutinefunction = 2 Callback = 3 Executor = 4 class HassJob: """Represent a job to be run later. We check the callable type in advance so we can avoid checking it every time we run the job. """ __slots__ = ("job_type", "target") def __init__(self, target: Callable): """Create a job object.""" self.target = target self.job_type = _get_callable_job_type(target) def __repr__(self) -> str: """Return the job.""" return f"<Job {self.job_type} {self.target}>" def _get_callable_job_type(target: Callable) -> HassJobType: """Determine the job type from the callable.""" # Check for partials to properly determine if coroutine function check_target = target while isinstance(check_target, functools.partial): check_target = check_target.func if asyncio.iscoroutine(check_target): return HassJobType.Coroutine if asyncio.iscoroutinefunction(check_target): return HassJobType.Coroutinefunction if is_callback(check_target): return HassJobType.Callback return HassJobType.Executor class CoreState(enum.Enum): """Represent the current state of Home Assistant.""" not_running = "NOT_RUNNING" starting = "STARTING" running = "RUNNING" stopping = "STOPPING" final_write = "FINAL_WRITE" stopped = "STOPPED" def __str__(self) -> str: # pylint: disable=invalid-str-returned """Return the event.""" return self.value # type: ignore class HomeAssistant: """Root object of the Home Assistant home automation.""" auth: "AuthManager" http: "HomeAssistantHTTP" = None # type: ignore config_entries: "ConfigEntries" = None # type: ignore def __init__(self) -> None: """Initialize new Home Assistant object.""" self.loop = asyncio.get_running_loop() self._pending_tasks: list = [] self._track_task = True self.bus = EventBus(self) self.services = ServiceRegistry(self) self.states = StateMachine(self.bus, self.loop) self.config = Config(self) self.components = loader.Components(self) self.helpers = loader.Helpers(self) # This is a dictionary that any component can store any data on. self.data: dict = {} self.state: CoreState = CoreState.not_running self.exit_code: int = 0 # If not None, use to signal end-of-loop self._stopped: Optional[asyncio.Event] = None # Timeout handler for Core/Helper namespace self.timeout: TimeoutManager = TimeoutManager() @property def is_running(self) -> bool: """Return if Home Assistant is running.""" return self.state in (CoreState.starting, CoreState.running) @property def is_stopping(self) -> bool: """Return if Home Assistant is stopping.""" return self.state in (CoreState.stopping, CoreState.final_write) def start(self) -> int: """Start Home Assistant. Note: This function is only used for testing. For regular use, use "await hass.run()". """ # Register the async start fire_coroutine_threadsafe(self.async_start(), self.loop) # Run forever try: # Block until stopped _LOGGER.info("Starting Home Assistant core loop") self.loop.run_forever() finally: self.loop.close() return self.exit_code async def async_run(self, *, attach_signals: bool = True) -> int: """Home Assistant main entry point. Start Home Assistant and block until stopped. This method is a coroutine. """ if self.state != CoreState.not_running: raise RuntimeError("Home Assistant is already running") # _async_stop will set this instead of stopping the loop self._stopped = asyncio.Event() await self.async_start() if attach_signals: # pylint: disable=import-outside-toplevel from homeassistant.helpers.signal import async_register_signal_handling async_register_signal_handling(self) await self._stopped.wait() return self.exit_code async def async_start(self) -> None: """Finalize startup from inside the event loop. This method is a coroutine. """ _LOGGER.info("Starting Home Assistant") setattr(self.loop, "_thread_ident", threading.get_ident()) self.state = CoreState.starting self.bus.async_fire(EVENT_CORE_CONFIG_UPDATE) self.bus.async_fire(EVENT_HOMEASSISTANT_START) try: # Only block for EVENT_HOMEASSISTANT_START listener self.async_stop_track_tasks() async with self.timeout.async_timeout(TIMEOUT_EVENT_START): await self.async_block_till_done() except asyncio.TimeoutError: _LOGGER.warning( "Something is blocking Home Assistant from wrapping up the " "start up phase. We're going to continue anyway. Please " "report the following info at http://bit.ly/2ogP58T : %s", ", ".join(self.config.components), ) # Allow automations to set up the start triggers before changing state await asyncio.sleep(0) if self.state != CoreState.starting: _LOGGER.warning( "Home Assistant startup has been interrupted. " "Its state may be inconsistent" ) return self.state = CoreState.running self.bus.async_fire(EVENT_CORE_CONFIG_UPDATE) self.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) _async_create_timer(self) def add_job(self, target: Callable[..., Any], *args: Any) -> None: """Add job to the executor pool. target: target to call. args: parameters for method to call. """ if target is None: raise ValueError("Don't call add_job with None") self.loop.call_soon_threadsafe(self.async_add_job, target, *args) @callback def async_add_job( self, target: Callable[..., Any], *args: Any ) -> Optional[asyncio.Future]: """Add a job from within the event loop. This method must be run in the event loop. target: target to call. args: parameters for method to call. """ if target is None: raise ValueError("Don't call async_add_job with None") return self.async_add_hass_job(HassJob(target), *args) @callback def async_add_hass_job( self, hassjob: HassJob, *args: Any ) -> Optional[asyncio.Future]: """Add a HassJob from within the event loop. This method must be run in the event loop. hassjob: HassJob to call. args: parameters for method to call. """ if hassjob.job_type == HassJobType.Coroutine: task = self.loop.create_task(hassjob.target) # type: ignore elif hassjob.job_type == HassJobType.Coroutinefunction: task = self.loop.create_task(hassjob.target(*args)) elif hassjob.job_type == HassJobType.Callback: self.loop.call_soon(hassjob.target, *args) return None else: task = self.loop.run_in_executor( # type: ignore None, hassjob.target, *args ) # If a task is scheduled if self._track_task: self._pending_tasks.append(task) return task @callback def async_create_task(self, target: Coroutine) -> asyncio.tasks.Task: """Create a task from within the eventloop. This method must be run in the event loop. target: target to call. """ task: asyncio.tasks.Task = self.loop.create_task(target) if self._track_task: self._pending_tasks.append(task) return task @callback def async_add_executor_job( self, target: Callable[..., T], *args: Any ) -> Awaitable[T]: """Add an executor job from within the event loop.""" task = self.loop.run_in_executor(None, target, *args) # If a task is scheduled if self._track_task: self._pending_tasks.append(task) return task @callback def async_track_tasks(self) -> None: """Track tasks so you can wait for all tasks to be done.""" self._track_task = True @callback def async_stop_track_tasks(self) -> None: """Stop track tasks so you can't wait for all tasks to be done.""" self._track_task = False @callback def async_run_hass_job(self, hassjob: HassJob, *args: Any) -> None: """Run a HassJob from within the event loop. This method must be run in the event loop. hassjob: HassJob args: parameters for method to call. """ if hassjob.job_type == HassJobType.Callback: hassjob.target(*args) else: self.async_add_hass_job(hassjob, *args) @callback def async_run_job( self, target: Callable[..., Union[None, Awaitable]], *args: Any ) -> None: """Run a job from within the event loop. This method must be run in the event loop. target: target to call. args: parameters for method to call. """ self.async_run_hass_job(HassJob(target), *args) def block_till_done(self) -> None: """Block until all pending work is done.""" asyncio.run_coroutine_threadsafe( self.async_block_till_done(), self.loop ).result() async def async_block_till_done(self) -> None: """Block until all pending work is done.""" # To flush out any call_soon_threadsafe await asyncio.sleep(0) start_time: Optional[float] = None while self._pending_tasks: pending = [task for task in self._pending_tasks if not task.done()] self._pending_tasks.clear() if pending: await self._await_and_log_pending(pending) if start_time is None: # Avoid calling monotonic() until we know # we may need to start logging blocked tasks. start_time = 0 elif start_time == 0: # If we have waited twice then we set the start # time start_time = monotonic() elif monotonic() - start_time > BLOCK_LOG_TIMEOUT: # We have waited at least three loops and new tasks # continue to block. At this point we start # logging all waiting tasks. for task in pending: _LOGGER.debug("Waiting for task: %s", task) else: await asyncio.sleep(0) async def _await_and_log_pending(self, pending: Iterable[Awaitable[Any]]) -> None: """Await and log tasks that take a long time.""" wait_time = 0 while pending: _, pending = await asyncio.wait(pending, timeout=BLOCK_LOG_TIMEOUT) if not pending: return wait_time += BLOCK_LOG_TIMEOUT for task in pending: _LOGGER.debug("Waited %s seconds for task: %s", wait_time, task) def stop(self) -> None: """Stop Home Assistant and shuts down all threads.""" if self.state == CoreState.not_running: # just ignore return fire_coroutine_threadsafe(self.async_stop(), self.loop) async def async_stop(self, exit_code: int = 0, *, force: bool = False) -> None: """Stop Home Assistant and shuts down all threads. The "force" flag commands async_stop to proceed regardless of Home Assistan't current state. You should not set this flag unless you're testing. This method is a coroutine. """ if not force: # Some tests require async_stop to run, # regardless of the state of the loop. if self.state == CoreState.not_running: # just ignore return if self.state in [CoreState.stopping, CoreState.final_write]: _LOGGER.info("async_stop called twice: ignored") return if self.state == CoreState.starting: # This may not work _LOGGER.warning("async_stop called before startup is complete") # stage 1 self.state = CoreState.stopping self.async_track_tasks() self.bus.async_fire(EVENT_HOMEASSISTANT_STOP) try: async with self.timeout.async_timeout(120): await self.async_block_till_done() except asyncio.TimeoutError: _LOGGER.warning( "Timed out waiting for shutdown stage 1 to complete, the shutdown will continue" ) # stage 2 self.state = CoreState.final_write self.bus.async_fire(EVENT_HOMEASSISTANT_FINAL_WRITE) try: async with self.timeout.async_timeout(60): await self.async_block_till_done() except asyncio.TimeoutError: _LOGGER.warning( "Timed out waiting for shutdown stage 2 to complete, the shutdown will continue" ) # stage 3 self.state = CoreState.not_running self.bus.async_fire(EVENT_HOMEASSISTANT_CLOSE) try: async with self.timeout.async_timeout(30): await self.async_block_till_done() except asyncio.TimeoutError: _LOGGER.warning( "Timed out waiting for shutdown stage 3 to complete, the shutdown will continue" ) # Python 3.9+ and backported in runner.py await self.loop.shutdown_default_executor() # type: ignore self.exit_code = exit_code self.state = CoreState.stopped if self._stopped is not None: self._stopped.set() else: self.loop.stop() @attr.s(slots=True, frozen=True) class Context: """The context that triggered something.""" user_id: str = attr.ib(default=None) parent_id: Optional[str] = attr.ib(default=None) id: str = attr.ib(factory=uuid_util.random_uuid_hex) def as_dict(self) -> dict: """Return a dictionary representation of the context.""" return {"id": self.id, "parent_id": self.parent_id, "user_id": self.user_id} class EventOrigin(enum.Enum): """Represent the origin of an event.""" local = "LOCAL" remote = "REMOTE" def __str__(self) -> str: # pylint: disable=invalid-str-returned """Return the event.""" return self.value # type: ignore class Event: """Representation of an event within the bus.""" __slots__ = ["event_type", "data", "origin", "time_fired", "context"] def __init__( self, event_type: str, data: Optional[Dict[str, Any]] = None, origin: EventOrigin = EventOrigin.local, time_fired: Optional[datetime.datetime] = None, context: Optional[Context] = None, ) -> None: """Initialize a new event.""" self.event_type = event_type self.data = data or {} self.origin = origin self.time_fired = time_fired or dt_util.utcnow() self.context: Context = context or Context() def __hash__(self) -> int: """Make hashable.""" # The only event type that shares context are the TIME_CHANGED return hash((self.event_type, self.context.id, self.time_fired)) def as_dict(self) -> Dict: """Create a dict representation of this Event. Async friendly. """ return { "event_type": self.event_type, "data": dict(self.data), "origin": str(self.origin.value), "time_fired": self.time_fired.isoformat(), "context": self.context.as_dict(), } def __repr__(self) -> str: """Return the representation.""" # pylint: disable=maybe-no-member if self.data: return f"<Event {self.event_type}[{str(self.origin)[0]}]: {util.repr_helper(self.data)}>" return f"<Event {self.event_type}[{str(self.origin)[0]}]>" def __eq__(self, other: Any) -> bool: """Return the comparison.""" return ( # type: ignore self.__class__ == other.__class__ and self.event_type == other.event_type and self.data == other.data and self.origin == other.origin and self.time_fired == other.time_fired and self.context == other.context ) class EventBus: """Allow the firing of and listening for events.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize a new event bus.""" self._listeners: Dict[str, List[HassJob]] = {} self._hass = hass @callback def async_listeners(self) -> Dict[str, int]: """Return dictionary with events and the number of listeners. This method must be run in the event loop. """ return {key: len(self._listeners[key]) for key in self._listeners} @property def listeners(self) -> Dict[str, int]: """Return dictionary with events and the number of listeners.""" return run_callback_threadsafe(self._hass.loop, self.async_listeners).result() def fire( self, event_type: str, event_data: Optional[Dict] = None, origin: EventOrigin = EventOrigin.local, context: Optional[Context] = None, ) -> None: """Fire an event.""" self._hass.loop.call_soon_threadsafe( self.async_fire, event_type, event_data, origin, context ) @callback def async_fire( self, event_type: str, event_data: Optional[Dict] = None, origin: EventOrigin = EventOrigin.local, context: Optional[Context] = None, time_fired: Optional[datetime.datetime] = None, ) -> None: """Fire an event. This method must be run in the event loop. """ listeners = self._listeners.get(event_type, []) # EVENT_HOMEASSISTANT_CLOSE should go only to his listeners match_all_listeners = self._listeners.get(MATCH_ALL) if match_all_listeners is not None and event_type != EVENT_HOMEASSISTANT_CLOSE: listeners = match_all_listeners + listeners event = Event(event_type, event_data, origin, time_fired, context) if event_type != EVENT_TIME_CHANGED: _LOGGER.debug("Bus:Handling %s", event) if not listeners: return for job in listeners: self._hass.async_add_hass_job(job, event) def listen(self, event_type: str, listener: Callable) -> CALLBACK_TYPE: """Listen for all events or events of a specific type. To listen to all events specify the constant ``MATCH_ALL`` as event_type. """ async_remove_listener = run_callback_threadsafe( self._hass.loop, self.async_listen, event_type, listener ).result() def remove_listener() -> None: """Remove the listener.""" run_callback_threadsafe(self._hass.loop, async_remove_listener).result() return remove_listener @callback def async_listen(self, event_type: str, listener: Callable) -> CALLBACK_TYPE: """Listen for all events or events of a specific type. To listen to all events specify the constant ``MATCH_ALL`` as event_type. This method must be run in the event loop. """ return self._async_listen_job(event_type, HassJob(listener)) @callback def _async_listen_job(self, event_type: str, hassjob: HassJob) -> CALLBACK_TYPE: self._listeners.setdefault(event_type, []).append(hassjob) def remove_listener() -> None: """Remove the listener.""" self._async_remove_listener(event_type, hassjob) return remove_listener def listen_once(self, event_type: str, listener: Callable) -> CALLBACK_TYPE: """Listen once for event of a specific type. To listen to all events specify the constant ``MATCH_ALL`` as event_type. Returns function to unsubscribe the listener. """ async_remove_listener = run_callback_threadsafe( self._hass.loop, self.async_listen_once, event_type, listener ).result() def remove_listener() -> None: """Remove the listener.""" run_callback_threadsafe(self._hass.loop, async_remove_listener).result() return remove_listener @callback def async_listen_once(self, event_type: str, listener: Callable) -> CALLBACK_TYPE: """Listen once for event of a specific type. To listen to all events specify the constant ``MATCH_ALL`` as event_type. Returns registered listener that can be used with remove_listener. This method must be run in the event loop. """ job: Optional[HassJob] = None @callback def _onetime_listener(event: Event) -> None: """Remove listener from event bus and then fire listener.""" nonlocal job if hasattr(_onetime_listener, "run"): return # Set variable so that we will never run twice. # Because the event bus loop might have async_fire queued multiple # times, its possible this listener may already be lined up # multiple times as well. # This will make sure the second time it does nothing. setattr(_onetime_listener, "run", True) assert job is not None self._async_remove_listener(event_type, job) self._hass.async_run_job(listener, event) job = HassJob(_onetime_listener) return self._async_listen_job(event_type, job) @callback def _async_remove_listener(self, event_type: str, hassjob: HassJob) -> None: """Remove a listener of a specific event_type. This method must be run in the event loop. """ try: self._listeners[event_type].remove(hassjob) # delete event_type list if empty if not self._listeners[event_type]: self._listeners.pop(event_type) except (KeyError, ValueError): # KeyError is key event_type listener did not exist # ValueError if listener did not exist within event_type _LOGGER.warning("Unable to remove unknown job listener %s", hassjob) class State: """Object to represent a state within the state machine. entity_id: the entity that is represented. state: the state of the entity attributes: extra information on entity and state last_changed: last time the state was changed, not the attributes. last_updated: last time this object was updated. context: Context in which it was created domain: Domain of this state. object_id: Object id of this state. """ __slots__ = [ "entity_id", "state", "attributes", "last_changed", "last_updated", "context", "domain", "object_id", "_as_dict", ] def __init__( self, entity_id: str, state: str, attributes: Optional[Mapping] = None, last_changed: Optional[datetime.datetime] = None, last_updated: Optional[datetime.datetime] = None, context: Optional[Context] = None, validate_entity_id: Optional[bool] = True, ) -> None: """Initialize a new state.""" state = str(state) if validate_entity_id and not valid_entity_id(entity_id): raise InvalidEntityFormatError( f"Invalid entity id encountered: {entity_id}. " "Format should be <domain>.<object_id>" ) if not valid_state(state): raise InvalidStateError( f"Invalid state encountered for entity id: {entity_id}. " "State max length is 255 characters." ) self.entity_id = entity_id.lower() self.state = state self.attributes = MappingProxyType(attributes or {}) self.last_updated = last_updated or dt_util.utcnow() self.last_changed = last_changed or self.last_updated self.context = context or Context() self.domain, self.object_id = split_entity_id(self.entity_id) self._as_dict: Optional[Dict[str, Collection[Any]]] = None @property def name(self) -> str: """Name of this state.""" return self.attributes.get(ATTR_FRIENDLY_NAME) or self.object_id.replace( "_", " " ) def as_dict(self) -> Dict: """Return a dict representation of the State. Async friendly. To be used for JSON serialization. Ensures: state == State.from_dict(state.as_dict()) """ if not self._as_dict: last_changed_isoformat = self.last_changed.isoformat() if self.last_changed == self.last_updated: last_updated_isoformat = last_changed_isoformat else: last_updated_isoformat = self.last_updated.isoformat() self._as_dict = { "entity_id": self.entity_id, "state": self.state, "attributes": dict(self.attributes), "last_changed": last_changed_isoformat, "last_updated": last_updated_isoformat, "context": self.context.as_dict(), } return self._as_dict @classmethod def from_dict(cls, json_dict: Dict) -> Any: """Initialize a state from a dict. Async friendly. Ensures: state == State.from_json_dict(state.to_json_dict()) """ if not (json_dict and "entity_id" in json_dict and "state" in json_dict): return None last_changed = json_dict.get("last_changed") if isinstance(last_changed, str): last_changed = dt_util.parse_datetime(last_changed) last_updated = json_dict.get("last_updated") if isinstance(last_updated, str): last_updated = dt_util.parse_datetime(last_updated) context = json_dict.get("context") if context: context = Context(id=context.get("id"), user_id=context.get("user_id")) return cls( json_dict["entity_id"], json_dict["state"], json_dict.get("attributes"), last_changed, last_updated, context, ) def __eq__(self, other: Any) -> bool: """Return the comparison of the state.""" return ( # type: ignore self.__class__ == other.__class__ and self.entity_id == other.entity_id and self.state == other.state and self.attributes == other.attributes and self.context == other.context ) def __repr__(self) -> str: """Return the representation of the states.""" attrs = f"; {util.repr_helper(self.attributes)}" if self.attributes else "" return ( f"<state {self.entity_id}={self.state}{attrs}" f" @ {dt_util.as_local(self.last_changed).isoformat()}>" ) class StateMachine: """Helper class that tracks the state of different entities.""" def __init__(self, bus: EventBus, loop: asyncio.events.AbstractEventLoop) -> None: """Initialize state machine.""" self._states: Dict[str, State] = {} self._bus = bus self._loop = loop def entity_ids(self, domain_filter: Optional[str] = None) -> List[str]: """List of entity ids that are being tracked.""" future = run_callback_threadsafe( self._loop, self.async_entity_ids, domain_filter ) return future.result() @callback def async_entity_ids( self, domain_filter: Optional[Union[str, Iterable]] = None ) -> List[str]: """List of entity ids that are being tracked. This method must be run in the event loop. """ if domain_filter is None: return list(self._states) if isinstance(domain_filter, str): domain_filter = (domain_filter.lower(),) return [ state.entity_id for state in self._states.values() if state.domain in domain_filter ] @callback def async_entity_ids_count( self, domain_filter: Optional[Union[str, Iterable]] = None ) -> int: """Count the entity ids that are being tracked. This method must be run in the event loop. """ if domain_filter is None: return len(self._states) if isinstance(domain_filter, str): domain_filter = (domain_filter.lower(),) return len( [None for state in self._states.values() if state.domain in domain_filter] ) def all(self, domain_filter: Optional[Union[str, Iterable]] = None) -> List[State]: """Create a list of all states.""" return run_callback_threadsafe( self._loop, self.async_all, domain_filter ).result() @callback def async_all( self, domain_filter: Optional[Union[str, Iterable]] = None ) -> List[State]: """Create a list of all states matching the filter. This method must be run in the event loop. """ if domain_filter is None: return list(self._states.values()) if isinstance(domain_filter, str): domain_filter = (domain_filter.lower(),) return [ state for state in self._states.values() if state.domain in domain_filter ] def get(self, entity_id: str) -> Optional[State]: """Retrieve state of entity_id or None if not found. Async friendly. """ return self._states.get(entity_id.lower()) def is_state(self, entity_id: str, state: str) -> bool: """Test if entity exists and is in specified state. Async friendly. """ state_obj = self.get(entity_id) return state_obj is not None and state_obj.state == state def remove(self, entity_id: str) -> bool: """Remove the state of an entity. Returns boolean to indicate if an entity was removed. """ return run_callback_threadsafe( self._loop, self.async_remove, entity_id ).result() @callback def async_remove(self, entity_id: str, context: Optional[Context] = None) -> bool: """Remove the state of an entity. Returns boolean to indicate if an entity was removed. This method must be run in the event loop. """ entity_id = entity_id.lower() old_state = self._states.pop(entity_id, None) if old_state is None: return False self._bus.async_fire( EVENT_STATE_CHANGED, {"entity_id": entity_id, "old_state": old_state, "new_state": None}, EventOrigin.local, context=context, ) return True def set( self, entity_id: str, new_state: str, attributes: Optional[Dict] = None, force_update: bool = False, context: Optional[Context] = None, ) -> None: """Set the state of an entity, add entity if it does not exist. Attributes is an optional dict to specify attributes of this state. If you just update the attributes and not the state, last changed will not be affected. """ run_callback_threadsafe( self._loop, self.async_set, entity_id, new_state, attributes, force_update, context, ).result() @callback def async_set( self, entity_id: str, new_state: str, attributes: Optional[Dict] = None, force_update: bool = False, context: Optional[Context] = None, ) -> None: """Set the state of an entity, add entity if it does not exist. Attributes is an optional dict to specify attributes of this state. If you just update the attributes and not the state, last changed will not be affected. This method must be run in the event loop. """ entity_id = entity_id.lower() new_state = str(new_state) attributes = attributes or {} old_state = self._states.get(entity_id) if old_state is None: same_state = False same_attr = False last_changed = None else: same_state = old_state.state == new_state and not force_update same_attr = old_state.attributes == MappingProxyType(attributes) last_changed = old_state.last_changed if same_state else None if same_state and same_attr: return if context is None: context = Context() state = State( entity_id, new_state, attributes, last_changed, None, context, old_state is None, ) self._states[entity_id] = state self._bus.async_fire( EVENT_STATE_CHANGED, {"entity_id": entity_id, "old_state": old_state, "new_state": state}, EventOrigin.local, context, ) class Service: """Representation of a callable service.""" __slots__ = ["job", "schema"] def __init__( self, func: Callable, schema: Optional[vol.Schema], context: Optional[Context] = None, ) -> None: """Initialize a service.""" self.job = HassJob(func) self.schema = schema class ServiceCall: """Representation of a call to a service.""" __slots__ = ["domain", "service", "data", "context"] def __init__( self, domain: str, service: str, data: Optional[Dict] = None, context: Optional[Context] = None, ) -> None: """Initialize a service call.""" self.domain = domain.lower() self.service = service.lower() self.data = MappingProxyType(data or {}) self.context = context or Context() def __repr__(self) -> str: """Return the representation of the service.""" if self.data: return ( f"<ServiceCall {self.domain}.{self.service} " f"(c:{self.context.id}): {util.repr_helper(self.data)}>" ) return f"<ServiceCall {self.domain}.{self.service} (c:{self.context.id})>" class ServiceRegistry: """Offer the services over the eventbus.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize a service registry.""" self._services: Dict[str, Dict[str, Service]] = {} self._hass = hass @property def services(self) -> Dict[str, Dict[str, Service]]: """Return dictionary with per domain a list of available services.""" return run_callback_threadsafe(self._hass.loop, self.async_services).result() @callback def async_services(self) -> Dict[str, Dict[str, Service]]: """Return dictionary with per domain a list of available services. This method must be run in the event loop. """ return {domain: self._services[domain].copy() for domain in self._services} def has_service(self, domain: str, service: str) -> bool: """Test if specified service exists. Async friendly. """ return service.lower() in self._services.get(domain.lower(), []) def register( self, domain: str, service: str, service_func: Callable, schema: Optional[vol.Schema] = None, ) -> None: """ Register a service. Schema is called to coerce and validate the service data. """ run_callback_threadsafe( self._hass.loop, self.async_register, domain, service, service_func, schema ).result() @callback def async_register( self, domain: str, service: str, service_func: Callable, schema: Optional[vol.Schema] = None, ) -> None: """ Register a service. Schema is called to coerce and validate the service data. This method must be run in the event loop. """ domain = domain.lower() service = service.lower() service_obj = Service(service_func, schema) if domain in self._services: self._services[domain][service] = service_obj else: self._services[domain] = {service: service_obj} self._hass.bus.async_fire( EVENT_SERVICE_REGISTERED, {ATTR_DOMAIN: domain, ATTR_SERVICE: service} ) def remove(self, domain: str, service: str) -> None: """Remove a registered service from service handler.""" run_callback_threadsafe( self._hass.loop, self.async_remove, domain, service ).result() @callback def async_remove(self, domain: str, service: str) -> None: """Remove a registered service from service handler. This method must be run in the event loop. """ domain = domain.lower() service = service.lower() if service not in self._services.get(domain, {}): _LOGGER.warning("Unable to remove unknown service %s/%s", domain, service) return self._services[domain].pop(service) if not self._services[domain]: self._services.pop(domain) self._hass.bus.async_fire( EVENT_SERVICE_REMOVED, {ATTR_DOMAIN: domain, ATTR_SERVICE: service} ) def call( self, domain: str, service: str, service_data: Optional[Dict] = None, blocking: bool = False, context: Optional[Context] = None, limit: Optional[float] = SERVICE_CALL_LIMIT, ) -> Optional[bool]: """ Call a service. See description of async_call for details. """ return asyncio.run_coroutine_threadsafe( self.async_call(domain, service, service_data, blocking, context, limit), self._hass.loop, ).result() async def async_call( self, domain: str, service: str, service_data: Optional[Dict] = None, blocking: bool = False, context: Optional[Context] = None, limit: Optional[float] = SERVICE_CALL_LIMIT, ) -> Optional[bool]: """ Call a service. Specify blocking=True to wait until service is executed. Waits a maximum of limit, which may be None for no timeout. If blocking = True, will return boolean if service executed successfully within limit. This method will fire an event to indicate the service has been called. Because the service is sent as an event you are not allowed to use the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data. This method is a coroutine. """ domain = domain.lower() service = service.lower() context = context or Context() service_data = service_data or {} try: handler = self._services[domain][service] except KeyError: raise ServiceNotFound(domain, service) from None if handler.schema: try: processed_data = handler.schema(service_data) except vol.Invalid: _LOGGER.debug( "Invalid data for service call %s.%s: %s", domain, service, service_data, ) raise else: processed_data = service_data service_call = ServiceCall(domain, service, processed_data, context) self._hass.bus.async_fire( EVENT_CALL_SERVICE, { ATTR_DOMAIN: domain.lower(), ATTR_SERVICE: service.lower(), ATTR_SERVICE_DATA: service_data, }, context=context, ) coro = self._execute_service(handler, service_call) if not blocking: self._run_service_in_background(coro, service_call) return None task = self._hass.async_create_task(coro) try: await asyncio.wait({task}, timeout=limit) except asyncio.CancelledError: # Task calling us was cancelled, so cancel service call task, and wait for # it to be cancelled, within reason, before leaving. _LOGGER.debug("Service call was cancelled: %s", service_call) task.cancel() await asyncio.wait({task}, timeout=SERVICE_CALL_LIMIT) raise if task.cancelled(): # Service call task was cancelled some other way, such as during shutdown. _LOGGER.debug("Service was cancelled: %s", service_call) raise asyncio.CancelledError if task.done(): # Propagate any exceptions that might have happened during service call. task.result() # Service call completed successfully! return True # Service call task did not complete before timeout expired. # Let it keep running in background. self._run_service_in_background(task, service_call) _LOGGER.debug("Service did not complete before timeout: %s", service_call) return False def _run_service_in_background( self, coro_or_task: Union[Coroutine, asyncio.Task], service_call: ServiceCall ) -> None: """Run service call in background, catching and logging any exceptions.""" async def catch_exceptions() -> None: try: await coro_or_task except Unauthorized: _LOGGER.warning( "Unauthorized service called %s/%s", service_call.domain, service_call.service, ) except asyncio.CancelledError: _LOGGER.debug("Service was cancelled: %s", service_call) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error executing service: %s", service_call) self._hass.async_create_task(catch_exceptions()) async def _execute_service( self, handler: Service, service_call: ServiceCall ) -> None: """Execute a service.""" if handler.job.job_type == HassJobType.Coroutinefunction: await handler.job.target(service_call) elif handler.job.job_type == HassJobType.Callback: handler.job.target(service_call) else: await self._hass.async_add_executor_job(handler.job.target, service_call) class Config: """Configuration settings for Home Assistant.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize a new config object.""" self.hass = hass self.latitude: float = 0 self.longitude: float = 0 self.elevation: int = 0 self.location_name: str = "Home" self.time_zone: datetime.tzinfo = dt_util.UTC self.units: UnitSystem = METRIC_SYSTEM self.internal_url: Optional[str] = None self.external_url: Optional[str] = None self.config_source: str = "default" # If True, pip install is skipped for requirements on startup self.skip_pip: bool = False # List of loaded components self.components: Set[str] = set() # API (HTTP) server configuration, see components.http.ApiConfig self.api: Optional[Any] = None # Directory that holds the configuration self.config_dir: Optional[str] = None # List of allowed external dirs to access self.allowlist_external_dirs: Set[str] = set() # List of allowed external URLs that integrations may use self.allowlist_external_urls: Set[str] = set() # Dictionary of Media folders that integrations may use self.media_dirs: Dict[str, str] = {} # If Home Assistant is running in safe mode self.safe_mode: bool = False # Use legacy template behavior self.legacy_templates: bool = False def distance(self, lat: float, lon: float) -> Optional[float]: """Calculate distance from Home Assistant. Async friendly. """ return self.units.length( location.distance(self.latitude, self.longitude, lat, lon), LENGTH_METERS ) def path(self, *path: str) -> str: """Generate path to the file within the configuration directory. Async friendly. """ if self.config_dir is None: raise HomeAssistantError("config_dir is not set") return os.path.join(self.config_dir, *path) def is_allowed_external_url(self, url: str) -> bool: """Check if an external URL is allowed.""" parsed_url = f"{str(yarl.URL(url))}/" return any( allowed for allowed in self.allowlist_external_urls if parsed_url.startswith(allowed) ) def is_allowed_path(self, path: str) -> bool: """Check if the path is valid for access from outside.""" assert path is not None thepath = pathlib.Path(path) try: # The file path does not have to exist (it's parent should) if thepath.exists(): thepath = thepath.resolve() else: thepath = thepath.parent.resolve() except (FileNotFoundError, RuntimeError, PermissionError): return False for allowed_path in self.allowlist_external_dirs: try: thepath.relative_to(allowed_path) return True except ValueError: pass return False def as_dict(self) -> Dict: """Create a dictionary representation of the configuration. Async friendly. """ time_zone = dt_util.UTC.zone if self.time_zone and getattr(self.time_zone, "zone"): time_zone = getattr(self.time_zone, "zone") return { "latitude": self.latitude, "longitude": self.longitude, "elevation": self.elevation, "unit_system": self.units.as_dict(), "location_name": self.location_name, "time_zone": time_zone, "components": self.components, "config_dir": self.config_dir, # legacy, backwards compat "whitelist_external_dirs": self.allowlist_external_dirs, "allowlist_external_dirs": self.allowlist_external_dirs, "allowlist_external_urls": self.allowlist_external_urls, "version": __version__, "config_source": self.config_source, "safe_mode": self.safe_mode, "state": self.hass.state.value, "external_url": self.external_url, "internal_url": self.internal_url, } def set_time_zone(self, time_zone_str: str) -> None: """Help to set the time zone.""" time_zone = dt_util.get_time_zone(time_zone_str) if time_zone: self.time_zone = time_zone dt_util.set_default_time_zone(time_zone) else: raise ValueError(f"Received invalid time zone {time_zone_str}") @callback def _update( self, *, source: str, latitude: Optional[float] = None, longitude: Optional[float] = None, elevation: Optional[int] = None, unit_system: Optional[str] = None, location_name: Optional[str] = None, time_zone: Optional[str] = None, # pylint: disable=dangerous-default-value # _UNDEFs not modified external_url: Optional[Union[str, dict]] = _UNDEF, internal_url: Optional[Union[str, dict]] = _UNDEF, ) -> None: """Update the configuration from a dictionary.""" self.config_source = source if latitude is not None: self.latitude = latitude if longitude is not None: self.longitude = longitude if elevation is not None: self.elevation = elevation if unit_system is not None: if unit_system == CONF_UNIT_SYSTEM_IMPERIAL: self.units = IMPERIAL_SYSTEM else: self.units = METRIC_SYSTEM if location_name is not None: self.location_name = location_name if time_zone is not None: self.set_time_zone(time_zone) if external_url is not _UNDEF: self.external_url = cast(Optional[str], external_url) if internal_url is not _UNDEF: self.internal_url = cast(Optional[str], internal_url) async def async_update(self, **kwargs: Any) -> None: """Update the configuration from a dictionary.""" self._update(source=SOURCE_STORAGE, **kwargs) await self.async_store() self.hass.bus.async_fire(EVENT_CORE_CONFIG_UPDATE, kwargs) async def async_load(self) -> None: """Load [homeassistant] core config.""" store = self.hass.helpers.storage.Store( CORE_STORAGE_VERSION, CORE_STORAGE_KEY, private=True ) data = await store.async_load() async def migrate_base_url(_: Event) -> None: """Migrate base_url to internal_url/external_url.""" if self.hass.config.api is None: return base_url = yarl.URL(self.hass.config.api.deprecated_base_url) # Check if this is an internal URL if str(base_url.host).endswith(".local") or ( network.is_ip_address(str(base_url.host)) and network.is_private(ip_address(base_url.host)) ): await self.async_update( internal_url=network.normalize_url(str(base_url)) ) return # External, ensure this is not a loopback address if not ( network.is_ip_address(str(base_url.host)) and network.is_loopback(ip_address(base_url.host)) ): await self.async_update( external_url=network.normalize_url(str(base_url)) ) if data: # Try to migrate base_url to internal_url/external_url if "external_url" not in data: self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, migrate_base_url ) self._update( source=SOURCE_STORAGE, latitude=data.get("latitude"), longitude=data.get("longitude"), elevation=data.get("elevation"), unit_system=data.get("unit_system"), location_name=data.get("location_name"), time_zone=data.get("time_zone"), external_url=data.get("external_url", _UNDEF), internal_url=data.get("internal_url", _UNDEF), ) async def async_store(self) -> None: """Store [homeassistant] core config.""" time_zone = dt_util.UTC.zone if self.time_zone and getattr(self.time_zone, "zone"): time_zone = getattr(self.time_zone, "zone") data = { "latitude": self.latitude, "longitude": self.longitude, "elevation": self.elevation, "unit_system": self.units.name, "location_name": self.location_name, "time_zone": time_zone, "external_url": self.external_url, "internal_url": self.internal_url, } store = self.hass.helpers.storage.Store( CORE_STORAGE_VERSION, CORE_STORAGE_KEY, private=True ) await store.async_save(data) def _async_create_timer(hass: HomeAssistant) -> None: """Create a timer that will start on HOMEASSISTANT_START.""" handle = None timer_context = Context() def schedule_tick(now: datetime.datetime) -> None: """Schedule a timer tick when the next second rolls around.""" nonlocal handle slp_seconds = 1 - (now.microsecond / 10 ** 6) target = monotonic() + slp_seconds handle = hass.loop.call_later(slp_seconds, fire_time_event, target) @callback def fire_time_event(target: float) -> None: """Fire next time event.""" now = dt_util.utcnow() hass.bus.async_fire( EVENT_TIME_CHANGED, {ATTR_NOW: now}, time_fired=now, context=timer_context ) # If we are more than a second late, a tick was missed late = monotonic() - target if late > 1: hass.bus.async_fire( EVENT_TIMER_OUT_OF_SYNC, {ATTR_SECONDS: late}, time_fired=now, context=timer_context, ) schedule_tick(now) @callback def stop_timer(_: Event) -> None: """Stop the timer.""" if handle is not None: handle.cancel() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer) _LOGGER.info("Timer:starting") schedule_tick(dt_util.utcnow())
32.854784
101
0.608757
795a68a3cd3f2b8d2d5ad1d9003bd9c095ebe603
1,826
py
Python
app/resources/teams.py
dpfg/kicker-scorer-api
38dcf85e8e80a7a6a2213fb80f7f480c74f87cac
[ "MIT" ]
null
null
null
app/resources/teams.py
dpfg/kicker-scorer-api
38dcf85e8e80a7a6a2213fb80f7f480c74f87cac
[ "MIT" ]
null
null
null
app/resources/teams.py
dpfg/kicker-scorer-api
38dcf85e8e80a7a6a2213fb80f7f480c74f87cac
[ "MIT" ]
null
null
null
from app.resources import CommunityBasedResource from flask import jsonify from app.decorators import json_content from app.util import is_not_valid_entity_name from app.models import Team, Player from app.service import PlayerService, TeamService from app import db class TeamsResource(CommunityBasedResource): def get(self, community): return { "teams": [t.serialize for t in community.teams] } @json_content def post(self, community): """Method to create new team in the community. Required data: - team name ('name') - forward username ('forward') - goalkeeper username ('goalkeeper') If one of those fields is missed error will be returned. """ if 'name' not in request.json: return { "message": "missing required field: name" } name = request.json['name'].lower() if is_not_valid_entity_name(name): return { "message": "invalid name" } q = Team.query.filter_by(community_id=community.id, name=name) if q.count() != 0: return { "message": "team with this name already exists" }, 400 if 'forward' not in request.json: return { "message" : "missing required field: forward" } forward = PlayerService.find_by_username(community, request.json['forward']) if forward is None: return { "message": "forward not found" } if 'goalkeeper' not in request.json: return { "message" : "missing required field: forward" } goalkeeper = PlayerService.find_by_username(community, request.json['goalkeeper']) if goalkeeper is None: return { "message": "goalkeeper not found" } team = TeamService.create(community, name, goalkeeper, forward) return team.serialize
34.45283
90
0.648412
795a6ba64247707783e91d651820bfc490310feb
12,949
py
Python
MuJoCo/Walker2d/utilities.py
NickKaparinos/OpenAI-Gym-Projects
84d02d3b268bbc6017f98c0948c603cfd416f5c2
[ "MIT" ]
8
2021-10-09T07:50:26.000Z
2022-03-06T18:38:36.000Z
MuJoCo/Walker2d/utilities.py
NickKaparinos/OpenAI-Gym-Projects
84d02d3b268bbc6017f98c0948c603cfd416f5c2
[ "MIT" ]
null
null
null
MuJoCo/Walker2d/utilities.py
NickKaparinos/OpenAI-Gym-Projects
84d02d3b268bbc6017f98c0948c603cfd416f5c2
[ "MIT" ]
1
2022-02-04T16:34:42.000Z
2022-02-04T16:34:42.000Z
""" Open AI Gym Walker2d-v2 Nick Kaparinos 2021 """ import time import warnings from os import listdir, makedirs from typing import Any, Dict, Optional import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from stable_baselines3.common.callbacks import BaseCallback from tensorflow.python.summary.summary_iterator import summary_iterator from tianshou.data import (Batch, to_numpy) from tqdm import tqdm class LogStepsCallback(BaseCallback): def __init__(self, log_dir, verbose=0): self.log_dir = log_dir super(LogStepsCallback, self).__init__(verbose) def _on_training_start(self) -> None: self.results = pd.DataFrame(columns=['Reward', 'Done']) print("Τraining starts!") def _on_step(self) -> bool: if 'reward' in self.locals: keys = ['reward', 'done'] else: keys = ['rewards', 'dones'] self.results.loc[len(self.results)] = [self.locals[keys[0]][0], self.locals[keys[1]][0]] return True def _on_training_end(self) -> None: self.results.to_csv(self.log_dir + 'training_data.csv', index=False) print("Τraining ends!") class TqdmCallback(BaseCallback): def __init__(self): super().__init__() self.progress_bar = None def _on_training_start(self): self.progress_bar = tqdm(total=self.locals['total_timesteps']) def _on_step(self): self.progress_bar.update(1) return True def _on_training_end(self): self.progress_bar.close() self.progress_bar = None def save_dict_to_file(dict, path, txt_name='hyperparameter_dict'): f = open(path + '/' + txt_name + '.txt', 'w') f.write(str(dict)) f.close() def calc_episode_rewards(training_data): # Calculate the rewards for each training episode episode_rewards = [] temp_reward_sum = 0 for step in range(training_data.shape[0]): reward, done = training_data.iloc[step, :] temp_reward_sum += reward if done: episode_rewards.append(temp_reward_sum) temp_reward_sum = 0 result = pd.DataFrame(columns=['Reward']) result['Reward'] = episode_rewards return result def learning_curve(episode_rewards, log_dir, window=10): # Calculate rolling window metrics rolling_average = episode_rewards.rolling(window=window, min_periods=window).mean().dropna() rolling_max = episode_rewards.rolling(window=window, min_periods=window).max().dropna() rolling_min = episode_rewards.rolling(window=window, min_periods=window).min().dropna() # Change column name rolling_average.columns = ['Average Reward'] rolling_max.columns = ['Max Reward'] rolling_min.columns = ['Min Reward'] rolling_data = pd.concat([rolling_average, rolling_max, rolling_min], axis=1) # Plot sns.set() plt.figure(0) ax = sns.lineplot(data=rolling_data) ax.fill_between(rolling_average.index, rolling_min.iloc[:, 0], rolling_max.iloc[:, 0], alpha=0.2) ax.set_title('Learning Curve') ax.set_ylabel('Reward') ax.set_xlabel('Episodes') # Save figure plt.savefig(log_dir + 'learning_curve' + str(window) + '.png') def learning_curve_baselines(log_dir, window=10): # Read data training_data = pd.read_csv(log_dir + 'training_data.csv', index_col=None) # Calculate episode rewards episode_rewards = calc_episode_rewards(training_data) learning_curve(episode_rewards=episode_rewards, log_dir=log_dir, window=window) def learning_curve_tianshou(log_dir, window=10): # Find event file files = listdir(log_dir) for f in files: if 'events' in f: event_file = f break # Read episode rewards episode_rewards_list = [] episode_rewards = pd.DataFrame(columns=['Reward']) try: for e in summary_iterator(log_dir + event_file): if len(e.summary.value) > 0: if e.summary.value[0].tag == 'train/reward': episode_rewards_list.append(e.summary.value[0].simple_value) except Exception as e: pass episode_rewards['Reward'] = episode_rewards_list # Learning curve learning_curve(episode_rewards, log_dir, window=window) def learning_curve_tianshou_multiple_runs(log_dirs, window=10): episode_rewards_list = [] episode_rewards = pd.DataFrame(columns=['Reward']) for log_dir in log_dirs: # Find event file files = listdir(log_dir) for f in files: if 'events' in f: event_file = f break # Read episode rewards try: for e in summary_iterator(log_dir + event_file): if len(e.summary.value) > 0: if e.summary.value[0].tag == 'train/reward': episode_rewards_list.append(e.summary.value[0].simple_value) except Exception as e: pass episode_rewards['Reward'] = episode_rewards_list # Learning curve learning_curve(episode_rewards, log_dir, window=window) def collect_and_record(self, video_dir, n_step: Optional[int] = None, n_episode: Optional[int] = None, random: bool = False, render: Optional[float] = None, no_grad: bool = True, ) -> Dict[str, Any]: """Collect a specified number of step or episode. To ensure unbiased sampling result with n_episode option, this function will first collect ``n_episode - env_num`` episodes, then for the last ``env_num`` episodes, they will be collected evenly from each env. :param int n_step: how many steps you want to collect. :param int n_episode: how many episodes you want to collect. :param bool random: whether to use random policy for collecting data. Default to False. :param float render: the sleep time between rendering consecutive frames. Default to None (no rendering). :param bool no_grad: whether to retain gradient in policy.forward(). Default to True (no gradient retaining). .. note:: One and only one collection number specification is permitted, either ``n_step`` or ``n_episode``. :return: A dict including the following keys * ``n/ep`` collected number of episodes. * ``n/st`` collected number of steps. * ``rews`` array of episode reward over collected episodes. * ``lens`` array of episode length over collected episodes. * ``idxs`` array of episode start index in buffer over collected episodes. """ assert not self.env.is_async, "Please use AsyncCollector if using async venv." if n_step is not None: assert n_episode is None, ( f"Only one of n_step or n_episode is allowed in Collector." f"collect, got n_step={n_step}, n_episode={n_episode}." ) assert n_step > 0 if not n_step % self.env_num == 0: warnings.warn( f"n_step={n_step} is not a multiple of #env ({self.env_num}), " "which may cause extra transitions collected into the buffer." ) ready_env_ids = np.arange(self.env_num) elif n_episode is not None: assert n_episode > 0 ready_env_ids = np.arange(min(self.env_num, n_episode)) self.data = self.data[:min(self.env_num, n_episode)] else: raise TypeError( "Please specify at least one (either n_step or n_episode) " "in AsyncCollector.collect()." ) start_time = time.time() step_count = 0 episode_count = 0 episode_rews = [] episode_lens = [] episode_start_indices = [] img_array_list = [] while True: assert len(self.data) == len(ready_env_ids) # restore the state: if the last state is None, it won't store last_state = self.data.policy.pop("hidden_state", None) # get the next action if random: self.data.update( act=[self._action_space[i].sample() for i in ready_env_ids] ) else: if no_grad: with torch.no_grad(): # faster than retain_grad version # self.data.obs will be used by agent to get result result = self.policy(self.data, last_state) else: result = self.policy(self.data, last_state) # update state / act / policy into self.data policy = result.get("policy", Batch()) assert isinstance(policy, Batch) state = result.get("state", None) if state is not None: policy.hidden_state = state # save state into buffer act = to_numpy(result.act) if self.exploration_noise: act = self.policy.exploration_noise(act, self.data) self.data.update(policy=policy, act=act) # get bounded and remapped actions first (not saved into buffer) action_remap = self.policy.map_action(self.data.act) # step in env result = self.env.step(action_remap, ready_env_ids) # type: ignore obs_next, rew, done, info = result self.data.update(obs_next=obs_next, rew=rew, done=done, info=info) if self.preprocess_fn: self.data.update( self.preprocess_fn( obs_next=self.data.obs_next, rew=self.data.rew, done=self.data.done, info=self.data.info, policy=self.data.policy, env_id=ready_env_ids, ) ) if render: img_array = self.env.render(mode='rgb_array') img_array = np.array(img_array)[0, :, :, :] img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB) img_array_list.append(img_array) if render > 0 and not np.isclose(render, 0): time.sleep(render) # add data into the buffer ptr, ep_rew, ep_len, ep_idx = self.buffer.add( self.data, buffer_ids=ready_env_ids ) # collect statistics step_count += len(ready_env_ids) if np.any(done): env_ind_local = np.where(done)[0] env_ind_global = ready_env_ids[env_ind_local] episode_count += len(env_ind_local) episode_lens.append(ep_len[env_ind_local]) episode_rews.append(ep_rew[env_ind_local]) episode_start_indices.append(ep_idx[env_ind_local]) # now we copy obs_next to obs, but since there might be # finished episodes, we have to reset finished envs first. obs_reset = self.env.reset(env_ind_global) if self.preprocess_fn: obs_reset = self.preprocess_fn( obs=obs_reset, env_id=env_ind_global ).get("obs", obs_reset) self.data.obs_next[env_ind_local] = obs_reset for i in env_ind_local: self._reset_state(i) # remove surplus env id from ready_env_ids # to avoid bias in selecting environments if n_episode: surplus_env_num = len(ready_env_ids) - (n_episode - episode_count) if surplus_env_num > 0: mask = np.ones_like(ready_env_ids, dtype=bool) mask[env_ind_local[:surplus_env_num]] = False ready_env_ids = ready_env_ids[mask] self.data = self.data[mask] self.data.obs = self.data.obs_next if (n_step and step_count >= n_step) or \ (n_episode and episode_count >= n_episode): break # generate statistics self.collect_step += step_count self.collect_episode += episode_count self.collect_time += max(time.time() - start_time, 1e-9) if n_episode: self.data = Batch( obs={}, act={}, rew={}, done={}, obs_next={}, info={}, policy={} ) self.reset_env() if episode_count > 0: rews, lens, idxs = list( map( np.concatenate, [episode_rews, episode_lens, episode_start_indices] ) ) else: rews, lens, idxs = np.array([]), np.array([], int), np.array([], int) # Save video width, height = img_array_list[0].shape[0], img_array_list[0].shape[1] fourcc = cv2.VideoWriter_fourcc(*'mp4v') makedirs(video_dir) video = cv2.VideoWriter(video_dir + 'video.mp4', fourcc, 60, (width, height)) for img in img_array_list: video.write(img) video.release() save_dict_to_file({'reward': rews[0], 'length': lens[0]}, video_dir, txt_name='episode_stats') return { "n/ep": episode_count, "n/st": step_count, "rews": rews, "lens": lens, "idxs": idxs, }
34.997297
102
0.617036
795a6bb4e966d7b1ed1c27ed5a9d84f01c0a4271
7,583
py
Python
leader/leader_arango2hbase.py
RogerJTX/kbpPipeline_ExpertSystem
53f998ccb04ec9e932363818e037c3c5b225f05b
[ "MIT" ]
3
2021-01-29T17:09:55.000Z
2021-07-12T11:37:29.000Z
leader/leader_arango2hbase.py
RogerJTX/kbpPipeline_ExpertSystem
53f998ccb04ec9e932363818e037c3c5b225f05b
[ "MIT" ]
null
null
null
leader/leader_arango2hbase.py
RogerJTX/kbpPipeline_ExpertSystem
53f998ccb04ec9e932363818e037c3c5b225f05b
[ "MIT" ]
1
2022-02-11T11:09:03.000Z
2022-02-11T11:09:03.000Z
#!/home/apollo/anaconda3/bin/python3 #-*- coding: utf-8 -*- #****************************************************************************** # Author : jtx # Last modified: 2020-08-31 14:08 # Filename : leader_arango2hbase.py # Description : 高管实体;从分区中读取数据调用pipeline处理,并存入HBASE结构化文档库;每天跑数据 #****************************************************************************** from pymongo import MongoClient import happybase from pyhive import hive from dateutil import parser import requests import sys from tqdm import tqdm import json import logging from logging.handlers import RotatingFileHandler import configparser from datetime import datetime, date, timedelta import pyArango.connection as ArangoDb from pyArango.theExceptions import AQLFetchError import pymysql import re import os dir_path = os.path.dirname(__file__) kbp_path = os.path.dirname(dir_path) config_path = os.path.join(kbp_path,"config.ini") def set_log(): logging.basicConfig(level=logging.INFO) file_log_handler = RotatingFileHandler(os.path.join(dir_path,"log.txt"), maxBytes=1024 * 1024 * 300, backupCount=10) formatter = logging.Formatter('%(asctime)s - %(filename)s - %(lineno)s - %(levelname)s - %(message)s') file_log_handler.setFormatter(formatter) logging.getLogger().addHandler(file_log_handler) set_log() logger = logging.getLogger(__name__) class EntityPipeline(object): def __init__(self): self.config = configparser.ConfigParser() self.config.read(config_path) self.init_concpet_classid() # 加载实体类别定义关键词映射 self.nlpipe_count = 0 # 经过PIPE的实体数 self.hbase_count = 0 # 导入HBASE的实体数 self.hbase_dupl_count = 0 # 监测rowkey已存在的实体数 self.no_hbase_count = 0 # 找不到HBASE rowkey的实体,分类去重颠倒导致 self.hive_count = 0 # 导入HIVE实体数 self.duplicate_count = 0 # PIPE去重模块检测到的重复实体数 self.ignore_count = 0 # 无关实体数 self.hive_dupl_count = 0 # 监测HIVE中已存在日志的实体数 def init_concpet_classid(self): ''' 加载MYSQL中定义的实体类别表 ''' self.news_class_ids = {} sql_conn = pymysql.connect( host = self.config.get("mysql","host") , user = self.config.get("mysql","user") , passwd = self.config.get("mysql","passwd"), port = self.config.getint("mysql","port") , db = self.config.get("mysql","db"), charset = "utf8" ) sql_cur = sql_conn.cursor() sql_state = self.config.get("mysql","entity_type_query").replace("eq","=") sql_cur.execute(sql_state) mysql_res = sql_cur.fetchall() for name, class_id, patent_id in mysql_res: self.news_class_ids[name] = class_id logger.info("MYSQL实体类别定义加载完成") sql_cur.close() sql_conn.close() def process_leader_hbase_data(self,item): ''' 将读取的arango记录转换成hbase存储结构''' classid = self.news_class_ids['企业高管'] rowkey_str = classid+'|'+item['_key'] rowkey = bytes(rowkey_str, encoding="utf8") alter_names = [] tags = [] crawl_t = "" if 'crawl_time' in item: craw_t = item["properties"]["crawl_time"] if 'alter_names' in item: alter_names = item['alter_names'] if 'tags' in item: tags = item['tags'] column_family = {#高管暂无别名 默认空 b"info:alter_names": bytes(json.dumps(alter_names, ensure_ascii=False), encoding="utf8"), b"info:entity_type_id": bytes(classid, encoding="utf8"), b"info:entity_name": bytes(item["name"], encoding="utf8"), b"info:uuid": bytes(item["_key"], encoding="utf8"), b"info:entity_properties": bytes(json.dumps(item["properties"], ensure_ascii=False), encoding="utf8"),#.getStore() for doc b"info:tags": bytes(json.dumps(tags, ensure_ascii=False), encoding="utf8"), b"info:relations": bytes(json.dumps(item["relations"], ensure_ascii=False), encoding="utf8"), b"info:insert_time": bytes(datetime.today().strftime("%Y-%m-%d %H:%M:%S"), encoding="utf8") } return rowkey,column_family def link_arangoDb(self, date_str, end_date=""): logging.info("正在处理[高管] arango数据...") query_time = "" colletion_name = "kb_leader" if date_str == "yesterday": process_date = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d") end_date = date.today().strftime("%Y-%m-%d") elif len(date_str.split("-")) == 3: process_date = date_str else: raise Exception("无效日期参数") query_time = parser.parse(process_date+"T00:00:00+08:00") if end_date: end_process_date = end_date iso_end_date_str = end_process_date + 'T00:00:00+08:00' iso_end_date = parser.parse(iso_end_date_str) if date_str == "yesterday" or end_date: aql_arango = "FOR leader IN {} FILTER leader.update_time >= '{}' and leader.update_time < '{}' return leader".format( colletion_name, query_time,iso_end_date) else: aql_arango = "FOR leader IN %s FILTER leader.update_time >= '%s' return leader" % (colletion_name,query_time) conn = ArangoDb.Connection(\ arangoURL=self.config.get("arango","arango_url"), username=self.config.get("arango","user") , password=self.config.get("arango","passwd") ) db_name = conn[self.config.get("arango","db")] collection = db_name[colletion_name] try: query = db_name.fetch_list(aql_arango) except AQLFetchError as e: query = [] logger.warn("Arango[高管] 库没有查到数据",e) logger.info("HBASE共含有[高管] %s条记录,本次查询%s条记录!" % (collection.figures()['count'],len(query))) num = 0 num_ins = 0 pre_send_rowkey = [] pre_send_data = [] for item in query: num += 1 #################################################### rowkey, data = self.process_leader_hbase_data(item)# #################################################### if rowkey not in pre_send_rowkey: pre_send_rowkey.append(rowkey) pre_send_data.append(data) zip_list = zip(pre_send_rowkey, pre_send_data) logger.info("数据封装完毕,开始写入hbase...") self.hbase_pool = happybase.ConnectionPool( host = self.config.get("hbase","host"), port = self.config.getint("hbase","port"), timeout=None, autoconnect=True, size = self.config.getint("hbase","pool_size")) with self.hbase_pool.connection() as hbase_conn: self.hbase_entity_table = hbase_conn.table(self.config.get("hbase","entity")) with self.hbase_entity_table.batch(batch_size=200) as bat: for send_rowkey, send_data in zip_list: bat.put(send_rowkey, send_data) self.hbase_count += 1 if self.hbase_count % 500 == 0: logger.info("已经写入写入hbase...{}条".format(self.hbase_count)) logger.info("HBASE批量数据导入完成,共插入%s条高管记录" % self.hbase_count) if __name__ == '__main__': entity_pipe = EntityPipeline() if len(sys.argv) > 1: tmp_param = sys.argv[1] else: tmp_param = "yesterday" entity_pipe.link_arangoDb(tmp_param)
40.989189
134
0.583015
795a6c2d22f8e70d88698bcc340f27ca21920623
1,387
py
Python
tao_triton/python/types/user_data.py
thtang-nv/tao-toolkit-triton-apps
de72ae4fe96986db620b542feed917f4430ac768
[ "MIT" ]
24
2021-08-31T04:34:31.000Z
2022-03-25T18:52:33.000Z
tao_triton/python/types/user_data.py
thtang-nv/tao-toolkit-triton-apps
de72ae4fe96986db620b542feed917f4430ac768
[ "MIT" ]
8
2021-11-03T09:45:16.000Z
2022-03-24T12:05:33.000Z
tao_triton/python/types/user_data.py
thtang-nv/tao-toolkit-triton-apps
de72ae4fe96986db620b542feed917f4430ac768
[ "MIT" ]
7
2021-12-02T06:09:57.000Z
2022-03-23T22:36:47.000Z
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # 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. """User data requests.""" import sys if sys.version_info >= (3, 0): import queue else: import Queue as queue class UserData: """Data structure to gather queued requests.""" def __init__(self): self._completed_requests = queue.Queue()
39.628571
72
0.754867
795a6c5d8345e070069f011b179b9851465e5e86
81
py
Python
apps/operations/views.py
HuChangShan/MyMOOC
4f82a70da58dbd06f4bf2200ac320595421b5625
[ "MIT" ]
null
null
null
apps/operations/views.py
HuChangShan/MyMOOC
4f82a70da58dbd06f4bf2200ac320595421b5625
[ "MIT" ]
null
null
null
apps/operations/views.py
HuChangShan/MyMOOC
4f82a70da58dbd06f4bf2200ac320595421b5625
[ "MIT" ]
null
null
null
# encoding:utf-8 from django.shortcuts import render # Create your views here.
13.5
35
0.765432
795a6d279a93270ad709f9f9c4c58c3948f5f291
1,810
py
Python
cogs/error_handling.py
roooof/RoboBilly
50cdf286bd4c90c4ae0d296a45921877ca063263
[ "MIT" ]
null
null
null
cogs/error_handling.py
roooof/RoboBilly
50cdf286bd4c90c4ae0d296a45921877ca063263
[ "MIT" ]
null
null
null
cogs/error_handling.py
roooof/RoboBilly
50cdf286bd4c90c4ae0d296a45921877ca063263
[ "MIT" ]
null
null
null
import discord from discord.ext import commands import difflib, math QUESTION_MARK_ICON = "https://cdn.discordapp.com/emojis/512367613339369475.png" class ErrorHandling(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): """Command error handler""" embed = discord.Embed(color=discord.Color.red()) if isinstance(error, commands.CommandNotFound): await self.send_command_suggestion(ctx, ctx.invoked_with) return elif isinstance(error, commands.CommandOnCooldown): embed.title = "Whoops Cooldown!" embed.description = f"Command is on cooldown. Try again after {math.ceil(error.retry_after)} seconds!" await ctx.send(embed=embed) else: print(error) async def send_command_suggestion(self, ctx: commands.Context, command_name: str) -> None: """Sends user similar commands if any can be found.""" raw_commands = [] for cmd in self.bot.walk_commands(): if not cmd.hidden: raw_commands += (cmd.name, *cmd.aliases) if similar_command_data := difflib.get_close_matches(command_name, raw_commands, 1): similar_command_name = similar_command_data[0] similar_command = self.bot.get_command(similar_command_name) if not similar_command: return misspelled_content = ctx.message.content e = discord.Embed() e.set_author(name="Did you mean:", icon_url=QUESTION_MARK_ICON) e.description = misspelled_content.replace(command_name, similar_command_name, 1) await ctx.send(embed=e) def setup(bot): bot.add_cog(ErrorHandling(bot))
36.938776
114
0.652486
795a6dcc28d5cc8c390cdb1c80f2721146dd1c09
36,020
py
Python
src/radical/entk/appman/appmanager.py
tirkarthi/radical.entk
ea84d8e85d82eb1dbf752d8f547c0f8872dc50a9
[ "MIT" ]
null
null
null
src/radical/entk/appman/appmanager.py
tirkarthi/radical.entk
ea84d8e85d82eb1dbf752d8f547c0f8872dc50a9
[ "MIT" ]
null
null
null
src/radical/entk/appman/appmanager.py
tirkarthi/radical.entk
ea84d8e85d82eb1dbf752d8f547c0f8872dc50a9
[ "MIT" ]
null
null
null
__copyright__ = 'Copyright 2017-2018, http://radical.rutgers.edu' __author__ = 'Vivek Balasubramanian <vivek.balasubramaniana@rutgers.edu>' __license__ = 'MIT' import os import json import pika import time import threading as mt import radical.utils as ru from .. import exceptions as ree from ..pipeline import Pipeline from ..task import Task from radical.entk import states from ..utils import write_session_description from ..utils import write_workflows from .wfprocessor import WFprocessor # pylint: disable=protected-access # ------------------------------------------------------------------------------ # class AppManager(object): ''' An application manager takes the responsibility of setting up the communication infrastructure, instantiates the ResourceManager, TaskManager, WFProcessor objects and all their threads and processes. This is the Master object running in the main process and is designed to recover from errors from all other objects, threads and processes. :Arguments: :config_path: Url to config path to be read for AppManager :hostname: host rabbitmq server is running :port: port at which rabbitmq can be accessed :username: username to log in to RabbitMQ :password: password to log in to RabbitMQ :reattempts: number of attempts to re-invoke any failed EnTK components :resubmit_failed: resubmit failed tasks (True/False) :autoterminate: terminate resource reservation upon execution of all tasks of first workflow (True/False) :write_workflow: write workflow and mapping to rts entities to a file (post-termination) :rts: Specify RTS to use. Current options: 'mock', 'radical.pilot' (default if unspecified) :rmq_cleanup: Cleanup all queues created in RabbitMQ server for current execution (default is True) :rts_config: Configuration for the RTS, accepts {'sandbox_cleanup': True/False,'db_cleanup': True/False} when RTS is RP :name: Name of the Application. It should be unique between executions. (default is randomly assigned) ''' # -------------------------------------------------------------------------- # def __init__(self, config_path=None, hostname=None, port=None, username=None, password=None, reattempts=None, resubmit_failed=None, autoterminate=None, write_workflow=None, rts=None, rmq_cleanup=None, rts_config=None, name=None): # Create a session for each EnTK script execution if name: self._name = name self._sid = name else: self._name = str() self._sid = ru.generate_id('re.session', ru.ID_PRIVATE) self._read_config(config_path, hostname, port, username, password, reattempts, resubmit_failed, autoterminate, write_workflow, rts, rmq_cleanup, rts_config) # Create an uid + logger + profiles for AppManager, under the sid # namespace self._uid = ru.generate_id('appmanager.%(counter)04d', ru.ID_CUSTOM) path = os.getcwd() + '/' + self._sid name = 'radical.entk.%s' % self._uid self._logger = ru.Logger(name=name, path=path) self._prof = ru.Profiler(name=name, path=path) self._report = ru.Reporter(name=name) self._report.info('EnTK session: %s\n' % self._sid) self._report.info('Creating AppManager') self._prof.prof('amgr_creat', uid=self._uid) self._rmgr = None self._pending_queue = list() self._completed_queue = list() # Global parameters to have default values self._mqs_setup = False self._resource_desc = None self._task_manager = None self._workflow = None self._workflows = list() self._cur_attempt = 1 self._shared_data = list() self._outputs = None self._wfp = None self._sync_thread = None self._terminate_sync = mt.Event() self._resubmit_failed = False self._port = int(self._port) # Setup rabbitmq queues self._setup_mqs() self._rmq_ping_interval = int(os.getenv('RMQ_PING_INTERVAL', "10")) self._logger.info('Application Manager initialized') self._prof.prof('amgr_created', uid=self._uid) self._report.ok('>>ok\n') # -------------------------------------------------------------------------- # def _read_config(self, config_path, hostname, port, username, password, reattempts, resubmit_failed, autoterminate, write_workflow, rts, rmq_cleanup, rts_config): if not config_path: config_path = os.path.dirname(os.path.abspath(__file__)) config = ru.read_json(os.path.join(config_path, 'config.json')) def _if(val1, val2): if val1 is not None: return val1 else : return val2 self._hostname = _if(hostname, config['hostname']) self._port = _if(port, config['port']) self._username = _if(username, config['username']) self._password = _if(password, config['password']) self._reattempts = _if(reattempts, config['reattempts']) self._resubmit_failed = _if(resubmit_failed, config['resubmit_failed']) self._autoterminate = _if(autoterminate, config['autoterminate']) self._write_workflow = _if(write_workflow, config['write_workflow']) self._rmq_cleanup = _if(rmq_cleanup, config['rmq_cleanup']) self._rts_config = _if(rts_config, config['rts_config']) self._rts = _if(rts, config['rts']) credentials = pika.PlainCredentials(self._username, self._password) self._rmq_conn_params = pika.connection.ConnectionParameters( host=self._hostname, port=self._port, credentials=credentials) self._num_pending_qs = config['pending_qs'] self._num_completed_qs = config['completed_qs'] if self._rts not in ['radical.pilot', 'mock']: raise ValueError('invalid RTS %s' % self._rts) # -------------------------------------------------------------------------- # # Getter functions # @property def name(self): ''' Name for the application manager. Allows the user to setup the name of the application manager, as well as its session ID. This name should be unique between different EnTK executions, otherwise it will produce an error. :getter: Returns the name of the application manager :setter: Assigns the name of the application manager :type: String ''' return self._name # -------------------------------------------------------------------------- # @property def sid(self): ''' Get the session ID of the current EnTK execution :getter: Returns the session ID of the EnTK execution :type: String ''' return self._sid # -------------------------------------------------------------------------- # @property def resource_desc(self): ''' :getter: Returns the resource description :setter: Assigns a resource description ''' return self._resource_desc # -------------------------------------------------------------------------- # @property def workflow(self): ''' :getter: Return the last workflow assigned for execution :setter: Assign a new workflow to be executed ''' return self._workflow # -------------------------------------------------------------------------- # @property def workflows(self): """ :getter: Return a list of workflows assigned for execution """ return self._workflows @property def shared_data(self): ''' :getter: Return list of filenames that are shared between multiple tasks of the application :setter: Assign a list of names of files that need to be staged to the remote machine ''' return self._shared_data @property def outputs(self): ''' :getter: Return list of filenames that are to be staged out after execution :setter: Assign a list of names of files that need to be staged from the remote machine ''' return self._outputs # -------------------------------------------------------------------------- # Setter functions # @name.setter def name(self, value): if not isinstance(value, str): raise ree.TypeError(expected_type=str, actual_type=type(value)) self._name = value # -------------------------------------------------------------------------- # @resource_desc.setter def resource_desc(self, value): if self._rts == 'radical.pilot': from radical.entk.execman.rp import ResourceManager elif self._rts == 'mock': from radical.entk.execman.mock import ResourceManager self._rmgr = ResourceManager(resource_desc=value, sid=self._sid, rts_config=self._rts_config) self._report.info('Validating and assigning resource manager') if not self._rmgr._validate_resource_desc(): self._logger.error('Could not validate resource description') raise ree.EnTKError('Could not validate resource description') self._rmgr._populate() self._rmgr.shared_data = self._shared_data self._rmgr.outputs = self._outputs self._report.ok('>>ok\n') # -------------------------------------------------------------------------- # @workflow.setter def workflow(self, workflow): self._prof.prof('assigning workflow', uid=self._uid) for p in workflow: if not isinstance(p, Pipeline): self._logger.info('workflow type incorrect') raise ree.TypeError(expected_type=['Pipeline', 'set of Pipelines'], actual_type=type(p)) p._validate() # keep history self._workflows.append(workflow) # set current workflow self._workflow = workflow self._logger.info('Workflow assigned to Application Manager') # -------------------------------------------------------------------------- # @shared_data.setter def shared_data(self, data): if not isinstance(data, list): data = [data] for value in data: if not isinstance(value, str): raise ree.TypeError(expected_type=str, actual_type=type(value)) self._shared_data = data if self._rmgr: self._rmgr.shared_data = data # -------------------------------------------------------------------------- # @outputs.setter def outputs(self, data): if not isinstance(data, list): data = [data] for value in data: if not isinstance(value, str): raise ree.TypeError(expected_type=str, actual_type=type(value)) if self._rmgr: self._rmgr.outputs = data # -------------------------------------------------------------------------- # # Public methods # def run(self): ''' **Purpose**: Run the application manager. Once the workflow and resource manager have been assigned. Invoking this method will start the setting up the communication infrastructure, submitting a resource request and then submission of all the tasks. ''' ret = None try: self._prof.prof('amgr_start', uid=self._uid) # Set None for variables local to each run self._resubmit_failed = False self._cur_attempt = 1 # Ensure that a workflow and a resource description have # been defined if not self._workflow: self._logger.error('No workflow assignedcurrently, please \ check your script') raise ree.MissingError(obj=self._uid, missing_attribute='workflow') if not self._rmgr: self._logger.error('No resource manager assigned currently, \ please create and add a valid resource \ manager') raise ree.MissingError(obj=self._uid, missing_attribute='resource_manager') self._prof.prof('amgr run started', uid=self._uid) # ensure rabbitmq setup self._setup_mqs() # Submit resource request if no resource allocation done till now or # resubmit a new one if the old one has completed res_alloc_state = self._rmgr.get_resource_allocation_state() if not res_alloc_state or \ res_alloc_state in self._rmgr.get_completed_states(): self._logger.info('Starting resource request submission') self._prof.prof('rreq_init', uid=self._uid) self._rmgr._submit_resource_request() res_alloc_state = self._rmgr.get_resource_allocation_state() if res_alloc_state in self._rmgr.get_completed_states(): raise ree.EnTKError(msg='Cannot proceed. Resource ' 'ended in state %s' % res_alloc_state) # Start all components and subcomponents self._start_all_comps() # Run workflow -- this call is blocking till all tasks of the # workflow are executed or an error/exception is encountered self._run_workflow() self._logger.info('Workflow execution finished.') if self._autoterminate: self._logger.debug('Autoterminate set to %s.' % self._autoterminate) self.terminate() except KeyboardInterrupt: self._logger.exception('Execution interrupted by user (you ' 'probably hit Ctrl+C), trying to cancel ' 'enqueuer thread gracefully...') self.terminate() raise KeyboardInterrupt except Exception: self._logger.exception('Error in AppManager') self.terminate() raise # return list of fetched output data, or None. outputs = self.outputs if outputs: ret = outputs return ret # -------------------------------------------------------------------------- # def terminate(self): self._prof.prof('term_start', uid=self._uid) # Terminate threads in following order: wfp, helper, synchronizer if self._wfp: self._logger.info('Terminating WFprocessor') self._wfp.terminate_processor() if self._task_manager: self._logger.info('Terminating task manager process') self._task_manager.terminate_manager() self._task_manager.terminate_heartbeat() if self._sync_thread: self._logger.info('Terminating synchronizer thread') self._terminate_sync.set() self._sync_thread.join() self._logger.info('Synchronizer thread terminated') if self._write_workflow: write_workflows(self.workflows, self._sid) if self._rmgr: self._rmgr._terminate_resource_request() if os.environ.get('RADICAL_ENTK_PROFILE'): write_session_description(self) if self._rmq_cleanup: self._cleanup_mqs() self._report.info('All components terminated\n') self._prof.prof('termination done', uid=self._uid) # -------------------------------------------------------------------------- # def resource_terminate(self): self._logger.warning('DeprecationWarning: `resource_terminate()` is ' 'deprecated, please use `terminate()`') self.terminate() # -------------------------------------------------------------------------- # # Private methods # def _setup_mqs(self): ''' **Purpose**: Setup RabbitMQ system on the client side. We instantiate queue(s) 'pendingq-*' for communication between the enqueuer thread and the task manager process. We instantiate queue(s) 'completedq-*' for communication between the task manager and dequeuer thread. We instantiate queue 'sync-to-master' for communication from enqueuer/dequeuer/task_manager to the synchronizer thread. We instantiate queue 'sync-ack' for communication from synchronizer thread to enqueuer/dequeuer/task_manager. Details: All queues are durable: Even if the RabbitMQ server goes down, the queues are saved to disk and can be retrieved. This also means that after an erroneous run the queues might still have unacknowledged messages and will contain messages from that run. Hence, in every new run, we first delete the queue and create a new one. ''' try: self._report.info('Setting up RabbitMQ system') if self._mqs_setup: self._report.ok('>>n/a\n') return self._report.ok('>>ok\n') self._prof.prof('mqs_setup_start', uid=self._uid) self._logger.debug('Setting up mq connection and channel') mq_connection = pika.BlockingConnection(self._rmq_conn_params) mq_channel = mq_connection.channel() self._logger.debug('Connection and channel setup successful') self._logger.debug('Setting up all exchanges and queues') qs = ['%s-tmgr-to-sync' % self._sid, '%s-cb-to-sync' % self._sid, '%s-sync-to-tmgr' % self._sid, '%s-sync-to-cb' % self._sid] for i in range(1, self._num_pending_qs + 1): queue_name = '%s-pendingq-%s' % (self._sid, i) self._pending_queue.append(queue_name) qs.append(queue_name) for i in range(1, self._num_completed_qs + 1): queue_name = '%s-completedq-%s' % (self._sid, i) self._completed_queue.append(queue_name) qs.append(queue_name) # f = open('.%s.txt' % self._sid, 'w') for q in qs: # Durable Qs will not be lost if rabbitmq server crashes mq_channel.queue_declare(queue=q) # f.write(q + '\n') # f.close() self._mqs_setup = True self._logger.debug('All exchanges and queues are setup') self._prof.prof('mqs_setup_stop', uid=self._uid) except Exception as ex: self._logger.exception('Error setting RabbitMQ system: %s' % ex) raise # -------------------------------------------------------------------------- # def _cleanup_mqs(self): try: self._prof.prof('mqs_cleanup_start', uid=self._uid) mq_connection = pika.BlockingConnection(self._rmq_conn_params) mq_channel = mq_connection.channel() mq_channel.queue_delete(queue='%s-tmgr-to-sync' % self._sid) mq_channel.queue_delete(queue='%s-cb-to-sync' % self._sid) mq_channel.queue_delete(queue='%s-sync-to-tmgr' % self._sid) mq_channel.queue_delete(queue='%s-sync-to-cb' % self._sid) for i in range(1, self._num_pending_qs + 1): queue_name = '%s-pendingq-%s' % (self._sid, i) mq_channel.queue_delete(queue=queue_name) for i in range(1, self._num_completed_qs + 1): queue_name = '%s-completedq-%s' % (self._sid, i) mq_channel.queue_delete(queue=queue_name) self._prof.prof('mqs_cleanup_stop', uid=self._uid) self._mqs_setup = False except Exception: self._logger.exception('Message queues not deleted, error') raise # -------------------------------------------------------------------------- # def _start_all_comps(self): if self._wfp: # This condition is called when there are multiple workflows # submitted for execution. Amgr.run() was probably called twice. # If a WFP exists, we use the same one but with the new workflow. # Since WFP (and its threads) and the Amgr share memory, we have # to terminate WFP's threads, assign the new workflow and then # start the threads again. self._wfp.terminate_processor() self._wfp._workflow = self._workflow self._wfp.start_processor() return # Create WFProcessor and initialize workflow its contents with # uids self._prof.prof('wfp_create_start', uid=self._uid) self._wfp = WFprocessor(sid=self._sid, workflow=self._workflow, pending_queue=self._pending_queue, completed_queue=self._completed_queue, resubmit_failed=self._resubmit_failed, rmq_conn_params=self._rmq_conn_params) self._prof.prof('wfp_create_stop', uid=self._uid) # Start synchronizer thread AM OK if not self._sync_thread: self._logger.info('Starting synchronizer thread') self._sync_thread = mt.Thread(target=self._synchronizer, name='synchronizer-thread') self._prof.prof('sync_thread_create', uid=self._uid) self._sync_thread.start() # Start WFprocessor self._logger.info('Starting WFProcessor') self._wfp.start_processor() self._report.ok('All components created\n') # Create tmgr object only if it does not already exist if self._rts == 'radical.pilot': from radical.entk.execman.rp import TaskManager elif self._rts == 'mock': from radical.entk.execman.mock import TaskManager if not self._task_manager: self._logger.info('Starting task manager') self._prof.prof('tmgr_create_start', uid=self._uid) self._task_manager = TaskManager( sid=self._sid, pending_queue=self._pending_queue, completed_queue=self._completed_queue, rmgr=self._rmgr, rmq_conn_params=self._rmq_conn_params) self._task_manager.start_manager() self._task_manager.start_heartbeat() self._prof.prof('tmgr_create_stop', uid=self._uid) # -------------------------------------------------------------------------- # def _run_workflow(self): active_pipe_count = len(self._workflow) finished_pipe_uids = list() # We wait till all pipelines of the workflow are marked # complete state = self._rmgr.get_resource_allocation_state() final = self._rmgr.get_completed_states() incomplete = self._wfp.workflow_incomplete() while active_pipe_count and \ incomplete and \ state not in final: state = self._rmgr.get_resource_allocation_state() for pipe in self._workflow: with pipe.lock: if pipe.completed and \ pipe.uid not in finished_pipe_uids: finished_pipe_uids.append(pipe.uid) active_pipe_count -= 1 self._logger.info('Pipe %s completed' % pipe.uid) self._logger.info('Active pipes %s' % active_pipe_count) if not self._sync_thread.is_alive() and \ self._cur_attempt <= self._reattempts: self._sync_thread = mt.Thread(target=self._synchronizer, name='synchronizer-thread') self._sync_thread.start() self._cur_attempt += 1 self._prof.prof('sync_thread_restart', uid=self._uid) self._logger.info('Restarting synchronizer thread') if not self._wfp.check_processor() and \ self._cur_attempt <= self._reattempts: # If WFP dies, both child threads are also cleaned out. # We simply recreate the wfp object with a copy of the # workflow in the appmanager and start the processor. self._prof.prof('wfp_recreate', uid=self._uid) self._wfp = WFprocessor(sid=self._sid, workflow=self._workflow, pending_queue=self._pending_queue, completed_queue=self._completed_queue, resubmit_failed=self._resubmit_failed, rmq_conn_params=self._rmq_conn_params) self._logger.info('Restarting WFProcessor') self._wfp.start_processor() self._cur_attempt += 1 if not self._task_manager.check_heartbeat() and \ self._cur_attempt <= self._reattempts: # If the tmgr process or heartbeat dies, we simply start a # new process using the start_manager method. We do not # need to create a new instance of the TaskManager object # itself. We stop and start a new instance of the # heartbeat thread as well. self._prof.prof('restart_tmgr', uid=self._uid) self._logger.info('Terminating heartbeat thread') self._task_manager.terminate_heartbeat() self._logger.info('Terminating tmgr process') self._task_manager.terminate_manager() self._logger.info('Restarting task manager process') self._task_manager.start_manager() self._logger.info('Restarting heartbeat thread') self._task_manager.start_heartbeat() self._cur_attempt += 1 # -------------------------------------------------------------------------- # def _get_message_to_sync(self, mq_channel, qname): ''' Reads a message from the queue, and exchange the message to where it was published by `update_task` ''' # -------------------------------------------------------------- # Messages between tmgr Main thread and synchronizer -- only # Task objects method_frame, props, body = mq_channel.basic_get(queue=qname) tmp = qname.split("-") q_sid = ''.join(tmp[:-3]) q_from = tmp[-3] q_to = tmp[-1] return_queue_name = f"{q_sid}-{q_to}-to-{q_from}" # The message received is a JSON object with the following # structure: # msg = { # 'type': 'Pipeline'/'Stage'/'Task', # 'object': json/dict # } if body: msg = json.loads(body) uid = msg['object']['uid'] state = msg['object']['state'] self._prof.prof('sync_recv_obj_state_%s' % state, uid=uid) self._logger.debug('recv %s in state %s (sync)' % (uid, state)) if msg['type'] == 'Task': self._update_task(msg, return_queue_name, props.correlation_id, mq_channel, method_frame) # -------------------------------------------------------------------------- # def _update_task(self, msg, reply_to, corr_id, mq_channel, method_frame): # pylint: disable=W0612,W0613 completed_task = Task() completed_task.from_dict(msg['object']) self._logger.info('Received %s with state %s' % (completed_task.uid, completed_task.state)) # found_task = False # Traverse the entire workflow to find the correct task for pipe in self._workflow: with pipe.lock: if pipe.completed or \ pipe.uid != completed_task.parent_pipeline['uid']: continue for stage in pipe.stages: if stage.uid != completed_task.parent_stage['uid']: continue for task in stage.tasks: if completed_task.uid != task.uid or \ completed_task.state == task.state: continue self._logger.debug(('Found task %s in state (%s)' ' changing to %s ==') % (task.uid, task.state, completed_task.state)) if task.state in [states.DONE, states.FAILED]: self._logger.debug(('No change on task state %s ' 'in state %s') % (task.uid, task.state)) break task.state = str(completed_task.state) self._logger.debug('Found task %s in state %s' % (task.uid, task.state)) if completed_task.path: task.path = str(completed_task.path) # mq_channel.basic_publish( # exchange='', # routing_key=reply_to, # properties=pika.BasicProperties( # correlation_id=corr_id), # body='%s-ack' % task.uid) state = msg['object']['state'] self._prof.prof('pub_ack_state_%s' % state, uid=msg['object']['uid']) mq_channel.basic_ack( delivery_tag=method_frame.delivery_tag) self._report.ok('Update: ') self._report.info('%s state: %s\n' % (task.luid, task.state)) # found_task = True break # if not found_task: # # # If there was a Stage update, but the Stage was # # not found in any of the Pipelines. This # # means that this was a Stage that was added # # during runtime and the AppManager does not # # know about it. The current solution is going # # to be: add it to the workflow object in the # # AppManager via the synchronizer. # # self._logger.info('Adding new task %s to \ # parent stage: %s' # % (completed_task.uid, # stage.uid)) # # self._prof.prof('adap_add_task_start', # uid=completed_task.uid) # stage.add_tasks(completed_task) # self._prof.prof('adap_add_task_stop', # uid=completed_task.uid) # # mq_channel.basic_publish(exchange='', # routing_key=reply_to, # properties=pika.BasicProperties( # correlation_id=corr_id), # body='%s-ack' % completed_task.uid) # # self._prof.prof('pub_ack_state_%s' % # msg['object']['state'], # uid=msg['object']['uid']) # # mq_channel.basic_ack( # delivery_tag=method_frame.delivery_tag) # self._report.ok('Update: ') # self._report.info('%s state: %s\n' % # (completed_task.luid, completed_task.state)) # -------------------------------------------------------------------------- # def _synchronizer(self): try: self._synchronizer_work() except KeyboardInterrupt: self._logger.exception('Execution interrupted by user (you \ probably hit Ctrl+C), trying to terminate \ synchronizer thread gracefully...') raise except Exception: self._logger.exception('Unknown error in synchronizer: %s. \ Terminating thread') raise # -------------------------------------------------------------------------- # def _synchronizer_work(self): ''' **Purpose**: Thread in the master process to keep the workflow data structure in appmanager up to date. We receive only tasks objects from the task manager. Details: Important to note that acknowledgements of the type `channel.basic_ack()` is an acknowledgement to the server that the msg was received. This is not to be confused with the Ack sent to the task_manager through the sync-ack queue. ''' self._prof.prof('sync_thread_start', uid=self._uid) self._logger.info('synchronizer thread started') mq_connection = pika.BlockingConnection(self._rmq_conn_params) mq_channel = mq_connection.channel() last = time.time() qname_t2s = '%s-tmgr-to-sync' % self._sid qname_c2s = '%s-cb-to-sync' % self._sid while not self._terminate_sync.is_set(): # wrapper to call `_update_task()` self._get_message_to_sync(mq_channel, qname_t2s) self._get_message_to_sync(mq_channel, qname_c2s) # Appease pika cos it thinks the connection is dead now = time.time() if now - last >= self._rmq_ping_interval: mq_connection.process_data_events() last = now self._prof.prof('sync_thread_stop', uid=self._uid) # ------------------------------------------------------------------------------ # pylint: disable=protected-access
37.134021
84
0.519517
795a6ec13f109723129ae258c0a06b9ca5b440c9
13,013
py
Python
Gems/Blast/Editor/Scripts/asset_builder_blast.py
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/Blast/Editor/Scripts/asset_builder_blast.py
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Blast/Editor/Scripts/asset_builder_blast.py
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ def install_user_site(): import os import sys import azlmbr.paths executableBinFolder = azlmbr.paths.executableFolder # the PyAssImp module checks the Windows PATH for the assimp DLL file if os.name == "nt": os.environ['PATH'] = os.environ['PATH'] + os.pathsep + executableBinFolder # PyAssImp module needs to find the shared library for assimp to load; "posix" handles Mac and Linux if os.name == "posix": if 'LD_LIBRARY_PATH' in os.environ: os.environ['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH'] + os.pathsep + executableBinFolder else: os.environ['LD_LIBRARY_PATH'] = executableBinFolder # add the user site packages folder to find the pyassimp egg link import site for item in sys.path: if (item.find('site-packages') != -1): site.addsitedir(item) install_user_site() import pyassimp import azlmbr.asset import azlmbr.asset.builder import azlmbr.asset.entity import azlmbr.blast import azlmbr.bus as bus import azlmbr.editor as editor import azlmbr.entity import azlmbr.math import os import traceback import binascii import sys # the UUID must be unique amongst all the asset builders in Python or otherwise # a collision of builders will happen preventing one from running busIdString = '{CF5C74D1-9ED4-4851-85B1-9B15090DBEC7}' busId = azlmbr.math.Uuid_CreateString(busIdString, 0) handler = None jobKeyName = 'Blast Chunk Assets' sceneManifestType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) dccMaterialType = azlmbr.math.Uuid_CreateString('{C88469CF-21E7-41EB-96FD-BF14FBB05EDC}', 0) def log_exception_traceback(): exc_type, exc_value, exc_tb = sys.exc_info() data = traceback.format_exception(exc_type, exc_value, exc_tb) print(str(data)) def get_source_fbx_filename(request): fullPath = os.path.join(request.watchFolder, request.sourceFile) basePath, filePart = os.path.split(fullPath) filename = os.path.splitext(filePart)[0] + '.fbx' filename = os.path.join(basePath, filename) return filename def raise_error(message): raise RuntimeError(f'[ERROR]: {message}') def generate_asset_info(chunkNames, request): import azlmbr.blast # write out an object stream with the extension of .fbx.assetinfo.generated basePath, sceneFile = os.path.split(request.sourceFile) assetinfoFilename = os.path.splitext(sceneFile)[0] + '.fbx.assetinfo.generated' assetinfoFilename = os.path.join(basePath, assetinfoFilename) assetinfoFilename = assetinfoFilename.replace('\\', '/').lower() outputFilename = os.path.join(request.tempDirPath, assetinfoFilename) storage = azlmbr.blast.BlastSliceAssetStorageComponent() if (storage.GenerateAssetInfo(chunkNames, request.sourceFile, outputFilename)): product = azlmbr.asset.builder.JobProduct(assetinfoFilename, sceneManifestType, 1) product.dependenciesHandled = True return product raise_error('Failed to generate assetinfo.generated') def export_fbx_manifest(request): output = [] fbxFilename = get_source_fbx_filename(request) sceneAsset = pyassimp.load(fbxFilename) with sceneAsset as scene: rootNode = scene.mRootNode.contents for index in range(0, rootNode.mNumChildren): child = rootNode.mChildren[index] childNode = child.contents childNodeName = bytes.decode(childNode.mName.data) output.append(str(childNodeName)) return output def convert_to_asset_paths(fbxFilename, gameRoot, chunkNameList): realtivePath = fbxFilename[len(gameRoot) + 1:] realtivePath = os.path.splitext(realtivePath)[0] output = [] for chunk in chunkNameList: assetPath = realtivePath + '-' + chunk + '.cgf' assetPath = assetPath.replace('\\', '/') assetPath = assetPath.lower() output.append(assetPath) return output # creates a single job to compile for each platform def create_jobs(request): fbxSidecarFilename = get_source_fbx_filename(request) if (os.path.exists(fbxSidecarFilename) is False): print('[WARN] Sidecar FBX file {} is missing for blast file {}'.format(fbxSidecarFilename, request.sourceFile)) return azlmbr.asset.builder.CreateJobsResponse() # see if the FBX file already has a .assetinfo source asset, if so then do not create a job if (os.path.exists(f'{fbxSidecarFilename}.assetinfo')): response = azlmbr.asset.builder.CreateJobsResponse() response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess return response # create job descriptor for each platform jobDescriptorList = [] for platformInfo in request.enabledPlatforms: jobDesc = azlmbr.asset.builder.JobDescriptor() jobDesc.jobKey = jobKeyName jobDesc.priority = 12 # higher than the 'Scene compilation' or 'fbx' jobDesc.set_platform_identifier(platformInfo.identifier) jobDescriptorList.append(jobDesc) response = azlmbr.asset.builder.CreateJobsResponse() response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess response.createJobOutputs = jobDescriptorList return response # handler to create jobs for a source asset def on_create_jobs(args): try: request = args[0] return create_jobs(request) except: log_exception_traceback() return azlmbr.asset.builder.CreateJobsResponse() def generate_blast_slice_asset(chunkNameList, request): # get list of relative chunk paths fbxFilename = get_source_fbx_filename(request) assetPaths = convert_to_asset_paths(fbxFilename, request.watchFolder, chunkNameList) outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'CreateEditorEntity', 'BlastData') if (outcome.IsSuccess() is False): raise_error('could not create an editor entity') blastDataEntityId = outcome.GetValue() # create a component for the editor entity gameType = azlmbr.entity.EntityType().Game blastMeshDataTypeIdList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Blast Slice Storage Component"], gameType) componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', blastDataEntityId, blastMeshDataTypeIdList[0]) if (componentOutcome.IsSuccess() is False): raise_error('failed to add component (Blast Slice Storage Component) to the blast_slice') # build the blast slice using the chunk asset paths blastMeshComponentId = componentOutcome.GetValue()[0] outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'BuildComponentPropertyTreeEditor', blastMeshComponentId) if(outcome.IsSuccess() is False): raise_error(f'failed to create Property Tree Editor for component ({blastMeshComponentId})') pte = outcome.GetValue() pte.set_visible_enforcement(True) pte.set_value('Mesh Paths', assetPaths) # write out an object stream with the extension of .blast_slice basePath, sceneFile = os.path.split(request.sourceFile) blastFilename = os.path.splitext(sceneFile)[0] + '.blast_slice' blastFilename = os.path.join(basePath, blastFilename) blastFilename = blastFilename.replace('\\', '/').lower() tempFilename = os.path.join(request.tempDirPath, blastFilename) entityList = [blastDataEntityId] makeDynamic = False outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'WriteSliceFile', tempFilename, entityList, makeDynamic) if (outcome.IsSuccess() is False): raise_error(f'WriteSliceFile failed for blast_slice file ({blastFilename})') # return a job product blastSliceAsset = azlmbr.blast.BlastSliceAsset() subId = binascii.crc32(blastFilename.encode('utf8')) product = azlmbr.asset.builder.JobProduct(blastFilename, blastSliceAsset.GetAssetTypeId(), subId) product.dependenciesHandled = True return product def read_in_string(data, dataLength): stringData = '' for idx in range(4, dataLength - 1): char = bytes.decode(data[idx]) if (str.isascii(char)): stringData += char return stringData def import_material_info(fbxFilename): _, group_name = os.path.split(fbxFilename) group_name = os.path.splitext(group_name)[0] output = {} output['group_name'] = group_name output['material_name_list'] = [] sceneAsset = pyassimp.load(fbxFilename) with sceneAsset as scene: for materialIndex in range(0, scene.mNumMaterials): material = scene.mMaterials[materialIndex].contents for materialPropertyIdx in range(0, material.mNumProperties): materialProperty = material.mProperties[materialPropertyIdx].contents materialPropertyName = bytes.decode(materialProperty.mKey.data) if (materialPropertyName.endswith('mat.name') and materialProperty.mType is 3): stringData = read_in_string(materialProperty.mData, materialProperty.mDataLength) output['material_name_list'].append(stringData) return output def write_material_file(sourceFile, destFolder): # preserve source MTL files rootPath, materialSourceFile = os.path.split(sourceFile) materialSourceFile = os.path.splitext(materialSourceFile)[0] + '.mtl' materialSourceFile = os.path.join(rootPath, materialSourceFile) if (os.path.exists(materialSourceFile)): print(f'{materialSourceFile} source already exists') return None # auto-generate a DCC material file info = import_material_info(sourceFile) materialGroupName = info['group_name'] materialNames = info['material_name_list'] materialFilename = materialGroupName + '.dccmtl.generated' subId = binascii.crc32(materialFilename.encode('utf8')) materialFilename = os.path.join(destFolder, materialFilename) storage = azlmbr.blast.BlastSliceAssetStorageComponent() storage.WriteMaterialFile(materialGroupName, materialNames, materialFilename) product = azlmbr.asset.builder.JobProduct(materialFilename, dccMaterialType, subId) product.dependenciesHandled = True return product def process_fbx_file(request): # fill out response object response = azlmbr.asset.builder.ProcessJobResponse() productOutputs = [] # write out DCCMTL file as a product (if needed) materialProduct = write_material_file(get_source_fbx_filename(request), request.tempDirPath) if (materialProduct is not None): productOutputs.append(materialProduct) # prepare output folder basePath, _ = os.path.split(request.sourceFile) outputPath = os.path.join(request.tempDirPath, basePath) os.makedirs(outputPath) # parse FBX for chunk names chunkNameList = export_fbx_manifest(request) # create assetinfo generated (is product) productOutputs.append(generate_asset_info(chunkNameList, request)) # write out the blast_slice object stream productOutputs.append(generate_blast_slice_asset(chunkNameList, request)) response.outputProducts = productOutputs response.resultCode = azlmbr.asset.builder.ProcessJobResponse_Success response.dependenciesHandled = True return response # using the incoming 'request' find the type of job via 'jobKey' to determine what to do def on_process_job(args): try: request = args[0] if (request.jobDescription.jobKey.startswith(jobKeyName)): return process_fbx_file(request) return azlmbr.asset.builder.ProcessJobResponse() except: log_exception_traceback() return azlmbr.asset.builder.ProcessJobResponse() # register asset builder def register_asset_builder(): assetPattern = azlmbr.asset.builder.AssetBuilderPattern() assetPattern.pattern = '*.blast' assetPattern.type = azlmbr.asset.builder.AssetBuilderPattern_Wildcard builderDescriptor = azlmbr.asset.builder.AssetBuilderDesc() builderDescriptor.name = "Blast Gem" builderDescriptor.patterns = [assetPattern] builderDescriptor.busId = busId builderDescriptor.version = 5 outcome = azlmbr.asset.builder.PythonAssetBuilderRequestBus(azlmbr.bus.Broadcast, 'RegisterAssetBuilder', builderDescriptor) if outcome.IsSuccess(): # created the asset builder to hook into the notification bus handler = azlmbr.asset.builder.PythonBuilderNotificationBusHandler() handler.connect(busId) handler.add_callback('OnCreateJobsRequest', on_create_jobs) handler.add_callback('OnProcessJobRequest', on_process_job) return handler # create the asset builder handler try: handler = register_asset_builder() except: handler = None log_exception_traceback()
40.287926
155
0.732729
795a6feb6ab04afaebecc44660c2ba6b73e7832c
1,419
py
Python
src/home/views.py
miguelaav/dev
5ade9d0b393f48c9cc3b160b6ede4a03c29addea
[ "bzip2-1.0.6" ]
null
null
null
src/home/views.py
miguelaav/dev
5ade9d0b393f48c9cc3b160b6ede4a03c29addea
[ "bzip2-1.0.6" ]
6
2020-06-05T20:02:33.000Z
2022-03-11T23:43:11.000Z
src/home/views.py
miguelaav/dev
5ade9d0b393f48c9cc3b160b6ede4a03c29addea
[ "bzip2-1.0.6" ]
null
null
null
from django.shortcuts import render from django.views import View from django.views.generic import ListView from menuResponse.models import MenuResponseModel from menu.models import MenuCreateModel # Vista HomeView # Descripción: Procesa la vista del Home mostrando el listado de peticiones realizadas al menu del dia # Parametros: UUID del menu class HomeView(ListView): template_name = 'home/home_list.html' queryset = MenuResponseModel.objects.all() # Se modifica el contexto para incorporar el UUID del menu # Se ejecuta consulta de menus creados para llenar selector def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) querysetMenuCreate = MenuCreateModel.objects.all() context['menuCreate'] = querysetMenuCreate context['menuCreateId'] = '0' return context # En submit se ejecuta consulta inner join para obtener los responses de usuarios en el menu # del dia en particular def post(self, request, *args, **kwargs): menuCreateId = request.POST.get('selectMenuCreate') querysetMenuCreate = MenuCreateModel.objects.all() queryset = MenuResponseModel.objects.select_related('option').filter(MenuID=menuCreateId).values('userName','comments','option__description') context = { "object_list" : queryset, "menuCreate" : querysetMenuCreate, "menuCreateId" : menuCreateId } return render(request, self.template_name, context)
34.609756
145
0.768147
795a702c2ad40be966ea5b7785d20db55a49914d
6,669
py
Python
bindings/python/ensmallen_graph/datasets/string/methylophagafrappieri.py
caufieldjh/ensmallen_graph
14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a
[ "MIT" ]
null
null
null
bindings/python/ensmallen_graph/datasets/string/methylophagafrappieri.py
caufieldjh/ensmallen_graph
14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a
[ "MIT" ]
null
null
null
bindings/python/ensmallen_graph/datasets/string/methylophagafrappieri.py
caufieldjh/ensmallen_graph
14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a
[ "MIT" ]
null
null
null
""" This file offers the methods to automatically retrieve the graph Methylophaga frappieri. The graph is automatically retrieved from the STRING repository. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime: 2021-02-02 21:40:43.671706 The undirected graph Methylophaga frappieri has 2609 nodes and 185932 weighted edges, of which none are self-loops. The graph is dense as it has a density of 0.05465 and has 9 connected components, where the component with most nodes has 2579 nodes and the component with the least nodes has 2 nodes. The graph median node degree is 126, the mean node degree is 142.53, and the node degree mode is 4. The top 5 most central nodes are 754477.Q7C_2234 (degree 1020), 754477.Q7C_546 (degree 826), 754477.Q7C_253 (degree 795), 754477.Q7C_1511 (degree 743) and 754477.Q7C_580 (degree 700). References --------------------- Please cite the following if you use the data: @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } Usage example ---------------------- The usage of this graph is relatively straightforward: .. code:: python # First import the function to retrieve the graph from the datasets from ensmallen_graph.datasets.string import MethylophagaFrappieri # Then load the graph graph = MethylophagaFrappieri() # Finally, you can do anything with it, for instance, compute its report: print(graph) # If you need to run a link prediction task with validation, # you can split the graph using a connected holdout as follows: train_graph, validation_graph = graph.connected_holdout( # You can use an 80/20 split the holdout, for example. train_size=0.8, # The random state is used to reproduce the holdout. random_state=42, # Wether to show a loading bar. verbose=True ) # Remember that, if you need, you can enable the memory-time trade-offs: train_graph.enable( vector_sources=True, vector_destinations=True, vector_outbounds=True ) # Consider using the methods made available in the Embiggen package # to run graph embedding or link prediction tasks. """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen_graph import EnsmallenGraph # pylint: disable=import-error def MethylophagaFrappieri( directed: bool = False, verbose: int = 2, cache_path: str = "graphs/string", **additional_graph_kwargs: Dict ) -> EnsmallenGraph: """Return new instance of the Methylophaga frappieri graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False, Wether to load the graph as directed or undirected. By default false. verbose: int = 2, Wether to show loading bars during the retrieval and building of the graph. cache_path: str = "graphs", Where to store the downloaded graphs. additional_graph_kwargs: Dict, Additional graph kwargs. Returns ----------------------- Instace of Methylophaga frappieri graph. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime: 2021-02-02 21:40:43.671706 The undirected graph Methylophaga frappieri has 2609 nodes and 185932 weighted edges, of which none are self-loops. The graph is dense as it has a density of 0.05465 and has 9 connected components, where the component with most nodes has 2579 nodes and the component with the least nodes has 2 nodes. The graph median node degree is 126, the mean node degree is 142.53, and the node degree mode is 4. The top 5 most central nodes are 754477.Q7C_2234 (degree 1020), 754477.Q7C_546 (degree 826), 754477.Q7C_253 (degree 795), 754477.Q7C_1511 (degree 743) and 754477.Q7C_580 (degree 700). References --------------------- Please cite the following if you use the data: @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } Usage example ---------------------- The usage of this graph is relatively straightforward: .. code:: python # First import the function to retrieve the graph from the datasets from ensmallen_graph.datasets.string import MethylophagaFrappieri # Then load the graph graph = MethylophagaFrappieri() # Finally, you can do anything with it, for instance, compute its report: print(graph) # If you need to run a link prediction task with validation, # you can split the graph using a connected holdout as follows: train_graph, validation_graph = graph.connected_holdout( # You can use an 80/20 split the holdout, for example. train_size=0.8, # The random state is used to reproduce the holdout. random_state=42, # Wether to show a loading bar. verbose=True ) # Remember that, if you need, you can enable the memory-time trade-offs: train_graph.enable( vector_sources=True, vector_destinations=True, vector_outbounds=True ) # Consider using the methods made available in the Embiggen package # to run graph embedding or link prediction tasks. """ return AutomaticallyRetrievedGraph( graph_name="MethylophagaFrappieri", dataset="string", directed=directed, verbose=verbose, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
35.285714
223
0.702954