text
stringlengths
28
881k
"""Fixes for CESM2-WACCM model."""NEWLINEfrom netCDF4 import DatasetNEWLINENEWLINEfrom .cesm2 import Cl as BaseClNEWLINEfrom .cesm2 import Fgco2 as BaseFgco2NEWLINEfrom .cesm2 import Tas as BaseTasNEWLINEfrom ..common import SiconcFixScalarCoordNEWLINENEWLINENEWLINEclass Cl(BaseCl):NEWLINE """Fixes for cl."""NEWLINENEWLINE def fix_file(self, filepath, output_dir):NEWLINE """Fix hybrid pressure coordinate.NEWLINENEWLINE Adds missing ``formula_terms`` attribute to file.NEWLINENEWLINE NoteNEWLINE ----NEWLINE Fixing this with :mod:`iris` in ``fix_metadata`` or ``fix_data`` isNEWLINE **not** possible, since the bounds of the vertical coordinates ``a``NEWLINE and ``b`` are not present in the loaded :class:`iris.cube.CubeList`,NEWLINE even when :func:`iris.load_raw` is used.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE filepath : strNEWLINE Path to the original file.NEWLINE output_dir : strNEWLINE Path of the directory where the fixed file is saved to.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE strNEWLINE Path to the fixed file.NEWLINENEWLINE """NEWLINE new_path = self._fix_formula_terms(filepath, output_dir)NEWLINE dataset = Dataset(new_path, mode='a')NEWLINE dataset.variables['a_bnds'][:] = dataset.variables['a_bnds'][:, ::-1]NEWLINE dataset.variables['b_bnds'][:] = dataset.variables['b_bnds'][:, ::-1]NEWLINE dataset.close()NEWLINE return new_pathNEWLINENEWLINENEWLINECli = ClNEWLINENEWLINENEWLINEClw = ClNEWLINENEWLINENEWLINEFgco2 = BaseFgco2NEWLINENEWLINENEWLINESiconc = SiconcFixScalarCoordNEWLINENEWLINENEWLINETas = BaseTasNEWLINE
#!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINEfrom PyQt5 import QtWidgets, QtCoreNEWLINEfrom PyQt5.Qt import QTreeWidgetNEWLINEfrom src.gui.sharedcomnponets.sharedcomponets import GUIToolKitNEWLINEfrom src.simpleFOCConnector import SimpleFOCDeviceNEWLINEfrom src.simpleFOCConnector import CommandNEWLINENEWLINEclass DeviceTreeView(QTreeWidget):NEWLINE def __init__(self, parent=None):NEWLINE super().__init__(parent)NEWLINENEWLINE self.device = SimpleFOCDevice.getInstance()NEWLINENEWLINE self.sFOCDevice = QtWidgets.QTreeWidgetItem(self)NEWLINE self.sFOCDevice.setText(0, 'sFOC 设备')NEWLINE self.sFOCDevice.setIcon(0, GUIToolKit.getIconByName('motor'))NEWLINENEWLINE self.setColumnCount(2)NEWLINENEWLINE self.motionControl = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.motionControl.setText(0, '运动控制设置')NEWLINE self.motionControl.setIcon(0, GUIToolKit.getIconByName('pidconfig'))NEWLINE self.sFOCDevice.addChild(self.motionControl)NEWLINE NEWLINE self.controller = QtWidgets.QTreeWidgetItem(self.motionControl)NEWLINE self.controller.setText(0, '运动控制类型')NEWLINE self.controller.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.selectorControlLoop = QtWidgets.QComboBox(self)NEWLINE self.selectorControlLoop.addItems(['力矩控制', '速度控制', '角度控制', '速度开环控制', '角度开环控制'])NEWLINE self.selectorControlLoop.currentIndexChanged.connect(self.changeControlLoop)NEWLINE self.setItemWidget(self.controller,1,self.selectorControlLoop)NEWLINENEWLINE self.torque = QtWidgets.QTreeWidgetItem(self.motionControl)NEWLINE self.torque.setText(0, '力矩控制类型')NEWLINE self.torque.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.selectorTorque = QtWidgets.QComboBox(self)NEWLINE self.selectorTorque.addItems(['电压', 'DC电流', 'FOC电流'])NEWLINE self.selectorTorque.currentIndexChanged.connect(self.changeTorque)NEWLINE self.setItemWidget(self.torque,1,self.selectorTorque)NEWLINE NEWLINE self.motionDownsample = QtWidgets.QTreeWidgetItem(self.motionControl)NEWLINE self.motionDownsample.setText(0, '运动控制频率降采样')NEWLINE self.motionDownsample.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.motionDownsample.setText(1, '')NEWLINE self.motionDownsample.setFlags(NEWLINE self.motionDownsample.flags() | QtCore.Qt.ItemIsEditable)NEWLINE NEWLINE self.PIDVelocityConfig = self.addPIDSubtree(self.motionControl,'速度 PID')NEWLINE self.PIDAngleConfig = self.addPIDSubtree(self.motionControl,'角度 PID')NEWLINE self.PIDCurrentQConfig = self.addPIDSubtree(self.motionControl,'电流q PID')NEWLINE self.PIDCurrentDConfig = self.addPIDSubtree(self.motionControl,'电流d PID')NEWLINENEWLINE self.limitsConfig = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.limitsConfig.setText(0, '限幅')NEWLINE self.limitsConfig.setIcon(0, GUIToolKit.getIconByName('statistics'))NEWLINE self.sFOCDevice.addChild(self.limitsConfig)NEWLINENEWLINE self.velocityLimit = QtWidgets.QTreeWidgetItem(self.limitsConfig)NEWLINE self.velocityLimit.setText(0, '速度限幅')NEWLINE self.velocityLimit.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.velocityLimit.setText(1, '')NEWLINE self.velocityLimit.setFlags(NEWLINE self.velocityLimit.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.voltageLimit = QtWidgets.QTreeWidgetItem(self.limitsConfig)NEWLINE self.voltageLimit.setText(0, '电压限幅')NEWLINE self.voltageLimit.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.voltageLimit.setText(1, '')NEWLINE self.voltageLimit.setFlags(NEWLINE self.voltageLimit.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.currentLimit = QtWidgets.QTreeWidgetItem(self.limitsConfig)NEWLINE self.currentLimit.setText(0, '电流限幅')NEWLINE self.currentLimit.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.currentLimit.setText(1, '')NEWLINE self.currentLimit.setFlags(NEWLINE self.currentLimit.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.statesConfig = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.statesConfig.setText(0, '状态')NEWLINE self.statesConfig.setIcon(0, GUIToolKit.getIconByName('statistics'))NEWLINE self.sFOCDevice.addChild(self.statesConfig)NEWLINENEWLINE self.satateTarget = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.satateTarget.setText(0, '目标')NEWLINE self.satateTarget.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.satateTarget.setText(1, '')NEWLINENEWLINE self.stateVq = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateVq.setText(0, '电压 q')NEWLINE self.stateVq.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.stateVd = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateVd.setText(0, '电压 d')NEWLINE self.stateVd.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINENEWLINE self.stateCq = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateCq.setText(0, '电流 q')NEWLINE self.stateCq.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.stateCd = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateCd.setText(0, '电流 d')NEWLINE self.stateCd.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINENEWLINE self.stateVel = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateVel.setText(0, '速度')NEWLINE self.stateVel.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.stateVel.setText(1, '')NEWLINENEWLINE self.stateAngle = QtWidgets.QTreeWidgetItem(self.statesConfig)NEWLINE self.stateAngle.setText(0, '角度')NEWLINE self.stateAngle.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.stateAngle.setText(1, '')NEWLINENEWLINE self.sensorConfig = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.sensorConfig.setText(0, '位置传感器设置')NEWLINE self.sensorConfig.setIcon(0, GUIToolKit.getIconByName('sensor'))NEWLINE self.sFOCDevice.addChild(self.sensorConfig)NEWLINENEWLINE self.sensorZeroOffset = QtWidgets.QTreeWidgetItem(self.sensorConfig)NEWLINE self.sensorZeroOffset.setText(0, '零点偏置')NEWLINE self.sensorZeroOffset.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.sensorZeroOffset.setText(1, '')NEWLINE self.sensorZeroOffset.setFlags(NEWLINE self.sensorZeroOffset.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.sensorZeroElecOffset = QtWidgets.QTreeWidgetItem(self.sensorConfig)NEWLINE self.sensorZeroElecOffset.setText(0, '电气零点偏置')NEWLINE self.sensorZeroElecOffset.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.sensorZeroElecOffset.setText(1, '')NEWLINE self.sensorZeroElecOffset.setFlags(NEWLINE self.sensorZeroElecOffset.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.generalSettings = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.generalSettings.setText(0, '通用设置')NEWLINE self.generalSettings.setIcon(0, GUIToolKit.getIconByName('generalsettings'))NEWLINE self.sFOCDevice.addChild(self.generalSettings)NEWLINENEWLINE self.phaseRes = QtWidgets.QTreeWidgetItem(self.generalSettings)NEWLINE self.phaseRes.setText(0, '相电阻')NEWLINE self.phaseRes.setIcon(0, GUIToolKit.getIconByName('res'))NEWLINE self.phaseRes.setText(1, '')NEWLINE self.phaseRes.setFlags(NEWLINE self.phaseRes.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE self.deviceStatus = QtWidgets.QTreeWidgetItem(self.generalSettings)NEWLINE self.deviceStatus.setText(0, '电机状态')NEWLINE self.deviceStatus.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.selectStatus = QtWidgets.QComboBox(self)NEWLINE self.selectStatus.addItems(['失能', '使能'])NEWLINE self.selectStatus.currentIndexChanged.connect(self.changeStatus)NEWLINE self.setItemWidget(self.deviceStatus,1,self.selectStatus)NEWLINENEWLINE self.modulationType = QtWidgets.QTreeWidgetItem(self.generalSettings)NEWLINE self.modulationType.setText(0, 'PWM调制')NEWLINE self.modulationType.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.selectModulation = QtWidgets.QComboBox(self)NEWLINE self.selectModulation.addItems(['正弦PWM调制', '空间矢量PWM调制', '梯形调制 120', '梯形调制 150'])NEWLINE self.selectModulation.currentIndexChanged.connect(self.changeModType)NEWLINE self.setItemWidget(self.modulationType,1,self.selectModulation)NEWLINENEWLINE self.modulationCenter = QtWidgets.QTreeWidgetItem(self.generalSettings)NEWLINE self.modulationCenter.setText(0, 'Modulation center')NEWLINE self.modulationCenter.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE self.selectModCenter = QtWidgets.QComboBox(self)NEWLINE self.selectModCenter.addItems(['Disabled', 'Enabled'])NEWLINE self.selectModCenter.currentIndexChanged.connect(self.changeModCenter)NEWLINE self.setItemWidget(self.modulationCenter,1,self.selectModCenter)NEWLINENEWLINE self.customComands = QtWidgets.QTreeWidgetItem(self.sFOCDevice)NEWLINE self.customComands.setText(0, 'Custom commands')NEWLINE self.customComands.setIcon(0, GUIToolKit.getIconByName('customcommands'))NEWLINE self.sFOCDevice.addChild(self.customComands)NEWLINENEWLINE for customCommand in self.device.customCommands.customCommandsList:NEWLINE self.initCustomCommand(customCommand)NEWLINENEWLINE self.installEventFilter(self)NEWLINE self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)NEWLINE self.customContextMenuRequested.connect(self.customCommandsMenu)NEWLINENEWLINE self.header().resizeSection(0,230)NEWLINENEWLINE self.setAlternatingRowColors(True)NEWLINE self.header().hide()NEWLINE self.expandItem(self.sFOCDevice)NEWLINE self.expandItem(self.motionControl)NEWLINENEWLINE self.device.addConnectionStateListener(self)NEWLINE self.device.commProvider.commandDataReceived.connect(self.commandResponseReceived)NEWLINE self.device.commProvider.stateMonitorReceived.connect(self.stateResponseReceived)NEWLINENEWLINE self.itemChanged.connect(self.treeItemEdited)NEWLINENEWLINE self.setEnabled(self.device.isConnected)NEWLINENEWLINE def customCommandsMenu(self, position):NEWLINE indexes = self.selectedIndexes()NEWLINE if len(indexes) > 0:NEWLINE level = 0NEWLINE index = indexes[0]NEWLINE while index.parent().isValid():NEWLINE index = index.parent()NEWLINE level += 1NEWLINE selectedItem = self.selectedItems()[0]NEWLINE menu = QtWidgets.QMenu()NEWLINE if selectedItem.text(0) == 'Custom commands':NEWLINE addComand = QtWidgets.QAction("Add command", self)NEWLINE addComand.triggered.connect(self.addCommandAction)NEWLINE menu.addAction(addComand)NEWLINE elif hasattr(selectedItem, 'isCustomCommand'):NEWLINE executeCommand = QtWidgets.QAction("Execute", self)NEWLINE executeCommand.triggered.connect(self.executeCustomCommandAction)NEWLINE menu.addAction(executeCommand)NEWLINE deleteCommand = QtWidgets.QAction("Remove", self)NEWLINE deleteCommand.triggered.connect(self.deleteCustomCommand)NEWLINE menu.addAction(deleteCommand)NEWLINENEWLINE menu.exec_(self.viewport().mapToGlobal(position))NEWLINENEWLINE def addCommandAction(self):NEWLINE selectedItem = self.selectedItems()[0]NEWLINE self.addCustomCommand(selectedItem)NEWLINENEWLINE def executeCustomCommandAction(self):NEWLINE selectedItem = self.selectedItems()[0]NEWLINE selectedCustomCommand = selectedItem.text(1)NEWLINE self.device.sendCommand(selectedCustomCommand)NEWLINENEWLINE def deleteCustomCommand(self):NEWLINE root = self.invisibleRootItem()NEWLINE deletedIndex = self.customComands.indexOfChild(self.selectedItems()[0])NEWLINE self.device.customCommands.customCommandsList.pop(deletedIndex)NEWLINE for item in self.selectedItems():NEWLINE (item.parent() or root).removeChild(item)NEWLINENEWLINE def eventFilter(self, obj, event):NEWLINE if event.type() == QtCore.QEvent.KeyPress:NEWLINE if event.key() == QtCore.Qt.Key_Return:NEWLINE selectedItem = self.selectedItems()[0]NEWLINE if selectedItem.text(0) == 'Custom commands':NEWLINE self.addCustomCommand(selectedItem)NEWLINE if event.key() == QtCore.Qt.Key_Space or event.key() == QtCore.Qt.Key_Right:NEWLINE selectedItem = self.selectedItems()[0]NEWLINE if selectedItem.parent().text(0) == 'Custom commands':NEWLINE self.executeCustomCommandAction()NEWLINE if event.key() == QtCore.Qt.Key_Delete or event.key() == QtCore.Qt.Key_Backspace:NEWLINE selectedItem = self.selectedItems()[0]NEWLINE if selectedItem.parent().text(0) == 'Custom commands':NEWLINE self.deleteCustomCommand()NEWLINE return super(DeviceTreeView, self).eventFilter(obj, event)NEWLINENEWLINE def addCustomCommand(sefl,selectedItem):NEWLINE customCommand = QtWidgets.QTreeWidgetItem()NEWLINE customCommand.isCustomCommand = TrueNEWLINE customCommand.setText(0, '命令')NEWLINE customCommand.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINENEWLINE customCommand.setFlags(NEWLINE customCommand.flags() | QtCore.Qt.ItemIsEditable)NEWLINE selectedItem.addChild(customCommand)NEWLINE sefl.device.customCommands.customCommandsList.append(Command('Command',''))NEWLINENEWLINE def initCustomCommand(sefl, command):NEWLINE customCommand = QtWidgets.QTreeWidgetItem()NEWLINE customCommand.isCustomCommand = TrueNEWLINE customCommand.setText(0, command.cmdName)NEWLINE customCommand.setText(1, command.cmd)NEWLINE customCommand.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE customCommand.setFlags(NEWLINE customCommand.flags() | QtCore.Qt.ItemIsEditable)NEWLINE sefl.customComands.addChild(customCommand)NEWLINENEWLINE def addPIDSubtree(self, parent, label):NEWLINE pidConfiguration = QtWidgets.QTreeWidgetItem()NEWLINE pidConfiguration.setText(0, label)NEWLINE pidConfiguration.setIcon(0, GUIToolKit.getIconByName('pidconfig'))NEWLINE parent.addChild(pidConfiguration)NEWLINENEWLINE proportionalGain = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE proportionalGain.setText(0, 'P 比例项')NEWLINE proportionalGain.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE proportionalGain.setText(1, '')NEWLINE proportionalGain.setFlags(NEWLINE proportionalGain.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE integralGain = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE integralGain.setText(0, 'I 积分项')NEWLINE integralGain.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE integralGain.setText(1, '')NEWLINE integralGain.setFlags(NEWLINE integralGain.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE derivativeGain = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE derivativeGain.setText(0, 'D 微分项')NEWLINE derivativeGain.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE derivativeGain.setText(1, '')NEWLINE derivativeGain.setFlags(NEWLINE derivativeGain.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE voltageRamp = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE voltageRamp.setText(0, '斜坡输出')NEWLINE voltageRamp.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE voltageRamp.setText(1, '')NEWLINE voltageRamp.setFlags(NEWLINE voltageRamp.flags() | QtCore.Qt.ItemIsEditable)NEWLINE NEWLINE limit = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE limit.setText(0, '输出限幅')NEWLINE limit.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE limit.setText(1, '')NEWLINE limit.setFlags(NEWLINE limit.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE lpfTf = QtWidgets.QTreeWidgetItem(pidConfiguration)NEWLINE lpfTf.setText(0, '低通滤波器')NEWLINE lpfTf.setIcon(0, GUIToolKit.getIconByName('gear'))NEWLINE lpfTf.setText(1, '')NEWLINE lpfTf.setFlags(NEWLINE lpfTf.flags() | QtCore.Qt.ItemIsEditable)NEWLINENEWLINE return pidConfigurationNEWLINENEWLINE def treeItemEdited(self, item, column):NEWLINE if item.parent().text(0) == 'Custom commands':NEWLINE updatedIndex = self.customComands.indexOfChild(item)NEWLINE updatedValue = item.text(column)NEWLINE if column == 0:NEWLINE self.device.customCommands.customCommandsList[NEWLINE updatedIndex].cmdName = updatedValueNEWLINE else:NEWLINE self.device.customCommands.customCommandsList[NEWLINE updatedIndex].cmd = updatedValueNEWLINE else:NEWLINE self.sendCommand(item, column)NEWLINENEWLINE def sendCommand(self, item, column):NEWLINE value = item.text(1)NEWLINE fieldName = item.text(0)NEWLINE pidLabel = item.parent().text(0)NEWLINE pid = {}NEWLINE lpf = {}NEWLINE if '速度 PID' in pidLabel:NEWLINE pid = self.device.PIDVelocityNEWLINE lpf = self.device.LPFVelocityNEWLINE elif '角度 PID' in pidLabel:NEWLINE pid = self.device.PIDAngleNEWLINE lpf = self.device.LPFAngleNEWLINE elif '电流Q PID' in pidLabel:NEWLINE pid = self.device.PIDCurrentQNEWLINE lpf = self.device.LPFCurrentQNEWLINE elif '电流D PID' in pidLabel:NEWLINE pid = self.device.PIDCurrentDNEWLINE lpf = self.device.LPFCurrentDNEWLINENEWLINE if 'P 比例项' in fieldName:NEWLINE self.device.sendProportionalGain(pid, value)NEWLINE elif 'I 积分项' in fieldName:NEWLINE self.device.sendIntegralGain(pid, value)NEWLINE elif 'D 微分项' in fieldName:NEWLINE self.device.sendDerivativeGain(pid, value)NEWLINE elif '斜坡输出' in fieldName:NEWLINE self.device.sendOutputRamp(pid, value)NEWLINE elif '低通滤波器' in fieldName:NEWLINE self.device.sendLowPassFilter(lpf, value)NEWLINE elif '输出限幅' in fieldName:NEWLINE self.device.sendOutputLimit(pid,value)NEWLINE elif '电压限幅' in fieldName:NEWLINE self.device.sendVoltageLimit(value)NEWLINE elif '速度限幅' in fieldName:NEWLINE self.device.sendVelocityLimit(value)NEWLINE elif '电流限幅' in fieldName:NEWLINE self.device.sendCurrentLimit(value)NEWLINE elif '相电阻' in fieldName:NEWLINE self.device.sendPhaseResistance(value)NEWLINE elif '零点偏置' in fieldName:NEWLINE self.device.sendSensorZeroOffset(value)NEWLINE elif '电气零点偏置' in fieldName:NEWLINE self.device.sendSensorZeroElectrical(value)NEWLINE elif '运动控制频率降采样' in fieldName:NEWLINE self.device.sendMotionDownsample(value)NEWLINENEWLINE def refreshPIDSubtree(self, pidDisp, pidVal, lpfVal):NEWLINE pidDisp.child(0).setText(1,str(pidVal.P))NEWLINE pidDisp.child(1).setText(1,str(pidVal.I))NEWLINE pidDisp.child(2).setText(1,str(pidVal.D))NEWLINE pidDisp.child(3).setText(1,str(pidVal.outputRamp))NEWLINE pidDisp.child(4).setText(1,str(pidVal.outputLimit))NEWLINE pidDisp.child(5).setText(1,str(lpfVal.Tf))NEWLINENEWLINE def commandResponseReceived(self, comandResponse):NEWLINE self.refreshDeviceTree()NEWLINE self.setTorqueMode(self.device.torqueType)NEWLINE self.setControlLopMode(self.device.controlType)NEWLINE self.setEnabledDisabled(self.device.deviceStatus)NEWLINE self.setModCenter(self.device.modulationCentered)NEWLINE self.setModType(self.device.modulationType)NEWLINENEWLINE def stateResponseReceived(self, comandResponse):NEWLINE self.blockSignals(True)NEWLINE self.stateVel.setText(1,str(self.device.velocityNow))NEWLINE self.stateAngle.setText(1,str(self.device.angleNow))NEWLINE self.stateVd.setText(1,str(self.device.voltageDNow))NEWLINE self.stateVq.setText(1,str(self.device.voltageQNow))NEWLINE self.stateCq.setText(1,str(self.device.currentQNow))NEWLINE self.stateCd.setText(1,str(self.device.currentDNow))NEWLINE self.satateTarget.setText(1,str(self.device.targetNow))NEWLINE self.update()NEWLINE self.blockSignals(False)NEWLINENEWLINE def refreshDeviceTree(self):NEWLINE self.blockSignals(True)NEWLINENEWLINE self.refreshPIDSubtree( self.PIDVelocityConfig, self.device.PIDVelocity, self.device.LPFVelocity)NEWLINE self.refreshPIDSubtree( self.PIDAngleConfig, self.device.PIDAngle, self.device.LPFAngle)NEWLINE self.refreshPIDSubtree( self.PIDCurrentQConfig, self.device.PIDCurrentQ, self.device.LPFCurrentQ)NEWLINE self.refreshPIDSubtree( self.PIDCurrentDConfig, self.device.PIDCurrentD, self.device.LPFCurrentD)NEWLINENEWLINE self.voltageLimit.setText(1,str(self.device.voltageLimit))NEWLINE self.velocityLimit.setText(1,str(self.device.velocityLimit))NEWLINE self.currentLimit.setText(1,str(self.device.currentLimit))NEWLINENEWLINE self.sensorZeroOffset.setText(1,str(self.device.sensorZeroOffset))NEWLINE self.sensorZeroElecOffset.setText(1,str(self.device.sensorElectricalZero))NEWLINE NEWLINE self.phaseRes.setText(1,str(self.device.phaseResistance))NEWLINE # self.deviceStatus.setText(1,str(self.device.deviceStatus))NEWLINENEWLINE self.motionDownsample.setText(1,str(self.device.motionDownsample))NEWLINE # self.torque.setText(1,str(self.device.torqueType))NEWLINE # self.controller.setText(1,str(self.device.controlType))NEWLINE self.update()NEWLINE self.blockSignals(False)NEWLINENEWLINE def setTorqueMode(self, value):NEWLINE self.blockSignals(True)NEWLINE if value == SimpleFOCDevice.VOLTAGE_TORQUE:NEWLINE self.selectorTorque.setCurrentIndex(0)NEWLINE elif value == SimpleFOCDevice.DC_CURRENT_TORQUE:NEWLINE self.selectorTorque.setCurrentIndex(1)NEWLINE elif value == SimpleFOCDevice.FOC_CURRENT_TORQUE:NEWLINE self.selectorTorque.setCurrentIndex(2)NEWLINE self.blockSignals(False)NEWLINENEWLINE def changeTorque(self):NEWLINE index = self.selectorTorque.currentIndex()NEWLINE if index == 0:NEWLINE self.device.sendTorqueType(SimpleFOCDevice.VOLTAGE_TORQUE)NEWLINE elif index == 1:NEWLINE self.device.sendTorqueType(SimpleFOCDevice.DC_CURRENT_TORQUE)NEWLINE elif index == 2:NEWLINE self.device.sendTorqueType(SimpleFOCDevice.FOC_CURRENT_TORQUE)NEWLINENEWLINE def setEnabledDisabled(self, value):NEWLINE self.blockSignals(True)NEWLINE if value == 0:NEWLINE self.selectStatus.setCurrentIndex(0)NEWLINE elif value == 1:NEWLINE self.selectStatus.setCurrentIndex(1)NEWLINE self.blockSignals(False)NEWLINENEWLINE def changeStatus(self):NEWLINE index = self.selectStatus.currentIndex()NEWLINE if index == 0:NEWLINE self.device.sendDeviceStatus(0)NEWLINE elif index == 1:NEWLINE self.device.sendDeviceStatus(1)NEWLINE NEWLINE def setModCenter(self,value):NEWLINE self.blockSignals(True)NEWLINE self.selectModCenter.setCurrentIndex(value)NEWLINE self.blockSignals(False)NEWLINE NEWLINE def changeModCenter(self):NEWLINE index = self.selectModCenter.currentIndex()NEWLINE if index == 0:NEWLINE self.device.sendModulationCentered(0)NEWLINE elif index == 1:NEWLINE self.device.sendModulationCentered(1)NEWLINENEWLINE def setModType(self, value):NEWLINE self.blockSignals(True)NEWLINE if value == SimpleFOCDevice.SINE_PWM:NEWLINE self.selectModulation.setCurrentIndex(0)NEWLINE elif value == SimpleFOCDevice.SPACE_VECTOR_PWM:NEWLINE self.selectModulation.setCurrentIndex(1)NEWLINE elif value == SimpleFOCDevice.TRAPEZOIDAL_120:NEWLINE self.selectModulation.setCurrentIndex(2)NEWLINE elif value == SimpleFOCDevice.TRAPEZOIDAL_150:NEWLINE self.selectModulation.setCurrentIndex(3)NEWLINE self.blockSignals(False)NEWLINENEWLINE def changeModType(self):NEWLINE index = self.selectModulation.currentIndex()NEWLINE if index == 0:NEWLINE self.device.sendModulationType(SimpleFOCDevice.SINE_PWM)NEWLINE elif index == 1:NEWLINE self.device.sendModulationType(SimpleFOCDevice.SPACE_VECTOR_PWM)NEWLINE elif index == 2:NEWLINE self.device.sendModulationType(SimpleFOCDevice.TRAPEZOIDAL_120)NEWLINE elif index == 3:NEWLINE self.device.sendModulationType(SimpleFOCDevice.TRAPEZOIDAL_150)NEWLINENEWLINE def setControlLopMode(self, value):NEWLINE self.blockSignals(True)NEWLINE if value == SimpleFOCDevice.TORQUE_CONTROL:NEWLINE self.selectorControlLoop.setCurrentIndex(0)NEWLINE elif value == SimpleFOCDevice.VELOCITY_CONTROL:NEWLINE self.selectorControlLoop.setCurrentIndex(1)NEWLINE elif value == SimpleFOCDevice.ANGLE_CONTROL:NEWLINE self.selectorControlLoop.setCurrentIndex(2)NEWLINE elif value == SimpleFOCDevice.VELOCITY_OPENLOOP_CONTROL:NEWLINE self.selectorControlLoop.setCurrentIndex(3)NEWLINE elif value == SimpleFOCDevice.ANGLE_OPENLOOP_CONTROL:NEWLINE self.selectorControlLoop.setCurrentIndex(4)NEWLINE self.blockSignals(False)NEWLINENEWLINE def changeControlLoop(self):NEWLINE index = self.selectorControlLoop.currentIndex()NEWLINE if index == 0:NEWLINE self.device.sendControlType(SimpleFOCDevice.TORQUE_CONTROL)NEWLINE elif index == 1:NEWLINE self.device.sendControlType(SimpleFOCDevice.VELOCITY_CONTROL)NEWLINE elif index == 2:NEWLINE self.device.sendControlType(SimpleFOCDevice.ANGLE_CONTROL)NEWLINE elif index == 3:NEWLINE self.device.sendControlType(SimpleFOCDevice.VELOCITY_OPENLOOP_CONTROL)NEWLINE elif index == 4:NEWLINE self.device.sendControlType(SimpleFOCDevice.ANGLE_OPENLOOP_CONTROL)NEWLINE NEWLINE def connectionStateChanged(self, connectionFlag):NEWLINE if connectionFlag is True:NEWLINE self.setEnabled(True)NEWLINE else:NEWLINE self.setEnabled(False)NEWLINE
from app import socketioNEWLINEfrom config import *NEWLINEfrom .spi import *NEWLINEfrom ..socketio_queue import EmitQueueNEWLINENEWLINEfrom flask_socketio import NamespaceNEWLINENEWLINEimport loggingNEWLINENEWLINElogger = logging.getLogger("SIO_Server")NEWLINENEWLINENEWLINEclass XApiNamespace(Namespace):NEWLINE md = NoneNEWLINE td = NoneNEWLINE mq = NoneNEWLINE spi = NoneNEWLINE orders_map = {}NEWLINENEWLINE def __init__(self, namespace=None):NEWLINE super(XApiNamespace, self).__init__(namespace)NEWLINE self.mq = EmitQueue(socketio)NEWLINE self.spi = md_spi(self.mq, self.namespace)NEWLINENEWLINE def start(self):NEWLINE # 有客户端连接上来时才启动NEWLINE # 1. 网页已经连接过一没有关,重开服务端也会导致触发NEWLINE # 2. 服务端已经连接成功了,但没有通知NEWLINE if self.md is None:NEWLINE self.md = config_md()NEWLINE if enable_md:NEWLINE init_md(self.md)NEWLINE if self.td is None:NEWLINE self.td = config_td()NEWLINE init_td(self.td)NEWLINENEWLINE def stop(self):NEWLINE if self.md is not None:NEWLINE self.md.disconnect()NEWLINE self.md = NoneNEWLINE if self.td is not None:NEWLINE self.td.disconnect()NEWLINE self.td = NoneNEWLINENEWLINE def connect(self):NEWLINE self.spi.set_api(self.md, self.td)NEWLINE self.md.register_spi(self.spi)NEWLINE if not self.md.is_connected():NEWLINE if enable_md:NEWLINE self.md.connect()NEWLINE self.td.register_spi(self.spi)NEWLINE if not self.td.is_connected():NEWLINE if enable_td:NEWLINE self.td.connect()NEWLINENEWLINE def on_connect(self):NEWLINE # 刷新网页时这里会触发两次,所以需要做到防止重连NEWLINE logger.info('on_connect')NEWLINE self.start()NEWLINE self.connect()NEWLINE self.spi.emit_is_connected()NEWLINENEWLINE def on_disconnect(self):NEWLINE # 得所有连接都断开才能取消订阅行情NEWLINE logger.info('on_disconnect')NEWLINENEWLINE def on_sub_quote(self, data):NEWLINE logger.info('on_sub_quote:%s', data)NEWLINE args = data['args']NEWLINE if not self.md.is_connected():NEWLINE returnNEWLINE self.md.subscribe(args['instruments'], args['exchange'])NEWLINENEWLINE def on_unsub_quote(self, data):NEWLINE logger.info('on_unsub_quote:%s', data)NEWLINE args = data['args']NEWLINE if not self.md.is_connected():NEWLINE returnNEWLINE self.md.unsubscribe(args['instruments'], args['exchange'])NEWLINENEWLINE def on_send_order(self, data):NEWLINE logger.info('on_send_order:%s', data)NEWLINE args = data['args']NEWLINE if not self.td.is_connected():NEWLINE returnNEWLINENEWLINE # 默认数据,如果输入的参数不够全,使用默认参数NEWLINE _d0 = {NEWLINE "InstrumentID": "c1909",NEWLINE "Type": "Limit",NEWLINE "Side": "Buy",NEWLINE "Qty": 1,NEWLINE "Price": 100.0,NEWLINE "OpenClose": "Open",NEWLINE "HedgeFlag": "Speculation",NEWLINE }NEWLINENEWLINE _input = argsNEWLINE # 使用输出的参数更新默认字典,防止下面取枚举时出错NEWLINE _d0.update(_input)NEWLINENEWLINE # 将原订单中的枚举字符串都换成数字NEWLINE _d1 = {NEWLINE 'Type': OrderType[_d0["Type"]],NEWLINE 'Side': OrderSide[_d0["Side"]],NEWLINE 'OpenClose': OpenCloseType[_d0["OpenClose"]],NEWLINE 'HedgeFlag': HedgeFlagType[_d0["HedgeFlag"]],NEWLINE }NEWLINE _d0.update(_d1)NEWLINE local_id = _d0['LocalID']NEWLINENEWLINE order_id = self.td.send_order(_d0)NEWLINENEWLINE # 也可以不设置,但这样远程就无法关联了NEWLINE if len(local_id) > 0:NEWLINE self.orders_map[order_id] = local_idNEWLINENEWLINE def on_cancel_order(self, data):NEWLINE logger.info('on_cancel_order:%s', data)NEWLINE args = data['args']NEWLINE if not self.td.is_connected():NEWLINE returnNEWLINE self.td.cancel_order(args["ID"])NEWLINENEWLINE def on_query_account(self, data):NEWLINE logger.info('on_query_account')NEWLINE query = ReqQueryField()NEWLINE self.td.req_query(QueryType.ReqQryTradingAccount, query)NEWLINENEWLINE def on_query_positions(self, data):NEWLINE logger.info('on_query_positions')NEWLINE query = ReqQueryField()NEWLINE self.td.req_query(QueryType.ReqQryInvestorPosition, query)NEWLINENEWLINE def on_query_instrument(self, data):NEWLINE logger.info('on_query_instrument')NEWLINE args = data['args']NEWLINENEWLINE query = ReqQueryField()NEWLINE try:NEWLINE exchange_id = args['ExchangeID']NEWLINE query.ExchangeID = exchange_id.encode()NEWLINE except:NEWLINE passNEWLINE self.td.req_query(QueryType.ReqQryInstrument, query)NEWLINENEWLINE def on_query_order(self, data):NEWLINE logger.info('on_query_order')NEWLINE args = data['args']NEWLINENEWLINE query = ReqQueryField()NEWLINE self.td.req_query(QueryType.ReqQryOrder, query)NEWLINENEWLINE def on_query_settlement_info(self, data):NEWLINE logger.info('on_query_settlement_info:%s', data)NEWLINE args = data['args']NEWLINENEWLINE query = ReqQueryField()NEWLINE query.DateStart = args["TradingDay"]NEWLINE self.td.req_query(QueryType.ReqQrySettlementInfo, query)NEWLINENEWLINE def on_query_history_data(self, data):NEWLINE logger.info('on_query_history_data:%s', data)NEWLINE args = data['args']NEWLINENEWLINE self.spi.emit_rsp_qry_history_data(args)NEWLINE
from ignite.metrics.accumulation import Average, GeometricAverage, VariableAccumulationNEWLINEfrom ignite.metrics.accuracy import AccuracyNEWLINEfrom ignite.metrics.classification_report import ClassificationReportNEWLINEfrom ignite.metrics.confusion_matrix import ConfusionMatrix, DiceCoefficient, IoU, JaccardIndex, mIoUNEWLINEfrom ignite.metrics.epoch_metric import EpochMetricNEWLINEfrom ignite.metrics.fbeta import FbetaNEWLINEfrom ignite.metrics.frequency import FrequencyNEWLINEfrom ignite.metrics.gan.fid import FIDNEWLINEfrom ignite.metrics.gan.inception_score import InceptionScoreNEWLINEfrom ignite.metrics.loss import LossNEWLINEfrom ignite.metrics.mean_absolute_error import MeanAbsoluteErrorNEWLINEfrom ignite.metrics.mean_pairwise_distance import MeanPairwiseDistanceNEWLINEfrom ignite.metrics.mean_squared_error import MeanSquaredErrorNEWLINEfrom ignite.metrics.metric import BatchFiltered, BatchWise, EpochWise, Metric, MetricUsageNEWLINEfrom ignite.metrics.metrics_lambda import MetricsLambdaNEWLINEfrom ignite.metrics.multilabel_confusion_matrix import MultiLabelConfusionMatrixNEWLINEfrom ignite.metrics.nlp.bleu import BleuNEWLINEfrom ignite.metrics.nlp.rouge import Rouge, RougeL, RougeNNEWLINEfrom ignite.metrics.precision import PrecisionNEWLINEfrom ignite.metrics.psnr import PSNRNEWLINEfrom ignite.metrics.recall import RecallNEWLINEfrom ignite.metrics.root_mean_squared_error import RootMeanSquaredErrorNEWLINEfrom ignite.metrics.running_average import RunningAverageNEWLINEfrom ignite.metrics.ssim import SSIMNEWLINEfrom ignite.metrics.top_k_categorical_accuracy import TopKCategoricalAccuracyNEWLINENEWLINE__all__ = [NEWLINE "Metric",NEWLINE "Accuracy",NEWLINE "Loss",NEWLINE "MetricsLambda",NEWLINE "MeanAbsoluteError",NEWLINE "MeanPairwiseDistance",NEWLINE "MeanSquaredError",NEWLINE "ConfusionMatrix",NEWLINE "ClassificationReport",NEWLINE "TopKCategoricalAccuracy",NEWLINE "Average",NEWLINE "DiceCoefficient",NEWLINE "EpochMetric",NEWLINE "Fbeta",NEWLINE "FID",NEWLINE "GeometricAverage",NEWLINE "IoU",NEWLINE "InceptionScore",NEWLINE "mIoU",NEWLINE "JaccardIndex",NEWLINE "MultiLabelConfusionMatrix",NEWLINE "Precision",NEWLINE "PSNR",NEWLINE "Recall",NEWLINE "RootMeanSquaredError",NEWLINE "RunningAverage",NEWLINE "VariableAccumulation",NEWLINE "Frequency",NEWLINE "SSIM",NEWLINE "Bleu",NEWLINE "Rouge",NEWLINE "RougeN",NEWLINE "RougeL",NEWLINE]NEWLINE
"""Program to draw Mandelbrot fractals: the graphical user interface.NEWLINENEWLINEAuthor: Lars van den Haak and Tom VerhoeffNEWLINENEWLINECopyright (c) 2020 - Eindhoven University of Technology, The NetherlandsNEWLINENEWLINEThis software is made available under the terms of the MIT License.NEWLINENEWLINE* Contributor 1: Harry VerspagenNEWLINE* TU/e ID number 1: 1484575NEWLINE* Contributor 2: Sander DebetsNEWLINE* TU/e ID number 2: 1252402NEWLINE* Date: 04-05-2020NEWLINE"""NEWLINEfrom PIL import Image, ImageTk # type: ignoreNEWLINEimport tkinter as tkNEWLINEfrom mandel import *NEWLINEfrom typing import CallableNEWLINENEWLINENEWLINEdef squares(px: int, py: int, c1: Color = GREEN, c2: Color = BLUE) -> Color:NEWLINE """Colors the screen in squares of 20 pixelsNEWLINENEWLINE :param: px: pixel x-coordinateNEWLINE :param: py: pixel y-coordinateNEWLINE :param: c1: Color of the first type of squareNEWLINE :param: c2: Color of the second type of squareNEWLINE :return: Color for the input pixelNEWLINE """NEWLINE if px // 20 % 2 == py // 20 % 2:NEWLINE c = c1NEWLINE else:NEWLINE c = c2NEWLINE return cNEWLINENEWLINENEWLINEclass GUI:NEWLINE """A class where we make our Graphical User Interface based on TkInterNEWLINE """NEWLINE def __init__(self) -> None:NEWLINE self.image = NoneNEWLINE self.window = tk.Tk()NEWLINE self.canvas = tk.Label(self.window, image=None)NEWLINE self.canvas.pack(side="bottom", fill="both", expand="yes")NEWLINENEWLINENEWLINEdef make_image(gui: GUI, colorize: Callable[[int, int], Color] = squares) -> None:NEWLINE """Puts an image on screen created by a functionNEWLINENEWLINE :param: gui: An instance from the GUI classNEWLINE :param: colorize: A function that gives a color to each pixelNEWLINE """NEWLINE img = Image.new('RGB', (600, 600))NEWLINE for x in range(0, 600):NEWLINE for y in range(0, 600):NEWLINE img.putpixel((x, y), colorize(x, y))NEWLINENEWLINE tkimg = ImageTk.PhotoImage(img)NEWLINE # Save the image to the gui class, otherwise it gets garbage collectedNEWLINE gui.image = tkimgNEWLINE canvas = gui.canvasNEWLINENEWLINE canvas.configure(image=tkimg)NEWLINE canvas.pack(side="bottom", fill="both", expand="yes")NEWLINE
from __future__ import absolute_importNEWLINENEWLINEfrom google.appengine.api import usersNEWLINENEWLINE# CUSTOMIZE can_see_experiments however you want to specifyNEWLINE# whether or not the currently-logged-in user has accessNEWLINE# to the experiment dashboard.NEWLINEdef can_control_experiments():NEWLINE return users.is_current_user_admin()NEWLINENEWLINE# CUSTOMIZE current_logged_in_identity to make your a/b sessionsNEWLINE# stickier and more persistent per user.NEWLINE#NEWLINE# This should return one of the following:NEWLINE#NEWLINE# A) a db.Model that identifies the current user, like models.UserData.current()NEWLINE# B) a unique string that consistently identifies the current user, like users.get_current_user().user_id()NEWLINE# C) None, if your app has no way of identifying the current user for the current request. In this case gae_bingo will automatically use a random unique identifier.NEWLINE#NEWLINE# Ideally, this should be connected to your app's existing identity system.NEWLINE#NEWLINE# To get the strongest identity tracking even when switching from a random, not logged-in userNEWLINE# to a logged in user, return a model that inherits from GaeBingoIdentityModel.NEWLINE# See docs for details.NEWLINE#NEWLINE# Examples:NEWLINE# return models.UserData.current()NEWLINE# ...or...NEWLINE# from google.appengine.api import usersNEWLINE# return users.get_current_user().user_id() if users.get_current_user() else NoneNEWLINEdef current_logged_in_identity():NEWLINE from models import UserDataNEWLINE return UserData.current(bust_cache=True)NEWLINENEWLINENEWLINE
from typing import ListNEWLINENEWLINEfrom .en import FILTERS as EN_FILTERSNEWLINEfrom .de import FILTERS as DE_FILTERSNEWLINEfrom .fr import FILTERS as FR_FILTERSNEWLINEfrom .es import FILTERS as ES_FILTERSNEWLINEfrom .mx import FILTERS as MX_FILTERSNEWLINEfrom .ru import FILTERS as RU_FILTERSNEWLINEfrom .cn import FILTERS as CN_FILTERSNEWLINEfrom .pt import FILTERS as PT_FILTERSNEWLINEfrom .ko import FILTERS as KO_FILTERSNEWLINENEWLINENEWLINEdef get_filter_list_by_lang(lang: str) -> List[str]:NEWLINE if lang == "en":NEWLINE return EN_FILTERSNEWLINE elif lang == "de":NEWLINE return DE_FILTERSNEWLINE elif lang == "fr":NEWLINE return FR_FILTERSNEWLINE elif lang == "es":NEWLINE return ES_FILTERSNEWLINE elif lang == "mx":NEWLINE return MX_FILTERSNEWLINE elif lang == "ru":NEWLINE return RU_FILTERSNEWLINE elif lang == "cn":NEWLINE return CN_FILTERSNEWLINE elif lang == "pt":NEWLINE return PT_FILTERSNEWLINE elif lang == "ko":NEWLINE return KO_FILTERSNEWLINE else:NEWLINE raise ValueError("Language '{}' not supported".format(lang))NEWLINE
"""NEWLINE@author: Junguang JiangNEWLINE@contact: JiangJunguang1123@outlook.comNEWLINE"""NEWLINEimport randomNEWLINEimport timeNEWLINEimport warningsNEWLINEimport sysNEWLINEimport argparseNEWLINEimport shutilNEWLINEimport os.path as ospNEWLINENEWLINEimport torchNEWLINEimport torch.nn as nnNEWLINEimport torch.backends.cudnn as cudnnNEWLINEfrom torch.optim import SGDNEWLINEfrom torch.optim.lr_scheduler import LambdaLRNEWLINEfrom torch.utils.data import DataLoaderNEWLINEimport torch.nn.functional as FNEWLINENEWLINEsys.path.append('../../..')NEWLINEfrom common.modules.classifier import ClassifierNEWLINEfrom common.utils.data import ForeverDataIteratorNEWLINEfrom common.utils.metric import accuracy, ConfusionMatrixNEWLINEfrom common.utils.meter import AverageMeter, ProgressMeterNEWLINEfrom common.utils.logger import CompleteLoggerNEWLINEfrom common.utils.analysis import collect_feature, tsne, a_distanceNEWLINENEWLINEsys.path.append('.')NEWLINEimport utilsNEWLINENEWLINEdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")NEWLINENEWLINENEWLINEdef main(args: argparse.Namespace):NEWLINE logger = CompleteLogger(args.log, args.phase)NEWLINE print(args)NEWLINENEWLINE if args.seed is not None:NEWLINE random.seed(args.seed)NEWLINE torch.manual_seed(args.seed)NEWLINE cudnn.deterministic = TrueNEWLINE warnings.warn('You have chosen to seed training. 'NEWLINE 'This will turn on the CUDNN deterministic setting, 'NEWLINE 'which can slow down your training considerably! 'NEWLINE 'You may see unexpected behavior when restarting 'NEWLINE 'from checkpoints.')NEWLINENEWLINE cudnn.benchmark = TrueNEWLINENEWLINE # Data loading codeNEWLINE # Data loading codeNEWLINE train_transform = utils.get_train_transform(args.train_resizing, random_horizontal_flip=True, random_color_jitter=False)NEWLINE val_transform = utils.get_val_transform(args.val_resizing)NEWLINE print("train_transform: ", train_transform)NEWLINE print("val_transform: ", val_transform)NEWLINENEWLINE train_source_dataset, _, val_dataset, test_dataset, num_classes, args.class_names = \NEWLINE utils.get_dataset(args.data, args.root, args.source, args.target, train_transform, val_transform)NEWLINE train_source_loader = DataLoader(train_source_dataset, batch_size=args.batch_size,NEWLINE shuffle=True, num_workers=args.workers, drop_last=True)NEWLINE val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers)NEWLINE test_loader = DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.workers)NEWLINENEWLINE train_source_iter = ForeverDataIterator(train_source_loader)NEWLINENEWLINE # create modelNEWLINE print("=> using pre-trained model '{}'".format(args.arch))NEWLINE backbone = utils.get_model(args.arch)NEWLINE pool_layer = nn.Identity() if args.no_pool else NoneNEWLINE classifier = Classifier(backbone, num_classes, pool_layer=pool_layer).to(device)NEWLINENEWLINE # define optimizer and lr schedulerNEWLINE optimizer = SGD(classifier.get_parameters(), args.lr, momentum=args.momentum, weight_decay=args.wd, nesterov=True)NEWLINE lr_scheduler = LambdaLR(optimizer, lambda x: args.lr * (1. + args.lr_gamma * float(x)) ** (-args.lr_decay))NEWLINENEWLINE # analysis the modelNEWLINE if args.phase == 'analysis':NEWLINE # using shuffled val loaderNEWLINE val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.workers)NEWLINE # extract features from both domainsNEWLINE feature_extractor = nn.Sequential(classifier.backbone, classifier.pool_layer, classifier.bottleneck).to(device)NEWLINE source_feature = collect_feature(train_source_loader, feature_extractor, device)NEWLINE target_feature = collect_feature(val_loader, feature_extractor, device)NEWLINE # plot t-SNENEWLINE tSNE_filename = osp.join(logger.visualize_directory, 'TSNE.png')NEWLINE tsne.visualize(source_feature, target_feature, tSNE_filename)NEWLINE print("Saving t-SNE to", tSNE_filename)NEWLINE # calculate A-distance, which is a measure for distribution discrepancyNEWLINE A_distance = a_distance.calculate(source_feature, target_feature, device)NEWLINE print("A-distance =", A_distance)NEWLINE returnNEWLINENEWLINE if args.phase == 'test':NEWLINE acc1 = validate(test_loader, classifier, args)NEWLINE print(acc1)NEWLINE returnNEWLINENEWLINE # start trainingNEWLINE best_h_score = 0.NEWLINE for epoch in range(args.epochs):NEWLINE # train for one epochNEWLINE train(train_source_iter, classifier, optimizer,NEWLINE lr_scheduler, epoch, args)NEWLINENEWLINE # evaluate on validation setNEWLINE h_score = validate(val_loader, classifier, args)NEWLINENEWLINE # remember best acc@1 and save checkpointNEWLINE torch.save(classifier.state_dict(), logger.get_checkpoint_path('latest'))NEWLINE if h_score > best_h_score:NEWLINE shutil.copy(logger.get_checkpoint_path('latest'), logger.get_checkpoint_path('best'))NEWLINE best_h_score = max(h_score, best_h_score)NEWLINENEWLINE print("best_h_score = {:3.1f}".format(best_h_score))NEWLINENEWLINE # evaluate on test setNEWLINE classifier.load_state_dict(torch.load(logger.get_checkpoint_path('best')))NEWLINE h_score = validate(test_loader, classifier, args)NEWLINE print("test_h_score = {:3.1f}".format(h_score))NEWLINENEWLINE logger.close()NEWLINENEWLINENEWLINEdef train(train_source_iter: ForeverDataIterator, model: Classifier, optimizer: SGD,NEWLINE lr_scheduler: LambdaLR, epoch: int, args: argparse.Namespace):NEWLINE batch_time = AverageMeter('Time', ':4.2f')NEWLINE data_time = AverageMeter('Data', ':3.1f')NEWLINE losses = AverageMeter('Loss', ':3.2f')NEWLINE cls_accs = AverageMeter('Cls Acc', ':3.1f')NEWLINENEWLINE progress = ProgressMeter(NEWLINE args.iters_per_epoch,NEWLINE [batch_time, data_time, losses, cls_accs],NEWLINE prefix="Epoch: [{}]".format(epoch))NEWLINENEWLINE # switch to train modeNEWLINE model.train()NEWLINENEWLINE end = time.time()NEWLINE for i in range(args.iters_per_epoch):NEWLINE x_s, labels_s = next(train_source_iter)NEWLINE x_s = x_s.to(device)NEWLINE labels_s = labels_s.to(device)NEWLINENEWLINE # measure data loading timeNEWLINE data_time.update(time.time() - end)NEWLINENEWLINE # compute outputNEWLINE y_s, f_s = model(x_s)NEWLINENEWLINE cls_loss = F.cross_entropy(y_s, labels_s)NEWLINE loss = cls_lossNEWLINENEWLINE cls_acc = accuracy(y_s, labels_s)[0]NEWLINENEWLINE losses.update(loss.item(), x_s.size(0))NEWLINE cls_accs.update(cls_acc.item(), x_s.size(0))NEWLINENEWLINE # compute gradient and do SGD stepNEWLINE optimizer.zero_grad()NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINE lr_scheduler.step()NEWLINENEWLINE # measure elapsed timeNEWLINE batch_time.update(time.time() - end)NEWLINE end = time.time()NEWLINENEWLINE if i % args.print_freq == 0:NEWLINE progress.display(i)NEWLINENEWLINENEWLINEdef validate(val_loader: DataLoader, model: Classifier, args: argparse.Namespace) -> float:NEWLINE batch_time = AverageMeter('Time', ':6.3f')NEWLINE classes = val_loader.dataset.classesNEWLINE confmat = ConfusionMatrix(len(classes))NEWLINE progress = ProgressMeter(NEWLINE len(val_loader),NEWLINE [batch_time],NEWLINE prefix='Test: ')NEWLINENEWLINE # switch to evaluate modeNEWLINE model.eval()NEWLINENEWLINE with torch.no_grad():NEWLINE end = time.time()NEWLINE for i, (images, target) in enumerate(val_loader):NEWLINE images = images.to(device)NEWLINE target = target.to(device)NEWLINENEWLINE # compute outputNEWLINE output = model(images)NEWLINE softmax_output = F.softmax(output, dim=1)NEWLINE softmax_output[:, -1] = args.thresholdNEWLINENEWLINE # measure accuracy and record lossNEWLINE confmat.update(target, softmax_output.argmax(1))NEWLINENEWLINE # measure elapsed timeNEWLINE batch_time.update(time.time() - end)NEWLINE end = time.time()NEWLINENEWLINE if i % args.print_freq == 0:NEWLINE progress.display(i)NEWLINENEWLINE acc_global, accs, iu = confmat.compute()NEWLINE all_acc = torch.mean(accs).item() * 100NEWLINE known = torch.mean(accs[:-1]).item() * 100NEWLINE unknown = accs[-1].item() * 100NEWLINE h_score = 2 * known * unknown / (known + unknown)NEWLINE if args.per_class_eval:NEWLINE print(confmat.format(classes))NEWLINE print(' * All {all:.3f} Known {known:.3f} Unknown {unknown:.3f} H-score {h_score:.3f}'NEWLINE .format(all=all_acc, known=known, unknown=unknown, h_score=h_score))NEWLINENEWLINE return h_scoreNEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE parser = argparse.ArgumentParser(description='Source Only for Openset Domain Adaptation')NEWLINE # dataset parametersNEWLINE parser.add_argument('root', metavar='DIR',NEWLINE help='root path of dataset')NEWLINE parser.add_argument('-d', '--data', metavar='DATA', default='Office31', choices=utils.get_dataset_names(),NEWLINE help='dataset: ' + ' | '.join(utils.get_dataset_names()) +NEWLINE ' (default: Office31)')NEWLINE parser.add_argument('-s', '--source', help='source domain')NEWLINE parser.add_argument('-t', '--target', help='target domain')NEWLINE parser.add_argument('--train-resizing', type=str, default='default')NEWLINE parser.add_argument('--val-resizing', type=str, default='default')NEWLINE # model parametersNEWLINE parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',NEWLINE choices=utils.get_model_names(),NEWLINE help='backbone architecture: ' +NEWLINE ' | '.join(utils.get_model_names()) +NEWLINE ' (default: resnet18)')NEWLINE parser.add_argument('--no-pool', action='store_true',NEWLINE help='no pool layer after the feature extractor.')NEWLINE parser.add_argument('--threshold', default=0.8, type=float,NEWLINE help='When class confidence is less than the given threshold, 'NEWLINE 'model will output "unknown" (default: 0.5)')NEWLINE # training parametersNEWLINE parser.add_argument('-b', '--batch-size', default=32, type=int,NEWLINE metavar='N',NEWLINE help='mini-batch size (default: 32)')NEWLINE parser.add_argument('--lr', '--learning-rate', default=0.001, type=float,NEWLINE metavar='LR', help='initial learning rate', dest='lr')NEWLINE parser.add_argument('--lr-gamma', default=0.0003, type=float, help='parameter for lr scheduler')NEWLINE parser.add_argument('--lr-decay', default=0.75, type=float, help='parameter for lr scheduler')NEWLINE parser.add_argument('--momentum', default=0.9, type=float, metavar='M',NEWLINE help='momentum')NEWLINE parser.add_argument('--wd', '--weight-decay', default=0.0005, type=float,NEWLINE metavar='W', help='weight decay (default: 5e-4)')NEWLINE parser.add_argument('-j', '--workers', default=2, type=int, metavar='N',NEWLINE help='number of data loading workers (default: 4)')NEWLINE parser.add_argument('--epochs', default=20, type=int, metavar='N',NEWLINE help='number of total epochs to run')NEWLINE parser.add_argument('-i', '--iters-per-epoch', default=500, type=int,NEWLINE help='Number of iterations per epoch')NEWLINE parser.add_argument('-p', '--print-freq', default=100, type=int,NEWLINE metavar='N', help='print frequency (default: 100)')NEWLINE parser.add_argument('--seed', default=None, type=int,NEWLINE help='seed for initializing training. ')NEWLINE parser.add_argument('--per-class-eval', action='store_true',NEWLINE help='whether output per-class accuracy during evaluation')NEWLINE parser.add_argument("--log", type=str, default='src_only',NEWLINE help="Where to save logs, checkpoints and debugging images.")NEWLINE parser.add_argument("--phase", type=str, default='train', choices=['train', 'test', 'analysis'],NEWLINE help="When phase is 'test', only test the model."NEWLINE "When phase is 'analysis', only analysis the model.")NEWLINE args = parser.parse_args()NEWLINE main(args)NEWLINENEWLINE
print('This is for test #1')
import osNEWLINEimport reNEWLINEimport shutilNEWLINEimport subprocessNEWLINEimport jsonNEWLINENEWLINEfrom core.python import help_textNEWLINEfrom core.python.python_terraform import IsNotFlaggedNEWLINEfrom core.python.utils import PatchedTerraform as TerraformNEWLINEfrom core.python.utils import (NEWLINE check_own_ip_address,NEWLINE create_dir_if_nonexistent,NEWLINE create_or_update_yaml_file,NEWLINE dirs_at_location,NEWLINE display_terraform_step_error,NEWLINE extract_cgid_from_dir_name,NEWLINE find_scenario_dir,NEWLINE find_scenario_instance_dir,NEWLINE generate_cgid,NEWLINE generate_cgid_using_username,NEWLINE ip_address_or_range_is_valid,NEWLINE load_and_validate_whitelist,NEWLINE load_data_from_yaml_file,NEWLINE normalize_scenario_name,NEWLINE)NEWLINENEWLINENEWLINEclass CloudGoat:NEWLINE def __init__(self, base_dir):NEWLINE self.base_dir = base_dirNEWLINE self.config_path = os.path.join(self.base_dir, "config.yml")NEWLINE self.scenarios_dir = os.path.join(base_dir, "scenarios")NEWLINE self.scenario_names = dirs_at_location(self.scenarios_dir, names_only=True)NEWLINE self.whitelist_path = os.path.join(base_dir, "whitelist.txt")NEWLINENEWLINE self.aws_region = "us-east-1"NEWLINE self.cloudgoat_commands = ["config", "create", "destroy", "list", "help"]NEWLINE self.non_scenario_instance_dirs = [NEWLINE ".git",NEWLINE "__pycache__",NEWLINE "core",NEWLINE "scenarios",NEWLINE "trash",NEWLINE ]NEWLINENEWLINE def parse_and_execute_command(self, parsed_args):NEWLINE command = parsed_args.commandNEWLINE profile = parsed_args.profileNEWLINENEWLINE # Display help text. Putting this first makes validation simpler.NEWLINE if len(command) == 0 \NEWLINE or command[0] in ["help", "-h", "--help"] \NEWLINE or (len(command) >= 2 and command[-1] == "help"):NEWLINE return self.display_cloudgoat_help(command)NEWLINENEWLINE # ValidationNEWLINE if len(command) == 1:NEWLINE if command[0] == "config":NEWLINE print(NEWLINE f'The {command[0]} currently must be used with "whitelist",'NEWLINE f' "profile", or "help".'NEWLINE )NEWLINE returnNEWLINE elif command[0] == "create":NEWLINE print(NEWLINE f"The {command[0]} command must be used with either a scenario name"NEWLINE f' or "help".'NEWLINE f"\nAll scenarios:\n " + "\n ".join(self.scenario_names)NEWLINE )NEWLINE returnNEWLINE elif command[0] == "destroy":NEWLINE print(NEWLINE f"The {command[0]} command must be used with a scenario name,"NEWLINE f' "all", or "help".'NEWLINE f"\nAll scenarios:\n " + "\n ".join(self.scenario_names)NEWLINE )NEWLINE returnNEWLINE elif command[0] == "list":NEWLINE print(NEWLINE f"The {command[0]} command must be used with a scenario name,"NEWLINE f' "all", "deployed", "undeployed", or "help".'NEWLINE f"\nAll scenarios:\n " + "\n ".join(self.scenario_names)NEWLINE )NEWLINE returnNEWLINENEWLINE if command[0] in ("create", "destroy", "list"):NEWLINE if command[1].lower() in self.cloudgoat_commands:NEWLINE print(f"CloudGoat scenarios cannot be named after CloudGoat commands.")NEWLINE returnNEWLINE if command[1] in self.non_scenario_instance_dirs:NEWLINE print(NEWLINE f'The name "{command[1]}" is reserved for CloudGoat and may not be'NEWLINE f" used with the {command[0]} command."NEWLINE )NEWLINE returnNEWLINENEWLINE if command[0] in ("create", "destroy"):NEWLINE if not profile:NEWLINE if os.path.exists(self.config_path):NEWLINE profile = load_data_from_yaml_file(NEWLINE self.config_path, "default-profile"NEWLINE )NEWLINE user_name = load_data_from_yaml_file(NEWLINE self.config_path, "user-name"NEWLINE )NEWLINE if not profile:NEWLINE print(NEWLINE f"The {command[0]} command requires the use of the --profile"NEWLINE f" flag, or a default profile defined in the config.yml file"NEWLINE f' (try "config profile").'NEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f'Using default profile "{profile}" from config.yml...')NEWLINENEWLINE # ExecutionNEWLINE if command[0] == "config":NEWLINE if command[1] == "whitelist" or command[1] == "whitelist.txt":NEWLINE return self.configure_or_check_whitelist(NEWLINE auto=parsed_args.auto, print_values=TrueNEWLINE )NEWLINE elif command[1] == "profile":NEWLINE return self.configure_or_check_default_profile()NEWLINE elif command[1] == "argcomplete":NEWLINE return self.configure_argcomplete()NEWLINENEWLINE elif command[0] == "create":NEWLINE return self.create_scenario(command[1], profile, user_name)NEWLINENEWLINE elif command[0] == "destroy":NEWLINE if command[1] == "all":NEWLINE return self.destroy_all_scenarios(profile)NEWLINE else:NEWLINE return self.destroy_scenario(command[1], profile)NEWLINENEWLINE elif command[0] == "list":NEWLINE if command[1] == "all":NEWLINE return self.list_all_scenarios()NEWLINE elif command[1] == "deployed":NEWLINE return self.list_deployed_scenario_instances()NEWLINE elif command[1] == "undeployed":NEWLINE return self.list_undeployed_scenarios()NEWLINE else:NEWLINE return self.list_scenario_instance(command[1])NEWLINENEWLINE print(f'Unrecognized command. Try "cloudgoat.py help"')NEWLINE returnNEWLINENEWLINE def display_cloudgoat_help(self, command):NEWLINE if not command or len(command) == 1:NEWLINE return print(help_text.CLOUDGOAT)NEWLINENEWLINE # Makes "help foo" equivalent to "foo help".NEWLINE command.remove("help")NEWLINENEWLINE if command[0] == "config":NEWLINE if len(command) > 1 and command[1] == "argcomplete":NEWLINE return print(help_text.CONFIG_ARGCOMPLETE)NEWLINE else:NEWLINE return print(help_text.CONFIG)NEWLINE elif command[0] == "create":NEWLINE return print(help_text.CREATE)NEWLINE elif command[0] == "destroy":NEWLINE return print(help_text.DESTROY)NEWLINE elif command[0] == "list":NEWLINE return print(help_text.LIST)NEWLINE elif command[0] == "help":NEWLINE if all([word == "help" for word in command]):NEWLINE joined_help_texts = " ".join(["help text for" for word in command])NEWLINE return print(f"Displays {joined_help_texts} CloudGoat.")NEWLINE else:NEWLINE scenario_name = normalize_scenario_name(command[0])NEWLINE scenario_dir_path = find_scenario_dir(self.scenarios_dir, scenario_name)NEWLINE if scenario_dir_path:NEWLINE scenario_help_text = load_data_from_yaml_file(NEWLINE os.path.join(scenario_dir_path, "manifest.yml"), "help"NEWLINE ).strip()NEWLINE return print(NEWLINE f"[cloudgoat scenario: {scenario_name}]\n{scenario_help_text}"NEWLINE )NEWLINENEWLINE return print(NEWLINE f'Unrecognized command or scenario name. Try "cloudgoat.py help" or'NEWLINE f' "cloudgoat.py list all"'NEWLINE )NEWLINENEWLINE def configure_argcomplete(self):NEWLINE print(help_text.CONFIG_ARGCOMPLETE)NEWLINENEWLINE def configure_or_check_default_profile(self):NEWLINE if not os.path.exists(self.config_path):NEWLINE create_config_file_now = input(NEWLINE f"No configuration file was found at {self.config_path}"NEWLINE f"\nWould you like to create this file with a default profile name now?"NEWLINE f" [y/n]: "NEWLINE )NEWLINE default_profile = NoneNEWLINE else:NEWLINE print(f"A configuration file exists at {self.config_path}")NEWLINE default_profile = load_data_from_yaml_file(NEWLINE self.config_path, "default-profile"NEWLINE )NEWLINE user_name = load_data_from_yaml_file(NEWLINE self.config_path, "user-name"NEWLINE )NEWLINE if default_profile:NEWLINE print(f'It specifies a default profile name of "{default_profile}".')NEWLINE print(f'And user name of "{user_name}".')NEWLINE else:NEWLINE print(f"It does not contain a default profile name.")NEWLINE create_config_file_now = input(NEWLINE f"Would you like to specify a new default profile name for the"NEWLINE f" configuration file now? [y/n]: "NEWLINE )NEWLINENEWLINE if not create_config_file_now.strip().lower().startswith("y"):NEWLINE returnNEWLINENEWLINE while True:NEWLINE default_profile = input(NEWLINE f"Enter the name of your default AWS profile: "NEWLINE ).strip()NEWLINENEWLINE user_name = input(NEWLINE f"Enter your last name: "NEWLINE ).strip()NEWLINENEWLINE if default_profile:NEWLINE create_or_update_yaml_file(NEWLINE self.config_path, {"default-profile": default_profile}NEWLINE )NEWLINENEWLINE create_or_update_yaml_file(NEWLINE self.config_path, {"user-name": user_name}NEWLINE )NEWLINENEWLINE print(f'A default profile name of "{default_profile}" has been saved.')NEWLINE print(f'A user name of "{user_name}" has been saved.')NEWLINE breakNEWLINE else:NEWLINE print(f"Enter your default profile's name, or hit ctrl-c to exit.")NEWLINE continueNEWLINENEWLINE returnNEWLINENEWLINE def configure_or_check_whitelist(self, auto=False, print_values=False):NEWLINE if auto:NEWLINE message = (NEWLINE f"CloudGoat can automatically make a network request, using "NEWLINE f"https://ifconfig.co to find your IP address, and then overwrite the"NEWLINE f" contents of the whitelist file with the result."NEWLINE f"\nWould you like to continue? [y/n]: "NEWLINE )NEWLINENEWLINE if os.path.exists(self.whitelist_path):NEWLINE confirm_auto_configure = input(NEWLINE f"A whitelist.txt file was found at {self.whitelist_path}\n\n{message}"NEWLINE )NEWLINE else:NEWLINE confirm_auto_configure = input(NEWLINE f"No whitelist.txt file was found at {self.whitelist_path}\n\n{message}"NEWLINE )NEWLINENEWLINE if confirm_auto_configure.strip().lower().startswith("y"):NEWLINE ip_address = check_own_ip_address()NEWLINENEWLINE if ip_address is None:NEWLINE print(f"\n[cloudgoat] Unknown error: Unable to retrieve IP address.\n")NEWLINE return NoneNEWLINENEWLINE ip_address = f"{ip_address}/32"NEWLINENEWLINE if ip_address_or_range_is_valid(ip_address):NEWLINE with open(self.whitelist_path, "w") as whitelist_file:NEWLINE whitelist_file.write(ip_address)NEWLINENEWLINE print(f"\nwhitelist.txt created with IP address {ip_address}")NEWLINENEWLINE return load_and_validate_whitelist(self.whitelist_path)NEWLINENEWLINE else:NEWLINE print(NEWLINE f"\n[cloudgoat] Unknown error: Did not receive a valid IP"NEWLINE f" address. Received this instead:\n{ip_address}\n"NEWLINE )NEWLINE return NoneNEWLINENEWLINE else:NEWLINE print(f"Automatic whitelist.txt configuration cancelled.")NEWLINE return NoneNEWLINENEWLINE elif not os.path.exists(self.whitelist_path):NEWLINE create_whitelist_now = input(NEWLINE f"No IP address whitelist was found at {self.whitelist_path}"NEWLINE f"\nCloudGoat requires a whitelist.txt file to exist before the"NEWLINE f' "create" command can be used.'NEWLINE f"\nWould you like to make one now? [y/n]: "NEWLINE )NEWLINENEWLINE if not create_whitelist_now.strip().lower().startswith("y"):NEWLINE return NoneNEWLINENEWLINE while True:NEWLINE ip_address = input(NEWLINE f"\nEnter a valid IP address, optionally with CIDR notation: "NEWLINE ).strip()NEWLINENEWLINE if not re.findall(r".*\/(\d+)", ip_address):NEWLINE ip_address = ip_address.split("/")[0] + "/32"NEWLINENEWLINE if ip_address_or_range_is_valid(ip_address):NEWLINE with open(self.whitelist_path, "w") as whitelist_file:NEWLINE whitelist_file.write(ip_address)NEWLINENEWLINE print(f"\nwhitelist.txt created with IP address {ip_address}")NEWLINENEWLINE return load_and_validate_whitelist(self.whitelist_path)NEWLINENEWLINE else:NEWLINE print(f"\nInvalid IP address.")NEWLINE continueNEWLINENEWLINE else:NEWLINE print(f"Loading whitelist.txt...")NEWLINE whitelist = load_and_validate_whitelist(self.whitelist_path)NEWLINE if whitelist:NEWLINE print(NEWLINE f"A whitelist.txt file was found that contains at least one valid"NEWLINE f" IP address or range."NEWLINE )NEWLINE if print_values:NEWLINE print(f"Whitelisted IP addresses:\n " + "\n ".join(whitelist))NEWLINE return whitelistNEWLINENEWLINE def create_scenario(self, scenario_name_or_path, profile, user_name):NEWLINE scenario_name = normalize_scenario_name(scenario_name_or_path)NEWLINE scenario_dir = os.path.join(self.scenarios_dir, scenario_name)NEWLINENEWLINE if not scenario_dir or not scenario_name or not os.path.exists(scenario_dir):NEWLINE if not scenario_name:NEWLINE return print(NEWLINE f"No recognized scenario name was entered. Did you mean one of"NEWLINE f" these?\n " + f"\n ".join(self.scenario_names)NEWLINE )NEWLINE else:NEWLINE return print(NEWLINE f"No scenario named {scenario_name} exists in the scenarios"NEWLINE f" directory. Did you mean one of these?"NEWLINE f"\n " + f"\n ".join(self.scenario_names)NEWLINE )NEWLINENEWLINE if not os.path.exists(self.whitelist_path):NEWLINE cg_whitelist = self.configure_or_check_whitelist(auto=True)NEWLINE else:NEWLINE cg_whitelist = self.configure_or_check_whitelist()NEWLINENEWLINE if not cg_whitelist:NEWLINE print(NEWLINE f"A valid whitelist.txt file must exist in the {self.base_dir}"NEWLINE f' directory before "create" may be used.'NEWLINE )NEWLINE returnNEWLINENEWLINE # Create a scenario-instance folder in the project root directory.NEWLINE # This command should fail with an explanatory error message if aNEWLINE # scenario-instance of the same root name (i.e. without the CGID) alreadyNEWLINE # exists.NEWLINE instance_path = find_scenario_instance_dir(self.base_dir, scenario_name)NEWLINE if instance_path is not None:NEWLINE print(NEWLINE f"\n*************************************************************************************************\n"NEWLINE f"Updating previously deployed {scenario_name} scenario. \n\n"NEWLINE f"To recreate this scenario from scratch instead, run `./cloudgoat destroy {scenario_name}` first."NEWLINE f"\n*************************************************************************************************\n"NEWLINE )NEWLINE else:NEWLINE cgid = generate_cgid_using_username(user_name)NEWLINE instance_path = os.path.join(NEWLINE self.base_dir, f"{scenario_name}_{cgid}"NEWLINE )NEWLINENEWLINE # Copy all the terraform files from the "/scenarios/scenario-name" folderNEWLINE # to the scenario-instance folder.NEWLINE source_dir_contents = os.path.join(scenario_dir, ".")NEWLINE shutil.copytree(source_dir_contents, instance_path)NEWLINENEWLINE if os.path.exists(os.path.join(instance_path, "start.sh")):NEWLINE print(f"\nNow running {scenario_name}'s start.sh...")NEWLINE start_script_process = subprocess.Popen(NEWLINE ["sh", "start.sh"], cwd=instance_pathNEWLINE )NEWLINE start_script_process.wait()NEWLINE else:NEWLINE passNEWLINENEWLINE terraform = Terraform(NEWLINE working_dir=os.path.join(instance_path, "terraform")NEWLINE )NEWLINENEWLINE init_retcode, init_stdout, init_stderr = terraform.init(NEWLINE capture_output=False, no_color=IsNotFlaggedNEWLINE )NEWLINE if init_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform init", init_retcode, init_stdout, init_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f"\n[cloudgoat] terraform init completed with no error code.")NEWLINE cgid = instance_path.split('/')[-1].split('_')[-1]NEWLINE plan_retcode, plan_stdout, plan_stderr = terraform.plan(NEWLINE capture_output=False,NEWLINE var={NEWLINE "cgid": cgid,NEWLINE "cg_whitelist": cg_whitelist,NEWLINE "profile": profile,NEWLINE "region": self.aws_region,NEWLINE },NEWLINE no_color=IsNotFlagged,NEWLINE )NEWLINE # For some reason, `python-terraform`'s `terraform init` returns "2" evenNEWLINE # when it appears to succeed. For that reason, it will temporarily permitNEWLINE # retcode 2.NEWLINE if plan_retcode not in (0, 2):NEWLINE display_terraform_step_error(NEWLINE "terraform plan", plan_retcode, plan_stdout, plan_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f"\n[cloudgoat] terraform plan completed with no error code.")NEWLINENEWLINE apply_retcode, apply_stdout, apply_stderr = terraform.apply(NEWLINE capture_output=False,NEWLINE var={NEWLINE "cgid": cgid,NEWLINE "cg_whitelist": cg_whitelist,NEWLINE "profile": profile,NEWLINE "region": self.aws_region,NEWLINE },NEWLINE skip_plan=True,NEWLINE no_color=IsNotFlagged,NEWLINE )NEWLINE if apply_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform apply", apply_retcode, apply_stdout, apply_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f"\n[cloudgoat] terraform apply completed with no error code.")NEWLINENEWLINE # python-terraform uses the '-json' flag by default.NEWLINE # The documentation for `output` suggests using output_cmd to receive theNEWLINE # library's standard threeple return value.NEWLINE # Can't use capture_output here because we need to write stdout to a file.NEWLINE output_retcode, output_stdout, output_stderr = terraform.output_cmd('--json')NEWLINENEWLINE if output_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform output", output_retcode, output_stdout, output_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f"\n[cloudgoat] terraform output completed with no error code.")NEWLINENEWLINE # Within this output will be values that begin with "cloudgoat_output".NEWLINE # Each line of console output which contains this tag will be written intoNEWLINE # a text file named "start.txt" in the scenario-instance folder.NEWLINE start_file_path = os.path.join(instance_path, "start.txt")NEWLINE with open(start_file_path, "w") as start_file:NEWLINE output = json.loads(output_stdout)NEWLINE for k, v in output.items():NEWLINE l = f"{k} = {v['value']}"NEWLINE print(l)NEWLINE start_file.write(l + '\n')NEWLINENEWLINE print(f"\n[cloudgoat] Output file written to:\n\n {start_file_path}\n")NEWLINENEWLINE def destroy_all_scenarios(self, profile):NEWLINE # Information gathering.NEWLINE extant_scenario_instance_names_and_paths = list()NEWLINE for scenario_name in self.scenario_names:NEWLINE scenario_instance_dir_path = find_scenario_instance_dir(NEWLINE self.base_dir, scenario_nameNEWLINE )NEWLINENEWLINE if scenario_instance_dir_path is None:NEWLINE continueNEWLINE else:NEWLINE extant_scenario_instance_names_and_paths.append(NEWLINE (scenario_name, scenario_instance_dir_path)NEWLINE )NEWLINE print(f"Scenario instance for {scenario_name} found.")NEWLINENEWLINE if not extant_scenario_instance_names_and_paths:NEWLINE print(f"\n No scenario instance directories exist.\n")NEWLINE returnNEWLINE else:NEWLINE print(NEWLINE f"\n {len(extant_scenario_instance_names_and_paths)} scenario"NEWLINE f" instance directories found."NEWLINE )NEWLINENEWLINE # Iteration.NEWLINE success_count, failure_count, skipped_count = 0, 0, 0NEWLINENEWLINE for scenario_name, instance_path in extant_scenario_instance_names_and_paths:NEWLINE print(f"\n--------------------------------\n")NEWLINENEWLINE # Confirmation.NEWLINE delete_permission = input(f'Destroy "{scenario_name}"? [y/n]: ')NEWLINENEWLINE if not delete_permission.strip()[0].lower() == "y":NEWLINE skipped_count += 1NEWLINE print(f"\nSkipped destruction of {scenario_name}.\n")NEWLINE continueNEWLINENEWLINE # Terraform execution.NEWLINE terraform_directory = os.path.join(instance_path, "terraform")NEWLINENEWLINE if os.path.exists(os.path.join(terraform_directory, "terraform.tfstate")):NEWLINE terraform = Terraform(working_dir=terraform_directory)NEWLINENEWLINE cgid = extract_cgid_from_dir_name(os.path.basename(instance_path))NEWLINENEWLINE destroy_retcode, destroy_stdout, destroy_stderr = terraform.destroy(NEWLINE capture_output=False,NEWLINE var={NEWLINE "cgid": cgid,NEWLINE "cg_whitelist": list(),NEWLINE "profile": profile,NEWLINE "region": self.aws_region,NEWLINE },NEWLINE no_color=IsNotFlagged,NEWLINE )NEWLINE if destroy_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform destroy",NEWLINE destroy_retcode,NEWLINE destroy_stdout,NEWLINE destroy_stderr,NEWLINE )NEWLINE failure_count += 1NEWLINE # Subsequent destroys should not be skipped when one fails.NEWLINE continueNEWLINE else:NEWLINE print(NEWLINE f"\n[cloudgoat] terraform destroy completed with no error code."NEWLINE )NEWLINE else:NEWLINE print(NEWLINE f"\nNo terraform.tfstate file was found in the scenario instance's"NEWLINE f' terraform directory, so "terraform destroy" will not be run.'NEWLINE )NEWLINENEWLINE # Scenario instance directory trashing.NEWLINE trash_dir = create_dir_if_nonexistent(self.base_dir, "trash")NEWLINENEWLINE trashed_instance_path = os.path.join(NEWLINE trash_dir, os.path.basename(instance_path)NEWLINE )NEWLINENEWLINE shutil.move(instance_path, trashed_instance_path)NEWLINENEWLINE success_count += 1NEWLINENEWLINE print(NEWLINE f"\nSuccessfully destroyed {scenario_name}."NEWLINE f"\nScenario instance files have been moved to {trashed_instance_path}"NEWLINE )NEWLINENEWLINE # Iteration summary.NEWLINE print(NEWLINE f"\nDestruction complete."NEWLINE f"\n {success_count} scenarios successfully destroyed"NEWLINE f"\n {failure_count} destroys failed"NEWLINE f"\n {skipped_count} skipped\n"NEWLINE )NEWLINENEWLINE returnNEWLINENEWLINE def destroy_scenario(self, scenario_name_or_path, profile, confirmed=False):NEWLINE # Information gathering.NEWLINE scenario_name = normalize_scenario_name(scenario_name_or_path)NEWLINE scenario_instance_dir_path = find_scenario_instance_dir(NEWLINE self.base_dir, scenario_nameNEWLINE )NEWLINENEWLINE if scenario_instance_dir_path is None:NEWLINE print(NEWLINE f'[cloudgoat] Error: No scenario instance for "{scenario_name}" found.'NEWLINE f" Try: cloudgoat.py list deployed"NEWLINE )NEWLINE returnNEWLINENEWLINE instance_name = os.path.basename(scenario_instance_dir_path)NEWLINENEWLINE # Confirmation.NEWLINE if not confirmed:NEWLINE delete_permission = input(f'Destroy "{instance_name}"? [y/n]: ').strip()NEWLINE if not delete_permission or not delete_permission[0].lower() == "y":NEWLINE print(f"\nCancelled destruction of {instance_name}.\n")NEWLINE returnNEWLINENEWLINE # Terraform execution.NEWLINE terraform_directory = os.path.join(scenario_instance_dir_path, "terraform")NEWLINENEWLINE if os.path.exists(os.path.join(terraform_directory, "terraform.tfstate")):NEWLINE terraform = Terraform(working_dir=terraform_directory)NEWLINENEWLINE cgid = extract_cgid_from_dir_name(NEWLINE os.path.basename(scenario_instance_dir_path)NEWLINE )NEWLINENEWLINE destroy_retcode, destroy_stdout, destroy_stderr = terraform.destroy(NEWLINE capture_output=False,NEWLINE var={NEWLINE "cgid": cgid,NEWLINE "cg_whitelist": list(),NEWLINE "profile": profile,NEWLINE "region": self.aws_region,NEWLINE },NEWLINE no_color=IsNotFlagged,NEWLINE )NEWLINE if destroy_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform destroy", destroy_retcode, destroy_stdout, destroy_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print("\n[cloudgoat] terraform destroy completed with no error code.")NEWLINE else:NEWLINE print(NEWLINE f"\nNo terraform.tfstate file was found in the scenario instance's"NEWLINE f' terraform directory, so "terraform destroy" will not be run.'NEWLINE )NEWLINENEWLINE # Scenario instance directory trashing.NEWLINE trash_dir = create_dir_if_nonexistent(self.base_dir, "trash")NEWLINENEWLINE trashed_instance_path = os.path.join(NEWLINE trash_dir, os.path.basename(scenario_instance_dir_path)NEWLINE )NEWLINENEWLINE shutil.move(scenario_instance_dir_path, trashed_instance_path)NEWLINENEWLINE print(NEWLINE f"\nSuccessfully destroyed {instance_name}."NEWLINE f"\nScenario instance files have been moved to {trashed_instance_path}"NEWLINE )NEWLINENEWLINE returnNEWLINENEWLINE def list_all_scenarios(self):NEWLINE undeployed_scenarios = list()NEWLINE deployed_scenario_instance_paths = list()NEWLINENEWLINE for scenario_name in self.scenario_names:NEWLINE scenario_instance_dir_path = find_scenario_instance_dir(NEWLINE self.base_dir, scenario_nameNEWLINE )NEWLINE if scenario_instance_dir_path:NEWLINE deployed_scenario_instance_paths.append(scenario_instance_dir_path)NEWLINENEWLINE else:NEWLINE undeployed_scenarios.append(scenario_name)NEWLINENEWLINE print(NEWLINE f"\n Deployed scenario instances: {len(deployed_scenario_instance_paths)}"NEWLINE )NEWLINENEWLINE for scenario_instance_dir_path in deployed_scenario_instance_paths:NEWLINE directory_name = os.path.basename(scenario_instance_dir_path)NEWLINE scenario_name, cgid = directory_name.split("_cgid")NEWLINE print(NEWLINE f"\n {scenario_name}"NEWLINE f"\n CGID: {'cgid' + cgid}"NEWLINE f"\n Path: {scenario_instance_dir_path}"NEWLINE )NEWLINENEWLINE print(f"\n Undeployed scenarios: {len(undeployed_scenarios)}")NEWLINENEWLINE # Visual spacing.NEWLINE if undeployed_scenarios:NEWLINE print(f"")NEWLINENEWLINE for scenario_name in undeployed_scenarios:NEWLINE print(f" {scenario_name}")NEWLINENEWLINE print(f"")NEWLINENEWLINE def list_deployed_scenario_instances(self):NEWLINE deployed_scenario_instances = list()NEWLINE for scenario_name in self.scenario_names:NEWLINE scenario_instance_dir_path = find_scenario_instance_dir(NEWLINE self.base_dir, scenario_nameNEWLINE )NEWLINENEWLINE if scenario_instance_dir_path is None:NEWLINE continueNEWLINE else:NEWLINE deployed_scenario_instances.append(scenario_instance_dir_path)NEWLINENEWLINE if not deployed_scenario_instances:NEWLINE print(NEWLINE f'\n No scenario instance directories exist. Try "list undeployed" or'NEWLINE f' "list all"\n'NEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(NEWLINE f"\n Deployed scenario instances: {len(deployed_scenario_instances)}"NEWLINE )NEWLINENEWLINE for scenario_instance_dir_path in deployed_scenario_instances:NEWLINE directory_name = os.path.basename(scenario_instance_dir_path)NEWLINE scenario_name, cgid = directory_name.split("_cgid")NEWLINENEWLINE print(NEWLINE f"\n {scenario_name}"NEWLINE f"\n CGID: {'cgid' + cgid}"NEWLINE f"\n Path: {scenario_instance_dir_path}"NEWLINE )NEWLINENEWLINE print("")NEWLINENEWLINE def list_undeployed_scenarios(self):NEWLINE undeployed_scenarios = list()NEWLINE for scenario_name in self.scenario_names:NEWLINE if not find_scenario_instance_dir(self.base_dir, scenario_name):NEWLINE undeployed_scenarios.append(scenario_name)NEWLINENEWLINE if undeployed_scenarios:NEWLINE return print(NEWLINE f"\n Undeployed scenarios: {len(undeployed_scenarios)}\n\n "NEWLINE + f"\n ".join(undeployed_scenarios)NEWLINE + f"\n"NEWLINE )NEWLINE else:NEWLINE return print(NEWLINE f'\n All scenarios have been deployed. Try "list deployed" or "list'NEWLINE f' all"\n'NEWLINE )NEWLINENEWLINE def list_scenario_instance(self, scenario_name_or_path):NEWLINE scenario_name = normalize_scenario_name(scenario_name_or_path)NEWLINE scenario_instance_dir_path = find_scenario_instance_dir(NEWLINE self.base_dir, scenario_nameNEWLINE )NEWLINENEWLINE if scenario_instance_dir_path is None:NEWLINE print(NEWLINE f'[cloudgoat] Error: No scenario instance for "{scenario_name}" found.'NEWLINE f" Try: cloudgoat.py list deployed"NEWLINE )NEWLINE returnNEWLINENEWLINE terraform = Terraform(NEWLINE working_dir=os.path.join(scenario_instance_dir_path, "terraform")NEWLINE )NEWLINENEWLINE show_retcode, show_stdout, show_stderr = terraform.show(NEWLINE capture_output=False, no_color=IsNotFlaggedNEWLINE )NEWLINE if show_retcode != 0:NEWLINE display_terraform_step_error(NEWLINE "terraform show", show_retcode, show_stdout, show_stderrNEWLINE )NEWLINE returnNEWLINE else:NEWLINE print(f"\n[cloudgoat] terraform show completed with no error code.")NEWLINENEWLINE returnNEWLINENEWLINE
from pycocotools.coco import COCONEWLINENEWLINEimport matplotlib.pyplot as pltNEWLINEimport cv2NEWLINENEWLINEimport osNEWLINEimport numpy as npNEWLINEimport randomNEWLINEimport torchNEWLINEimport torchvision.transforms as transformsNEWLINEfrom torch.utils.data import DataLoader,DatasetNEWLINEfrom skimage import io,transformNEWLINEimport matplotlib.pyplot as pltNEWLINEimport osNEWLINEimport torchNEWLINEfrom torchvision import transformsNEWLINEimport numpy as npNEWLINEimport PIL.Image as ImageNEWLINEfrom skimage import measureNEWLINEfrom tqdm import tqdmNEWLINEimport torch.nn.functional as FNEWLINEfrom skimage.morphology import convex_hull_imageNEWLINENEWLINEclass SuperPixelGet(Dataset): #继承DatasetNEWLINE def __init__(self, segments_label, segments_tensor, g_theta_m, data_num):NEWLINE self.segments_label = segments_label.cuda()NEWLINE self.segments_tensor = segments_tensor.cuda()NEWLINE self.g_theta_m = g_theta_m.cuda()NEWLINE self.data_num = data_numNEWLINENEWLINENEWLINE self.zero_layer = torch.zeros_like(self.segments_tensor)NEWLINE self.one_layer = torch.ones_like(self.segments_tensor)NEWLINENEWLINE NEWLINE def __len__(self):NEWLINE return self.data_numNEWLINE NEWLINE def __getitem__(self, index):NEWLINENEWLINE attack_region_tmp = self.zero_layer.clone()NEWLINE flag = torch.rand_like( self.segments_label) < self.g_theta_m NEWLINE for i in range(flag.shape[0]):NEWLINE if flag[i]:NEWLINE sp = self.segments_label[i]NEWLINE attack_region_tmp = torch.where(self.segments_tensor==sp, self.one_layer, attack_region_tmp)NEWLINE NEWLINE # # get convex envolopeNEWLINE # attack_region_tmp_np = attack_region_tmp.cpu().numpy()NEWLINE # attack_region_tmp_label_np = measure.label(attack_region_tmp_np)NEWLINE # connect_region_number = int(np.max(attack_region_tmp_label_np))NEWLINE NEWLINE # one_np = np.ones_like(attack_region_tmp_np)NEWLINE # zero_np = np.zeros_like(attack_region_tmp_np)NEWLINE # attack_region_envolope_np = np.zeros_like(attack_region_tmp_np)NEWLINENEWLINE # for i in range(connect_region_number):NEWLINE # binary_map = np.where(attack_region_tmp_label_np==i+1, one_np, zero_np)NEWLINE # convex_env = convex_hull_image(binary_map)NEWLINENEWLINE # attack_region_envolope_np = attack_region_envolope_np + convex_envNEWLINE # passNEWLINENEWLINENEWLINE # attack_region_tmp = torch.from_numpy(attack_region_envolope_np)NEWLINE # attack_region_tmp = torch.clamp(attack_region_tmp, 0, 1).cuda()NEWLINENEWLINE return attack_region_tmp, flagNEWLINENEWLINEif __name__=='__main__':NEWLINE segments_tensor = [NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,5,5,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,4,5,5,0,0],NEWLINE [0,0,1,1,1,2,3,3,3,3,4,4,4,5,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE [0,0,1,1,1,2,2,2,3,3,4,4,6,6,5,0,0],NEWLINE ]NEWLINE segments_tensor = torch.Tensor(segments_tensor)NEWLINE g_theta_m = torch.Tensor([0.1,0.2,0.3,0.4,0.5,0.6])NEWLINE data_num = 555NEWLINE data = SuperPixelGet(torch.Tensor([1,2,3,4,5,6]), segments_tensor, g_theta_m, data_num)NEWLINE dataloader = DataLoader(data, batch_size=128,shuffle=False) #使用DataLoader加载数据NEWLINENEWLINE max_len = 0NEWLINE for epoch in range(10):NEWLINE for i_batch, batch_data in enumerate(dataloader):NEWLINENEWLINE sum_tensor = torch.sum(batch_data, dim=0)NEWLINE sum_tensor = sum_tensor/torch.max(sum_tensor)NEWLINE sum_tensor = sum_tensor.unsqueeze(0).unsqueeze(0)NEWLINE sum_tensor = F.interpolate(sum_tensor, (800, 800), mode='nearest').squeeze()NEWLINE sum_pil = transforms.ToPILImage()(sum_tensor)NEWLINE sum_pil.show()NEWLINENEWLINE passNEWLINENEWLINENEWLINE
"""Base definitions for RPC."""NEWLINEfrom __future__ import absolute_importNEWLINENEWLINEimport socketNEWLINEimport timeNEWLINEimport jsonNEWLINEimport errnoNEWLINEimport structNEWLINEimport randomNEWLINEimport loggingNEWLINENEWLINEfrom ..._ffi.function import _init_apiNEWLINEfrom ..._ffi.base import py_strNEWLINENEWLINE# Magic header for RPC data planeNEWLINERPC_MAGIC = 0xff271NEWLINE# magic header for RPC tracker(control plane)NEWLINERPC_TRACKER_MAGIC = 0x2f271NEWLINE# sucess responseNEWLINERPC_CODE_SUCCESS = RPC_MAGIC + 0NEWLINE# duplicate key in proxyNEWLINERPC_CODE_DUPLICATE = RPC_MAGIC + 1NEWLINE# cannot found matched key in serverNEWLINERPC_CODE_MISMATCH = RPC_MAGIC + 2NEWLINENEWLINENEWLINEclass TrackerCode(object):NEWLINE """Enumeration code for the RPC tracker"""NEWLINE FAIL = -1NEWLINE SUCCESS = 0NEWLINE PING = 1NEWLINE STOP = 2NEWLINE PUT = 3NEWLINE REQUEST = 4NEWLINE UPDATE_INFO = 5NEWLINE SUMMARY = 6NEWLINE GET_PENDING_MATCHKEYS = 7NEWLINENEWLINERPC_SESS_MASK = 128NEWLINENEWLINENEWLINEdef recvall(sock, nbytes):NEWLINE """Receive all nbytes from socket.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE sock: SocketNEWLINE The socketNEWLINENEWLINE nbytes : intNEWLINE Number of bytes to be received.NEWLINE """NEWLINE res = []NEWLINE nread = 0NEWLINE while nread < nbytes:NEWLINE chunk = sock.recv(min(nbytes - nread, 1024))NEWLINE if not chunk:NEWLINE raise IOError("connection reset")NEWLINE nread += len(chunk)NEWLINE res.append(chunk)NEWLINE return b"".join(res)NEWLINENEWLINENEWLINEdef sendjson(sock, data):NEWLINE """send a python value to remote via jsonNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE sock : SocketNEWLINE The socketNEWLINENEWLINE data : objectNEWLINE Python value to be sent.NEWLINE """NEWLINE data = json.dumps(data)NEWLINE sock.sendall(struct.pack("<i", len(data)))NEWLINE sock.sendall(data.encode("utf-8"))NEWLINENEWLINENEWLINEdef recvjson(sock):NEWLINE """receive python value from remote via jsonNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE sock : SocketNEWLINE The socketNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE value : objectNEWLINE The value received.NEWLINE """NEWLINE size = struct.unpack("<i", recvall(sock, 4))[0]NEWLINE data = json.loads(py_str(recvall(sock, size)))NEWLINE return dataNEWLINENEWLINENEWLINEdef random_key(prefix, cmap=None):NEWLINE """Generate a random keyNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE prefix : strNEWLINE The string prefixNEWLINENEWLINE cmap : dictNEWLINE Conflict mapNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE key : strNEWLINE The generated random keyNEWLINE """NEWLINE if cmap:NEWLINE while True:NEWLINE key = prefix + str(random.random())NEWLINE if key not in cmap:NEWLINE return keyNEWLINE else:NEWLINE return prefix + str(random.random())NEWLINENEWLINENEWLINEdef connect_with_retry(addr, timeout=60, retry_period=5, silent=False):NEWLINE """Connect to a TPC address with retryNEWLINENEWLINE This function is only reliable to short period of server restart.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE addr : tupleNEWLINE address tupleNEWLINENEWLINE timeout : floatNEWLINE Timeout during retryNEWLINENEWLINE retry_period : floatNEWLINE Number of seconds before we retry again.NEWLINENEWLINE silent: boolNEWLINE whether run in silent modeNEWLINE """NEWLINE tstart = time.time()NEWLINE while True:NEWLINE try:NEWLINE sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)NEWLINE sock.connect(addr)NEWLINE return sockNEWLINE except socket.error as sock_err:NEWLINE if sock_err.args[0] not in (errno.ECONNREFUSED,):NEWLINE raise sock_errNEWLINE period = time.time() - tstartNEWLINE if period > timeout:NEWLINE raise RuntimeError(NEWLINE "Failed to connect to server %s" % str(addr))NEWLINE if not silent:NEWLINE logging.info("Cannot connect to tracker%s, retry in %g secs...",NEWLINE str(addr), retry_period)NEWLINE time.sleep(retry_period)NEWLINENEWLINENEWLINE# Still use tvm.contrib.rpc for the foreign functionsNEWLINE_init_api("tvm.contrib.rpc", "tvm.contrib.rpc.base")NEWLINE
#!/usr/bin/env python3NEWLINENEWLINE__author__ = 'xtof'NEWLINENEWLINEimport argparseNEWLINEimport reNEWLINEimport loggingNEWLINEimport sysNEWLINEfrom subprocess import Popen, PIPENEWLINEfrom docker import ClientNEWLINEfrom docker.utils import kwargs_from_envNEWLINEfrom dns.resolver import ResolverNEWLINEfrom dns.exception import DNSExceptionNEWLINENEWLINE# Templates for nsupdateNEWLINEzone_update_start_template = """server {0}NEWLINEzone {1}.NEWLINE"""NEWLINENEWLINEzone_update_template = """update delete {0}.{1}NEWLINEupdate add {0}.{1} 60 A {2}NEWLINE"""NEWLINENEWLINEzone_update_add_alias_template = """update delete {0}.{1}NEWLINEupdate add {0}.{1} 600 CNAME {2}.{1}.NEWLINEupdate add {2}.{1} 600 TXT dockerDDNS-alias:{0}:NEWLINE"""NEWLINENEWLINEzone_update_delete_record_template = """update delete {0}.{1}NEWLINE"""NEWLINENEWLINENEWLINEdef register_container(container_id):NEWLINE detail = c.inspect_container(container_id)NEWLINE container_hostname = detail["Config"]["Hostname"]NEWLINE container_name = detail["Name"].split('/', 1)[1]NEWLINE network_mode = detail["HostConfig"]["NetworkMode"]NEWLINE if network_mode == "default":NEWLINE container_ip = detail["NetworkSettings"]["IPAddress"]NEWLINE else :NEWLINE container_ip = detail["NetworkSettings"]["Networks"][network_mode]["IPAddress"]NEWLINE logging.info("Updating %s to ip (%s|%s) -> %s", container_id, container_hostname, container_name, container_ip)NEWLINE if not args.dry_run:NEWLINE nsupdate = Popen(['nsupdate', '-k', args.key], stdin=PIPE)NEWLINE nsupdate.stdin.write(bytes(zone_update_start_template.format(args.server, args.zone), "UTF-8"))NEWLINE nsupdate.stdin.write(bytes(zone_update_template.format(container_hostname, args.domain, container_ip), "UTF-8"))NEWLINE if container_name != container_hostname:NEWLINE nsupdate.stdin.write(bytes(zone_update_add_alias_template.format(container_name, args.domain, container_hostname), "UTF-8"))NEWLINE if re.search("_", container_name):NEWLINE alternate_name = re.sub('_','-',container_name)NEWLINE logging.info("Adding alternate name %s to %s", alternate_name, container_name)NEWLINE nsupdate.stdin.write(bytes(zone_update_add_alias_template.format(alternate_name, args.domain, container_hostname), "UTF-8"))NEWLINE nsupdate.stdin.write(bytes("send\n", "UTF-8"))NEWLINE nsupdate.stdin.close()NEWLINENEWLINENEWLINEdef remove_container(container_id):NEWLINE logging.info("Destroying %s", container_id)NEWLINE short_id = container_id[:12]NEWLINE record_to_delete = [short_id]NEWLINE logging.debug("Looking for alias to %s.%s", short_id, args.domain)NEWLINENEWLINE try:NEWLINE answers = resolver.query("{0}.{1}.".format(short_id, args.domain), "TXT", raise_on_no_answer=False).rrsetNEWLINE if answers:NEWLINE for answer in answers:NEWLINE logging.debug("Checking TXT record %s for alias", answer)NEWLINE match = re.search(r"dockerDDNS-alias:([^:]+):", answer.to_text())NEWLINE if match:NEWLINE record_to_delete.append(match.group(1))NEWLINE except DNSException as e:NEWLINE logging.error("Cannot get TXT record for %s: %s", short_id, e)NEWLINE except:NEWLINE logging.error("Unexpected error: %s", sys.exc_info()[0])NEWLINE raiseNEWLINENEWLINE if not args.dry_run:NEWLINE nsupdate = Popen(['nsupdate', '-k', args.key], stdin=PIPE)NEWLINE nsupdate.stdin.write(bytes(zone_update_start_template.format(args.server, args.zone), "UTF-8"))NEWLINENEWLINE for record in record_to_delete:NEWLINE logging.info("Removing record for %s", record)NEWLINE nsupdate.stdin.write(bytes(zone_update_delete_record_template.format(record, args.domain), "UTF-8"))NEWLINENEWLINE nsupdate.stdin.write(bytes("send\n", "UTF-8"))NEWLINE nsupdate.stdin.close()NEWLINENEWLINENEWLINEparser = argparse.ArgumentParser()NEWLINENEWLINEparser.add_argument("--key", required=True, help="Path to the dynamic dns key")NEWLINEparser.add_argument("--server", help="IP/Hostname of the server to update", default="127.0.0.1")NEWLINEparser.add_argument("--domain", help="The domain to be updated", required=True)NEWLINEparser.add_argument("--zone", help="The zone to be updated (default to the domain)")NEWLINENEWLINEparser.add_argument("--dry-run", help="Run in dry run mode without doing any update", default=False, action="store_true")NEWLINEparser.add_argument("--catchup", help="Register the running containers on startup", default=False, action="store_true")NEWLINENEWLINEparser.add_argument("--log-level", help="Log level to display", default="INFO")NEWLINEparser.add_argument("--log-file", help="Where to put the logs", default="/var/log/docker-ddns.log")NEWLINENEWLINEargs = parser.parse_args()NEWLINENEWLINElogging.basicConfig(level=getattr(logging,args.log_level.upper()),NEWLINE format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',NEWLINE filename=(args.log_file if args.log_file != '-' else None))NEWLINENEWLINEif args.zone is None:NEWLINE args.zone = args.domainNEWLINENEWLINElogging.info("Starting with arguments %s", args)NEWLINENEWLINEc = Client(**(kwargs_from_env()))NEWLINENEWLINEresolver = Resolver()NEWLINEresolver.nameservers = [args.server]NEWLINENEWLINEif args.catchup:NEWLINE logging.info("Registering existing containers")NEWLINE containers = c.containers()NEWLINE for container in containers:NEWLINE register_container(container["Id"])NEWLINENEWLINENEWLINE# TODO use docker-py streaming APINEWLINEevents_pipe = Popen(['docker', 'events'], stdout=PIPE)NEWLINENEWLINEwhile True:NEWLINE line = events_pipe.stdout.readline()NEWLINE if line != '':NEWLINE text_line = line.decode().rstrip()NEWLINE logging.debug("Read line %s", text_line)NEWLINE m = re.search(r".*\s+container\s+([a-z]+)\s+([0-9a-f]{64}).*$", text_line)NEWLINE if m:NEWLINE event = m.group(1)NEWLINE container_id = m.group(2)NEWLINE logging.debug("Got event %s for container %s", event, container_id)NEWLINENEWLINE if event == "start":NEWLINE register_container(container_id)NEWLINE elif event == "destroy":NEWLINE remove_container(container_id)NEWLINE else:NEWLINE print("Done return code: ", events_pipe.returncode)NEWLINE breakNEWLINENEWLINE# 2014-11-28T15:32:04.000000000+01:00 a3d66b00acc9adbdbdbc91cc664d2d94b6a07cc4295c5cf54fcc595e2aa92a43: (from mongo:latest) restartNEWLINE# 2015-03-05T08:36:14.000000000+01:00 eb75c1a5ad836d008b0fd66bf6b1ea353510175e8caa619e59d9851029b1ceca: (from ggtools/zabbix-server:latest) exec_start: ifconfig eth0NEWLINENEWLINE# docker Version: 1.12.1 NEWLINE# 2017-01-11T20:46:26.268651386-05:00 container start bc340bc76860452fb99ce15101765107f0cf32005e9fcb3261407d81d247307d (image=ubuntu:14.04, name=toto)NEWLINE
#!/usr/bin/env python3NEWLINE# coding=utf-8NEWLINENEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINENEWLINENEWLINEdef show_predict_probability(frame):NEWLINE x1 = frame['x1']NEWLINE x2 = frame['x2']NEWLINE probability = frame['probabilities']NEWLINE class1_x = [x1[i] for i, x in enumerate(probability) if x >= 0.5]NEWLINE class1_y = [x2[i] for i, x in enumerate(probability) if x >= 0.5]NEWLINE class2_x = [x1[i] for i, x in enumerate(probability) if x < 0.5]NEWLINE class2_y = [x2[i] for i, x in enumerate(probability) if x < 0.5]NEWLINE print('class1_x = \n %s' % class1_x)NEWLINE print('class1_y = \n %s' % class1_y)NEWLINE print('class2_x = \n %s' % class2_x)NEWLINE print('class2_y = \n %s' % class2_y)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE frame = pd.DataFrame()NEWLINE n = 5NEWLINE npx1 = np.linspace(0, 9, n)NEWLINE npx2 = np.linspace(100, 109, n)NEWLINE X1, X2 = np.meshgrid(npx1, npx2)NEWLINE frame['x1'] = np.reshape(X1, n * n)NEWLINE frame['x2'] = np.reshape(X2, n * n)NEWLINE frame['probabilities'] = np.random.rand(n * n)NEWLINE print(frame)NEWLINE show_predict_probability(frame)NEWLINE
#!/usr/bin/env pythonNEWLINENEWLINEimport jsonNEWLINEimport clickNEWLINENEWLINENEWLINE@click.command()NEWLINE@click.option("--in-private")NEWLINEdef dump_pem_to_jwks(in_private):NEWLINE try:NEWLINE from jwcrypto.jwk import JWK, JWKSetNEWLINE except ImportError as e:NEWLINE msg = "You have to install jwcrypto to use this function"NEWLINE print(msg)NEWLINE raise ImportError(msg) from eNEWLINENEWLINE with open(in_private, "rb") as privfile:NEWLINE data = privfile.read()NEWLINENEWLINE jwk = JWK()NEWLINE jwk.import_from_pem(data)NEWLINENEWLINE jwks = JWKSet()NEWLINE jwks.add(jwk)NEWLINENEWLINE raw = jwks.export(private_keys=True)NEWLINE formatted = json.dumps(json.loads(raw), indent=2)NEWLINE with open("private.json", "w") as priv_jwks_file:NEWLINE priv_jwks_file.write(formatted)NEWLINENEWLINE raw = jwks.export(private_keys=False)NEWLINE formatted = json.dumps(json.loads(raw), indent=2)NEWLINE with open("public.json", "w") as public_jwks_file:NEWLINE public_jwks_file.write(formatted)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE dump_pem_to_jwks()NEWLINE
from __future__ import division, absolute_import, print_functionNEWLINENEWLINE__copyright__ = "Copyright (C) 2015 Andreas Kloeckner"NEWLINENEWLINE__license__ = """NEWLINEPermission is hereby granted, free of charge, to any person obtaining a copyNEWLINEof this software and associated documentation files (the "Software"), to dealNEWLINEin the Software without restriction, including without limitation the rightsNEWLINEto use, copy, modify, merge, publish, distribute, sublicense, and/or sellNEWLINEcopies of the Software, and to permit persons to whom the Software isNEWLINEfurnished to do so, subject to the following conditions:NEWLINENEWLINEThe above copyright notice and this permission notice shall be included inNEWLINEall copies or substantial portions of the Software.NEWLINENEWLINETHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORNEWLINEIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINEFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINELIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,NEWLINEOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INNEWLINETHE SOFTWARE.NEWLINE"""NEWLINENEWLINEimport sysNEWLINEimport numpy as np # noqaNEWLINEimport numpy.linalg as laNEWLINEimport loopy as lpNEWLINEimport pyopencl as clNEWLINEimport pyopencl.clrandom # noqaNEWLINENEWLINEimport loggingNEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEtry:NEWLINE import faulthandlerNEWLINEexcept ImportError:NEWLINE passNEWLINEelse:NEWLINE faulthandler.enable()NEWLINENEWLINEfrom pyopencl.tools import pytest_generate_tests_for_pyopencl \NEWLINE as pytest_generate_testsNEWLINENEWLINE__all__ = [NEWLINE "pytest_generate_tests",NEWLINE "cl" # 'cl.create_some_context'NEWLINE ]NEWLINENEWLINENEWLINEfrom loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_2 # noqaNEWLINENEWLINENEWLINEdef test_diff(ctx_factory):NEWLINE ctx = ctx_factory()NEWLINE queue = cl.CommandQueue(ctx)NEWLINENEWLINE knl = lp.make_function(NEWLINE """{ [i,j]: 0<=i,j<n }""",NEWLINE """NEWLINE <> a = 1/(1+sinh(x[i] + y[j])**2)NEWLINE z[i] = sum(j, exp(a * x[j]))NEWLINE """)NEWLINENEWLINE knl = lp.fix_parameters(knl, n=50)NEWLINENEWLINE from loopy.transform.diff import diff_kernelNEWLINE dknl, diff_map = diff_kernel(knl, "z", "x")NEWLINE dknl = lp.make_program(dknl)NEWLINE dknl = lp.remove_unused_arguments(dknl)NEWLINENEWLINE dknl = lp.add_inames_to_insn(dknl, "diff_i0", "writes:a_dx or writes:a")NEWLINENEWLINE print(dknl)NEWLINENEWLINE n = 50NEWLINE x = np.random.randn(n)NEWLINE y = np.random.randn(n)NEWLINENEWLINE dx = np.random.randn(n)NEWLINENEWLINE fac = 1e-1NEWLINE h1 = 1e-4NEWLINE h2 = h1 * facNEWLINENEWLINE evt, (z0,) = knl(queue, x=x, y=y)NEWLINE evt, (z1,) = knl(queue, x=(x + h1*dx), y=y)NEWLINE evt, (z2,) = knl(queue, x=(x + h2*dx), y=y)NEWLINENEWLINE dknl = lp.set_options(dknl, write_cl=True)NEWLINE evt, (df,) = dknl(queue, x=x, y=y)NEWLINENEWLINE diff1 = (z1-z0)NEWLINE diff2 = (z2-z0)NEWLINENEWLINE diff1_predicted = df.dot(h1*dx)NEWLINE diff2_predicted = df.dot(h2*dx)NEWLINENEWLINE err1 = la.norm(diff1 - diff1_predicted) / la.norm(diff1)NEWLINE err2 = la.norm(diff2 - diff2_predicted) / la.norm(diff2)NEWLINE print(err1, err2)NEWLINENEWLINE assert (err2 < err1 * fac * 1.1).all()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE if len(sys.argv) > 1:NEWLINE exec(sys.argv[1])NEWLINE else:NEWLINE from pytest import mainNEWLINE main([__file__])NEWLINENEWLINE# vim: foldmethod=markerNEWLINE
"""Log consumers are responsible for fetching chia logsNEWLINEand propagating them to subscribers for further handling.NEWLINENEWLINEThis abstraction should provide an easy ability to switch betweenNEWLINElocal file reader and fetching logs from a remote machine.NEWLINEThe latter has not been implemented yet. Feel free to add it.NEWLINE"""NEWLINENEWLINE# stdNEWLINEimport loggingNEWLINEimport subprocessNEWLINEfrom abc import ABC, abstractmethodNEWLINEfrom pathlib import Path, PurePosixPath, PureWindowsPath, PurePathNEWLINEfrom threading import ThreadNEWLINEfrom typing import List, Optional, TupleNEWLINENEWLINE# projectNEWLINEfrom src.config import check_keys, is_win_platformNEWLINEfrom src.util import OSNEWLINENEWLINE# libNEWLINEimport paramikoNEWLINENEWLINENEWLINEclass LogConsumerSubscriber(ABC):NEWLINE """Interface for log consumer subscribers (i.e. handlers)"""NEWLINENEWLINE @abstractmethodNEWLINE def consume_logs(self, logs: str):NEWLINE """This method will be called when new logs are available"""NEWLINE passNEWLINENEWLINENEWLINEclass LogConsumer(ABC):NEWLINE """Abstract class providing common interface for log consumers"""NEWLINENEWLINE def __init__(self):NEWLINE self._subscribers: List[LogConsumerSubscriber] = []NEWLINENEWLINE @abstractmethodNEWLINE def stop(self):NEWLINE passNEWLINENEWLINE def subscribe(self, subscriber: LogConsumerSubscriber):NEWLINE self._subscribers.append(subscriber)NEWLINENEWLINE def _notify_subscribers(self, logs: str):NEWLINE for subscriber in self._subscribers:NEWLINE subscriber.consume_logs(logs)NEWLINENEWLINENEWLINEclass FileLogConsumer(LogConsumer):NEWLINE """Specific implementation for a simple file consumer"""NEWLINENEWLINE def __init__(self, log_path: Path):NEWLINE logging.info("Enabled file log consumer.")NEWLINE super().__init__()NEWLINE self._log_path = log_pathNEWLINE self._is_running = TrueNEWLINE self._thread = Thread(target=self._consume_loop)NEWLINE self._thread.start()NEWLINENEWLINE def stop(self):NEWLINE logging.info("Stopping")NEWLINE self._is_running = FalseNEWLINENEWLINE def _consume_loop(self):NEWLINE expanded_user_log_path = str(self._log_path.expanduser())NEWLINE logging.info(f"Consuming log file from {expanded_user_log_path}")NEWLINENEWLINE if is_win_platform():NEWLINE consume_command_args = ["powershell.exe", "get-content", expanded_user_log_path, "-tail", "1", "-wait"]NEWLINE else:NEWLINE consume_command_args = ["tail", "-F", expanded_user_log_path]NEWLINENEWLINE f = subprocess.Popen(consume_command_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)NEWLINE while self._is_running:NEWLINE log_line = f.stdout.readline().decode(encoding="utf-8")NEWLINE self._notify_subscribers(log_line)NEWLINENEWLINENEWLINEclass NetworkLogConsumer(LogConsumer):NEWLINE """Consume logs over the network"""NEWLINENEWLINE def __init__(NEWLINE self, remote_log_path: PurePath, remote_user: str, remote_host: str, remote_port: int, remote_platform: OSNEWLINE ):NEWLINE logging.info("Enabled network log consumer.")NEWLINE super().__init__()NEWLINENEWLINE self._remote_user = remote_userNEWLINE self._remote_host = remote_hostNEWLINE self._remote_port = remote_portNEWLINE self._remote_log_path = remote_log_pathNEWLINE self._remote_platform = remote_platformNEWLINENEWLINE self._ssh_client = paramiko.client.SSHClient()NEWLINE self._ssh_client.load_system_host_keys()NEWLINE self._ssh_client.connect(hostname=self._remote_host, username=self._remote_user, port=self._remote_port)NEWLINENEWLINE # Start threadNEWLINE self._is_running = TrueNEWLINE self._thread = Thread(target=self._consume_loop)NEWLINE self._thread.start()NEWLINENEWLINE def stop(self):NEWLINE logging.info("Stopping")NEWLINE self._is_running = FalseNEWLINENEWLINE def _consume_loop(self):NEWLINE logging.info(NEWLINE f"Consuming remote log file {self._remote_log_path}"NEWLINE + f" from {self._remote_host}:{self._remote_port} ({self._remote_platform})"NEWLINE )NEWLINENEWLINE if self._remote_platform == OS.WINDOWS:NEWLINE stdin, stdout, stderr = self._ssh_client.exec_command(NEWLINE f"powershell.exe Get-Content {self._remote_log_path} -Wait -Tail 1"NEWLINE )NEWLINE else:NEWLINE stdin, stdout, stderr = self._ssh_client.exec_command(f"tail -F {self._remote_log_path}")NEWLINENEWLINE while self._is_running:NEWLINE log_line = stdout.readline()NEWLINE self._notify_subscribers(log_line)NEWLINENEWLINENEWLINEdef get_host_info(host: str, user: str, path: str, port: int) -> Tuple[OS, PurePath]:NEWLINENEWLINE client = paramiko.client.SSHClient()NEWLINE client.load_system_host_keys()NEWLINE client.connect(hostname=host, username=user, port=port)NEWLINENEWLINE stdin, stdout, stderr = client.exec_command("uname -a")NEWLINE fout: str = stdout.readline().lower()NEWLINE ferr: str = stderr.readline().lower()NEWLINENEWLINE if "linux" in fout:NEWLINE return OS.LINUX, PurePosixPath(path)NEWLINE elif "darwin" in fout:NEWLINE return OS.MACOS, PurePosixPath(path)NEWLINE elif "not recognized" in ferr:NEWLINE return OS.WINDOWS, PureWindowsPath(path)NEWLINE else:NEWLINE logging.error("Found unsupported platform on remote host, assuming Linux and hope for the best.")NEWLINENEWLINE return OS.LINUX, PurePosixPath(path)NEWLINENEWLINENEWLINEdef create_log_consumer_from_config(config: dict) -> Optional[LogConsumer]:NEWLINE enabled_consumer = NoneNEWLINE for consumer in config.keys():NEWLINE if config[consumer]["enable"]:NEWLINE if enabled_consumer:NEWLINE logging.error("Detected multiple enabled consumers. This is unsupported configuration!")NEWLINE return NoneNEWLINE enabled_consumer = consumerNEWLINE if enabled_consumer is None:NEWLINE logging.error("Couldn't find enabled log consumer in config.yaml")NEWLINE return NoneNEWLINENEWLINE enabled_consumer_config = config[enabled_consumer]NEWLINENEWLINE if enabled_consumer == "file_log_consumer":NEWLINE if not check_keys(required_keys=["file_path"], config=enabled_consumer_config):NEWLINE return NoneNEWLINE return FileLogConsumer(log_path=Path(enabled_consumer_config["file_path"]))NEWLINENEWLINE if enabled_consumer == "network_log_consumer":NEWLINE if not check_keys(NEWLINE required_keys=["remote_file_path", "remote_host", "remote_user"],NEWLINE config=enabled_consumer_config,NEWLINE ):NEWLINE return NoneNEWLINENEWLINE # default SSH Port : 22NEWLINE remote_port = enabled_consumer_config.get("remote_port", 22)NEWLINENEWLINE platform, path = get_host_info(NEWLINE enabled_consumer_config["remote_host"],NEWLINE enabled_consumer_config["remote_user"],NEWLINE enabled_consumer_config["remote_file_path"],NEWLINE remote_port,NEWLINE )NEWLINENEWLINE return NetworkLogConsumer(NEWLINE remote_log_path=path,NEWLINE remote_host=enabled_consumer_config["remote_host"],NEWLINE remote_user=enabled_consumer_config["remote_user"],NEWLINE remote_port=remote_port,NEWLINE remote_platform=platform,NEWLINE )NEWLINENEWLINE logging.error("Unhandled consumer type")NEWLINE return NoneNEWLINE
# -*- coding: utf-8 -*-NEWLINE#NEWLINE# Copyright (C) 2021 Graz University of Technology.NEWLINE# Copyright (C) 2021 CERN.NEWLINE# Copyright (C) 2021 TU Wien.NEWLINE#NEWLINE# Invenio-Records-Permissions is free software; you can redistribute itNEWLINE# and/or modify it under the terms of the MIT License; see LICENSE file forNEWLINE# more details.NEWLINENEWLINE"""Pytest configuration.NEWLINENEWLINESee https://pytest-invenio.readthedocs.io/ for documentation on which testNEWLINEfixtures are available.NEWLINE"""NEWLINENEWLINEfrom typing import PatternNEWLINENEWLINEimport pytestNEWLINEfrom flask_principal import Identity, UserNeedNEWLINEfrom invenio_access.permissions import any_user, authenticated_user, \NEWLINE system_processNEWLINEfrom invenio_db import dbNEWLINEfrom invenio_pidstore.models import PersistentIdentifier, PIDStatusNEWLINEfrom invenio_records_permissions.generators import AnyUser, \NEWLINE AuthenticatedUser, SystemProcessNEWLINENEWLINEfrom invenio_rdm_records.records import RDMParent, RDMRecordNEWLINEfrom invenio_rdm_records.services.generators import IfRestricted, RecordOwnersNEWLINENEWLINENEWLINEdef _public_record():NEWLINE record = RDMRecord({}, access={})NEWLINE record.access.protection.set("public", "public")NEWLINE return recordNEWLINENEWLINENEWLINEdef _restricted_record():NEWLINE record = RDMRecord({}, access={})NEWLINE record.access.protection.set("restricted", "restricted")NEWLINE return recordNEWLINENEWLINENEWLINEdef _owned_record():NEWLINE parent = RDMParent.create({})NEWLINE parent.access.owners.add({"user": 16})NEWLINE parent.access.owners.add({"user": 17})NEWLINE record = RDMRecord.create({}, parent=parent)NEWLINE return recordNEWLINENEWLINENEWLINEdef _then_needs():NEWLINE return {authenticated_user, system_process}NEWLINENEWLINENEWLINEdef _else_needs():NEWLINE return {any_user, system_process}NEWLINENEWLINENEWLINE#NEWLINE# TestsNEWLINE#NEWLINE@pytest.mark.parametrize(NEWLINE "field,record_fun,expected_needs_fun", [NEWLINE ("record", _public_record, _else_needs),NEWLINE ("record", _restricted_record, _then_needs),NEWLINE ("files", _public_record, _else_needs),NEWLINE ("files", _restricted_record, _then_needs),NEWLINE ]NEWLINE)NEWLINEdef test_ifrestricted_needs(field, record_fun, expected_needs_fun):NEWLINE """Test the IfRestricted generator."""NEWLINE generator = IfRestricted(NEWLINE field,NEWLINE then_=[AuthenticatedUser(), SystemProcess()],NEWLINE else_=[AnyUser(), SystemProcess()]NEWLINE )NEWLINE assert generator.needs(record=record_fun()) == expected_needs_fun()NEWLINE assert generator.excludes(record=record_fun()) == set()NEWLINENEWLINENEWLINEdef test_ifrestricted_query():NEWLINE """Test the query generation."""NEWLINE generator = IfRestricted(NEWLINE "record",NEWLINE then_=[AuthenticatedUser()],NEWLINE else_=[AnyUser()]NEWLINE )NEWLINE assert generator.query_filter(identity=any_user).to_dict() == {NEWLINE 'bool': {NEWLINE 'should': [NEWLINE {'match': {'access.record': 'restricted'}},NEWLINE {'match': {'access.record': 'public'}}NEWLINE ]NEWLINE }NEWLINE }NEWLINENEWLINENEWLINEdef test_record_owner(app, mocker):NEWLINE generator = RecordOwners()NEWLINE record = _owned_record()NEWLINENEWLINE assert generator.needs(record=record) == [NEWLINE UserNeed(16),NEWLINE UserNeed(17),NEWLINE ]NEWLINENEWLINE assert generator.excludes(record=record) == []NEWLINENEWLINE # Anonymous identity.NEWLINE assert not generator.query_filter(identity=mocker.Mock(provides=[]))NEWLINENEWLINE # Authenticated identityNEWLINE query_filter = generator.query_filter(NEWLINE identity=mocker.Mock(NEWLINE provides=[mocker.Mock(method='id', value=15)]NEWLINE )NEWLINE )NEWLINENEWLINE expected_query_filter = {NEWLINE "terms": {NEWLINE "parent.access.owned_by.user": [15]NEWLINE }NEWLINE }NEWLINE assert query_filter.to_dict() == expected_query_filterNEWLINE
#!/usr/bin/env python3NEWLINE# -*- coding:utf-8 -*-NEWLINE"""NEWLINEreceive_logs_direct.py published log messages are going to be broadcast to all the receivesNEWLINE"""NEWLINE# Pika is a pure-Python implementation of the AMQP 0-9-1 protocolNEWLINEimport pikaNEWLINEimport sysNEWLINENEWLINENEWLINE# guest user can only connect via localhostNEWLINE#credentials = pika.PlainCredentials('guest', 'guest')NEWLINEcredentials = pika.PlainCredentials('pi', 'macintosh')NEWLINEconnection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.31.156',NEWLINE port=5672,NEWLINE virtual_host='/',NEWLINE credentials=credentials))NEWLINEchannel = connection.channel()NEWLINE# declare the exchangeNEWLINEchannel.exchange_declare(exchange='direct_logs',NEWLINE exchange_type='direct')NEWLINENEWLINEresult = channel.queue_declare(exclusive=True)NEWLINEqueue_name = result.method.queueNEWLINENEWLINEseverities = sys.argv[1:]NEWLINENEWLINEif not severities:NEWLINE sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])NEWLINE sys.exit(1)NEWLINENEWLINEfor severity in severities:NEWLINE channel.queue_bind(exchange='direct_logs',NEWLINE queue=queue_name,NEWLINE routing_key=severity)NEWLINENEWLINENEWLINEprint(" [*] Waiting for logs. To exit press CTRL+C")NEWLINENEWLINENEWLINEdef callback(ch, method, properties, body):NEWLINE print(" [x] %r:%r" % (method.routing_key, body))NEWLINENEWLINENEWLINEchannel.basic_consume(callback,NEWLINE queue=queue_name,NEWLINE no_ack=True)NEWLINENEWLINEchannel.start_consuming()NEWLINE"""NEWLINEPlease keep in mind that this and other tutorials are, well, tutorials, They demonstrate one new concept at a time and mayNEWLINEintentionally oversimplify some things and leave out others. For example topics such as connection management, error handling,NEWLINEconnection recovery, concurrency and metric collection are largely omitted for the sake of brevity. Such simplified code NEWLINEshould not be considered production ready.NEWLINENEWLINE"""
# Copyright 2016-2018 Intel CorporationNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ------------------------------------------------------------------------------NEWLINENEWLINEimport loggingNEWLINENEWLINEfrom sawtooth_xo.processor.xo_payload import XoPayloadNEWLINEfrom sawtooth_xo.processor.xo_state import GameNEWLINEfrom sawtooth_xo.processor.xo_state import XoStateNEWLINEfrom sawtooth_xo.processor.xo_state import XO_NAMESPACENEWLINENEWLINEfrom sawtooth_sdk.processor.handler import TransactionHandlerNEWLINEfrom sawtooth_sdk.processor.exceptions import InvalidTransactionNEWLINEfrom sawtooth_sdk.processor.exceptions import InternalErrorNEWLINENEWLINENEWLINELOGGER = logging.getLogger(__name__)NEWLINENEWLINENEWLINEclass XoTransactionHandler(TransactionHandler):NEWLINE # Disable invalid-overridden-method. The sawtooth-sdk expects these to beNEWLINE # properties.NEWLINE # pylint: disable=invalid-overridden-methodNEWLINE @propertyNEWLINE def family_name(self):NEWLINE return 'xo'NEWLINENEWLINE @propertyNEWLINE def family_versions(self):NEWLINE return ['1.0']NEWLINENEWLINE @propertyNEWLINE def namespaces(self):NEWLINE return [XO_NAMESPACE]NEWLINENEWLINE def apply(self, transaction, context):NEWLINENEWLINE header = transaction.headerNEWLINE signer = header.signer_public_keyNEWLINENEWLINE xo_payload = XoPayload.from_bytes(transaction.payload)NEWLINENEWLINE xo_state = XoState(context)NEWLINENEWLINE if xo_payload.action == 'delete':NEWLINE game = xo_state.get_game(xo_payload.name)NEWLINENEWLINE if game is None:NEWLINE raise InvalidTransaction(NEWLINE 'Invalid action: game does not exist')NEWLINENEWLINE xo_state.delete_game(xo_payload.name)NEWLINENEWLINE elif xo_payload.action == 'create':NEWLINENEWLINE if xo_state.get_game(xo_payload.name) is not None:NEWLINE raise InvalidTransaction(NEWLINE 'Invalid action: Game already exists: {}'.format(NEWLINE xo_payload.name))NEWLINENEWLINE game = Game(name=xo_payload.name,NEWLINE board="-" * 9,NEWLINE state="P1-NEXT",NEWLINE player1="",NEWLINE player2="")NEWLINENEWLINE xo_state.set_game(xo_payload.name, game)NEWLINE _display("Player {} created a game.".format(signer[:6]))NEWLINENEWLINE elif xo_payload.action == 'take':NEWLINE game = xo_state.get_game(xo_payload.name)NEWLINENEWLINE if game is None:NEWLINE raise InvalidTransaction(NEWLINE 'Invalid action: Take requires an existing game')NEWLINENEWLINE if game.state in ('P1-WIN', 'P2-WIN', 'TIE'):NEWLINE raise InvalidTransaction('Invalid Action: Game has ended')NEWLINENEWLINE if (game.player1 and game.state == 'P1-NEXT'NEWLINE and game.player1 != signer) or \NEWLINE (game.player2 and game.state == 'P2-NEXT'NEWLINE and game.player2 != signer):NEWLINE raise InvalidTransaction(NEWLINE "Not this player's turn: {}".format(signer[:6]))NEWLINENEWLINE if game.board[xo_payload.space - 1] != '-':NEWLINE raise InvalidTransaction(NEWLINE 'Invalid Action: space {} already taken'.format(NEWLINE xo_payload))NEWLINENEWLINE if game.player1 == '':NEWLINE game.player1 = signerNEWLINENEWLINE elif game.player2 == '':NEWLINE game.player2 = signerNEWLINENEWLINE upd_board = _update_board(game.board,NEWLINE xo_payload.space,NEWLINE game.state)NEWLINENEWLINE upd_game_state = _update_game_state(game.state, upd_board)NEWLINENEWLINE game.board = upd_boardNEWLINE game.state = upd_game_stateNEWLINENEWLINE xo_state.set_game(xo_payload.name, game)NEWLINE _display(NEWLINE "Player {} takes space: {}\n\n".format(NEWLINE signer[:6],NEWLINE xo_payload.space)NEWLINE + _game_data_to_str(NEWLINE game.board,NEWLINE game.state,NEWLINE game.player1,NEWLINE game.player2,NEWLINE xo_payload.name))NEWLINENEWLINE else:NEWLINE raise InvalidTransaction('Unhandled action: {}'.format(NEWLINE xo_payload.action))NEWLINENEWLINENEWLINEdef _update_board(board, space, state):NEWLINE if state == 'P1-NEXT':NEWLINE mark = 'X'NEWLINE elif state == 'P2-NEXT':NEWLINE mark = 'O'NEWLINENEWLINE index = space - 1NEWLINENEWLINE # replace the index-th space with mark, leave everything else the sameNEWLINE return ''.join([NEWLINE current if square != index else markNEWLINE for square, current in enumerate(board)NEWLINE ])NEWLINENEWLINENEWLINEdef _update_game_state(game_state, board):NEWLINE x_wins = _is_win(board, 'X')NEWLINE o_wins = _is_win(board, 'O')NEWLINENEWLINE if x_wins and o_wins:NEWLINE raise InternalError('Two winners (there can be only one)')NEWLINENEWLINE if x_wins:NEWLINE return 'P1-WIN'NEWLINENEWLINE if o_wins:NEWLINE return 'P2-WIN'NEWLINENEWLINE if '-' not in board:NEWLINE return 'TIE'NEWLINENEWLINE if game_state == 'P1-NEXT':NEWLINE return 'P2-NEXT'NEWLINENEWLINE if game_state == 'P2-NEXT':NEWLINE return 'P1-NEXT'NEWLINENEWLINE if game_state in ('P1-WINS', 'P2-WINS', 'TIE'):NEWLINE return game_stateNEWLINENEWLINE raise InternalError('Unhandled state: {}'.format(game_state))NEWLINENEWLINENEWLINEdef _is_win(board, letter):NEWLINE wins = ((1, 2, 3), (4, 5, 6), (7, 8, 9),NEWLINE (1, 4, 7), (2, 5, 8), (3, 6, 9),NEWLINE (1, 5, 9), (3, 5, 7))NEWLINENEWLINE for win in wins:NEWLINE if (board[win[0] - 1] == letterNEWLINE and board[win[1] - 1] == letterNEWLINE and board[win[2] - 1] == letter):NEWLINE return TrueNEWLINE return FalseNEWLINENEWLINENEWLINEdef _game_data_to_str(board, game_state, player1, player2, name):NEWLINE board = list(board.replace("-", " "))NEWLINE out = ""NEWLINE out += "GAME: {}\n".format(name)NEWLINE out += "PLAYER 1: {}\n".format(player1[:6])NEWLINE out += "PLAYER 2: {}\n".format(player2[:6])NEWLINE out += "STATE: {}\n".format(game_state)NEWLINE out += "\n"NEWLINE out += "{} | {} | {}\n".format(board[0], board[1], board[2])NEWLINE out += "---|---|---\n"NEWLINE out += "{} | {} | {}\n".format(board[3], board[4], board[5])NEWLINE out += "---|---|---\n"NEWLINE out += "{} | {} | {}".format(board[6], board[7], board[8])NEWLINE return outNEWLINENEWLINENEWLINEdef _display(msg):NEWLINE n = msg.count("\n")NEWLINENEWLINE if n > 0:NEWLINE msg = msg.split("\n")NEWLINE length = max(len(line) for line in msg)NEWLINE else:NEWLINE length = len(msg)NEWLINE msg = [msg]NEWLINENEWLINE # pylint: disable=logging-not-lazyNEWLINE LOGGER.debug("+" + (length + 2) * "-" + "+")NEWLINE for line in msg:NEWLINE LOGGER.debug("+ " + line.center(length) + " +")NEWLINE LOGGER.debug("+" + (length + 2) * "-" + "+")NEWLINE
import sysNEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINEimport networkx as nxNEWLINENEWLINEimport hypercomparison.utilsNEWLINEimport hypercomparison.networksNEWLINEimport hypercomparison.embedding_centeredNEWLINEfrom hypercomparison.link_prediction import LinkPredictionTaskNEWLINEfrom hypercomparison.network_train_test_splitter import NetworkTrainTestSplitterWithMSTNEWLINENEWLINE# Force numpy to only use single thread in linear algebraNEWLINEimport osNEWLINEos.environ['OPENBLAS_NUM_THREADS'] = '1'NEWLINEos.environ['MKL_NUM_THREADS'] = '1'NEWLINENEWLINElogger = hypercomparison.utils.get_logger(__name__)NEWLINENEWLINEnetwork_name = sys.argv[1]NEWLINEdimensions = int(sys.argv[2])NEWLINENEWLINEout_path = sys.argv[-1]NEWLINEresult_list = []NEWLINEnetwork = hypercomparison.networks.RealNetwork(network_name)NEWLINEif dimensions > len(network.G.nodes()):NEWLINE dimensions = len(network.G.nodes())NEWLINE NEWLINElogger.info("Working on network {} dimension {}".format(network_name, dimensions))NEWLINE#split test and negative edgesNEWLINEsplitter = NetworkTrainTestSplitterWithMST(network.G)NEWLINEG, test_edges = splitter.train_test_split()NEWLINEnegative_edges = splitter.generate_negative_edges()NEWLINE#calculate embeddingsNEWLINEadjacency_matrix = nx.to_numpy_array(G)NEWLINEe = np.linalg.eigvals(adjacency_matrix)NEWLINEbeta=1/max(e).real - 0.001NEWLINElogger.info("network {} dimension {}, beta calculated".format(network_name, dimensions))NEWLINEembeddings = hypercomparison.embedding_centered.HOPE(dimension=dimensions, beta=beta).train(G)NEWLINE#perform link predictionNEWLINEtest = LinkPredictionTask(test_edges, negative_edges, embeddings, name=network_name) NEWLINEroc_auc, aupr, average_precision, precision = test.do_link_prediction()NEWLINEresult_list.append([network_name, dimensions, beta, roc_auc, aupr, average_precision, precision])NEWLINEdf = pd.DataFrame(result_list, columns=['network_name', 'dimensions', 'beta', 'roc_auc', 'aupr', 'average_precision', 'precision'])NEWLINENEWLINEdf.to_csv(out_path, index=None)
import clickNEWLINEfrom collections import CounterNEWLINEfrom typing import List, TupleNEWLINENEWLINEfrom .utils import assertCommitsNEWLINENEWLINENEWLINEclass EmailRedactParamType(click.ParamType):NEWLINE name = 'emailredact'NEWLINENEWLINE def convert(self, value, param, ctx) -> Tuple[str, str, str]:NEWLINE if ":" in value:NEWLINE try:NEWLINE old, new = value.split(":", maxsplit=1)NEWLINE name = ""NEWLINE if ":" in new:NEWLINE new, name = new.split(":")NEWLINE return (old, new, name)NEWLINE except ValueError:NEWLINE self.fail(NEWLINE f'{value} is not in the format 'NEWLINE 'old-email[:new-email[:new-name]]',NEWLINE param, ctx,NEWLINE )NEWLINE return (value, "", "")NEWLINENEWLINENEWLINEEMAIL_REDACT = EmailRedactParamType()NEWLINEGHNOREPLY = "{username}@users.noreply.github.com"NEWLINENEWLINENEWLINE@click.command('redact-email')NEWLINE@click.argument('addresses', nargs=-1, type=EMAIL_REDACT)NEWLINE@click.option('-r', '--replacement', type=str,NEWLINE default="noreply@gitprivacy.invalid",NEWLINE help="Email address used as replacement.")NEWLINE@click.option('-g', '--use-github-noreply', 'use_ghnoreply', is_flag=True,NEWLINE help="Interpret custom replacements as GitHub usernames"NEWLINE " and construct noreply addresses.")NEWLINE@click.pass_contextNEWLINEdef redact_email(ctx: click.Context,NEWLINE addresses: List[Tuple[str, str, str]],NEWLINE replacement: str,NEWLINE use_ghnoreply: bool) -> None:NEWLINE """Redact email addresses from existing commits."""NEWLINE if not addresses:NEWLINE return # nothing to doNEWLINENEWLINE assertCommits(ctx)NEWLINE repo = ctx.obj.repoNEWLINENEWLINE env_cmd = ""NEWLINE with click.progressbar(addresses,NEWLINE label="Redacting emails") as bar:NEWLINE for old, new, name in bar:NEWLINE if new and use_ghnoreply:NEWLINE new = GHNOREPLY.format(username=new)NEWLINE if not new:NEWLINE new = replacementNEWLINE env_cmd += get_env_cmd("COMMITTER", old, new, name)NEWLINE env_cmd += get_env_cmd("AUTHOR", old, new, name)NEWLINE filter_cmd = ["git", "filter-branch", "-f",NEWLINE "--env-filter", env_cmd,NEWLINE "--",NEWLINE "HEAD"]NEWLINE repo.git.execute(command=filter_cmd)NEWLINENEWLINENEWLINEdef get_env_cmd(role: str, old: str, new: str, name: str) -> str:NEWLINE name_env = f'GIT_{role}_NAME="{name}"'NEWLINE return (NEWLINE f'if test "$GIT_{role}_EMAIL" = "{old}"; then 'NEWLINE f'export GIT_{role}_EMAIL="{new}" 'NEWLINE f'{name_env if name else ""}; 'NEWLINE 'fi; 'NEWLINE )NEWLINENEWLINENEWLINE@click.command('list-email')NEWLINE@click.option('-a', '--all', 'check_all', is_flag=True,NEWLINE help="Include all local references.")NEWLINE@click.option('-e', '--email-only', is_flag=True,NEWLINE help="Only consider actors' email address when counting contributions.")NEWLINE@click.pass_contextNEWLINEdef list_email(ctx: click.Context, check_all: bool, email_only: bool) -> None:NEWLINE """List all author and committer identities."""NEWLINE assertCommits(ctx)NEWLINE repo = ctx.obj.repoNEWLINE commits = repo.iter_commits("HEAD" if not check_all else "--all")NEWLINE authors: Counter[str] = Counter()NEWLINE committers: Counter[str] = Counter()NEWLINE if email_only:NEWLINE to_str = lambda a: a.emailNEWLINE else:NEWLINE to_str = _actor_to_strNEWLINE for commit in commits:NEWLINE authors[to_str(commit.author)] += 1NEWLINE committers[to_str(commit.committer)] += 1NEWLINE total = authors + committersNEWLINE for actor in sorted(total):NEWLINE print(f"{actor} (total: {total[actor]}, author: {authors[actor]}, committer: {committers[actor]})")NEWLINENEWLINEdef _actor_to_str(actor):NEWLINE return f"{actor.name} <{actor.email}>"NEWLINE
import osNEWLINEimport shutilNEWLINENEWLINEfrom riptide.config.document.command import CommandNEWLINEfrom riptide.config.files import path_in_projectNEWLINEfrom riptide.engine.abstract import ExecErrorNEWLINENEWLINEIMAGE = 'alpine'NEWLINE# TODO: Since permissions are always mapped to user->root under Windows, there won't be permissionNEWLINE# problems under windows. We could probably just use the AbstractEngine implementation there.NEWLINENEWLINENEWLINEdef rm(engine, path, project: 'Project'):NEWLINE """NEWLINE Removes path from the hosts file system using a Docker container running root.NEWLINE See AbstractEngine.path_rm for general usage.NEWLINE """NEWLINE # TODO: Safety checks, this function is potentially really dangerous right nowNEWLINE if not path_in_project(path, project):NEWLINE raise PermissionError(f"Tried to delete a file/directory that is not within the project: {path}")NEWLINE if not os.path.exists(path):NEWLINE returnNEWLINE name_of_file = os.path.basename(path)NEWLINE file_dir = os.path.abspath(os.path.join(path, '..'))NEWLINE command = Command({NEWLINE 'image': IMAGE,NEWLINE 'command': f'rm -rf /cmd_target/{name_of_file}',NEWLINE 'additional_volumes': {'target': {NEWLINE 'host': file_dir,NEWLINE 'container': '/cmd_target',NEWLINE 'mode': 'rw'NEWLINE }}NEWLINE })NEWLINE command.validate()NEWLINE command.freeze()NEWLINE (exit_code, output) = engine.cmd_detached(project, command, run_as_root=True)NEWLINE if exit_code != 0:NEWLINE raise ExecError(f"Error removing the path ({str(exit_code)}) {path}: {output}")NEWLINENEWLINENEWLINEdef copy(engine, fromm, to, project: 'Project'):NEWLINE """NEWLINE Copy files from the hosts file system using a Docker container running root.NEWLINE See AbstractEngine.path_copy for general usage.NEWLINE """NEWLINE if not path_in_project(to, project):NEWLINE raise PermissionError(f"Tried to copy into a path that is not within the project: {fromm} -> {to}")NEWLINE if not os.path.exists(fromm):NEWLINE raise OSError(f"Tried to copy a directory/file that does not exist: {fromm}")NEWLINE if not os.path.exists(os.path.dirname(to)):NEWLINE raise OSError(f"Tried to copy into a path that does not exist: {to}")NEWLINE command = Command({NEWLINE 'image': IMAGE,NEWLINE 'command': 'cp -a /copy_from/. /copy_to/',NEWLINE 'additional_volumes': {'fromm': {NEWLINE 'host': fromm,NEWLINE 'container': '/copy_from',NEWLINE 'mode': 'ro'NEWLINE }, 'to': {NEWLINE 'host': to,NEWLINE 'container': '/copy_to',NEWLINE 'mode': 'rw'NEWLINE }}NEWLINE })NEWLINE command.validate()NEWLINE command.freeze()NEWLINE (exit_code, output) = engine.cmd_detached(project, command, run_as_root=True)NEWLINE if exit_code != 0:NEWLINE raise ExecError(f"Error copying the directory ({str(exit_code)}) {fromm} -> {to}: {output}")NEWLINE
# This file was automatically generated by SWIG (http://www.swig.org).NEWLINE# Version 2.0.11NEWLINE#NEWLINE# Do not make changes to this file unless you know what you are doing--modifyNEWLINE# the SWIG interface file instead.NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINEfrom sys import version_infoNEWLINEif version_info >= (2,6,0):NEWLINE def swig_import_helper():NEWLINE from os.path import dirnameNEWLINE import impNEWLINE fp = NoneNEWLINE try:NEWLINE fp, pathname, description = imp.find_module('_param_ArmISA', [dirname(__file__)])NEWLINE except ImportError:NEWLINE import _param_ArmISANEWLINE return _param_ArmISANEWLINE if fp is not None:NEWLINE try:NEWLINE _mod = imp.load_module('_param_ArmISA', fp, pathname, description)NEWLINE finally:NEWLINE fp.close()NEWLINE return _modNEWLINE _param_ArmISA = swig_import_helper()NEWLINE del swig_import_helperNEWLINEelse:NEWLINE import _param_ArmISANEWLINEdel version_infoNEWLINEtry:NEWLINE _swig_property = propertyNEWLINEexcept NameError:NEWLINE pass # Python < 2.2 doesn't have 'property'.NEWLINEdef _swig_setattr_nondynamic(self,class_type,name,value,static=1):NEWLINE if (name == "thisown"): return self.this.own(value)NEWLINE if (name == "this"):NEWLINE if type(value).__name__ == 'SwigPyObject':NEWLINE self.__dict__[name] = valueNEWLINE returnNEWLINE method = class_type.__swig_setmethods__.get(name,None)NEWLINE if method: return method(self,value)NEWLINE if (not static):NEWLINE self.__dict__[name] = valueNEWLINE else:NEWLINE raise AttributeError("You cannot add attributes to %s" % self)NEWLINENEWLINEdef _swig_setattr(self,class_type,name,value):NEWLINE return _swig_setattr_nondynamic(self,class_type,name,value,0)NEWLINENEWLINEdef _swig_getattr(self,class_type,name):NEWLINE if (name == "thisown"): return self.this.own()NEWLINE method = class_type.__swig_getmethods__.get(name,None)NEWLINE if method: return method(self)NEWLINE raise AttributeError(name)NEWLINENEWLINEdef _swig_repr(self):NEWLINE try: strthis = "proxy of " + self.this.__repr__()NEWLINE except: strthis = ""NEWLINE return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)NEWLINENEWLINEtry:NEWLINE _object = objectNEWLINE _newclass = 1NEWLINEexcept AttributeError:NEWLINE class _object : passNEWLINE _newclass = 0NEWLINENEWLINENEWLINEdef _swig_setattr_nondynamic_method(set):NEWLINE def set_attr(self,name,value):NEWLINE if (name == "thisown"): return self.this.own(value)NEWLINE if hasattr(self,name) or (name == "this"):NEWLINE set(self,name,value)NEWLINE else:NEWLINE raise AttributeError("You cannot add attributes to %s" % self)NEWLINE return set_attrNEWLINENEWLINENEWLINEimport m5.internal.enum_DecoderFlavourNEWLINEimport m5.internal.param_ArmPMUNEWLINEimport m5.internal.param_PlatformNEWLINEimport m5.internal.param_IntrControlNEWLINEimport m5.internal.param_SystemNEWLINEimport m5.internal.enum_MemoryModeNEWLINEimport m5.internal.AddrRange_vectorNEWLINEimport m5.internal.AbstractMemory_vectorNEWLINEimport m5.internal.param_AbstractMemoryNEWLINEimport m5.internal.param_MemObjectNEWLINEimport m5.internal.param_ClockedObjectNEWLINEimport m5.internal.param_ClockDomainNEWLINEimport m5.internal.param_SimObjectNEWLINEimport m5.internal.drainNEWLINEimport m5.internal.serializeNEWLINEimport m5.internal.enum_PwrStateNEWLINEimport m5.internal.param_PowerModelNEWLINEimport m5.internal.PowerModelState_vectorNEWLINEimport m5.internal.param_PowerModelStateNEWLINEimport m5.internal.param_SubSystemNEWLINEimport m5.internal.param_ThermalDomainNEWLINEimport m5.internal.SimObject_vectorNEWLINEimport m5.internal.param_ThermalModelNEWLINEclass ArmISA_COLONS_ISA(m5.internal.param_SimObject.SimObject):NEWLINE thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')NEWLINE def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")NEWLINE __repr__ = _swig_reprNEWLINEArmISA_COLONS_ISA_swigregister = _param_ArmISA.ArmISA_COLONS_ISA_swigregisterNEWLINEArmISA_COLONS_ISA_swigregister(ArmISA_COLONS_ISA)NEWLINENEWLINEclass ArmISAParams(m5.internal.param_SimObject.SimObjectParams):NEWLINE thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')NEWLINE __repr__ = _swig_reprNEWLINE def create(self): return _param_ArmISA.ArmISAParams_create(self)NEWLINE decoderFlavour = _swig_property(_param_ArmISA.ArmISAParams_decoderFlavour_get, _param_ArmISA.ArmISAParams_decoderFlavour_set)NEWLINE fpsid = _swig_property(_param_ArmISA.ArmISAParams_fpsid_get, _param_ArmISA.ArmISAParams_fpsid_set)NEWLINE id_aa64afr0_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64afr0_el1_get, _param_ArmISA.ArmISAParams_id_aa64afr0_el1_set)NEWLINE id_aa64afr1_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64afr1_el1_get, _param_ArmISA.ArmISAParams_id_aa64afr1_el1_set)NEWLINE id_aa64dfr0_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64dfr0_el1_get, _param_ArmISA.ArmISAParams_id_aa64dfr0_el1_set)NEWLINE id_aa64dfr1_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64dfr1_el1_get, _param_ArmISA.ArmISAParams_id_aa64dfr1_el1_set)NEWLINE id_aa64isar0_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64isar0_el1_get, _param_ArmISA.ArmISAParams_id_aa64isar0_el1_set)NEWLINE id_aa64isar1_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64isar1_el1_get, _param_ArmISA.ArmISAParams_id_aa64isar1_el1_set)NEWLINE id_aa64mmfr0_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64mmfr0_el1_get, _param_ArmISA.ArmISAParams_id_aa64mmfr0_el1_set)NEWLINE id_aa64mmfr1_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64mmfr1_el1_get, _param_ArmISA.ArmISAParams_id_aa64mmfr1_el1_set)NEWLINE id_aa64pfr0_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64pfr0_el1_get, _param_ArmISA.ArmISAParams_id_aa64pfr0_el1_set)NEWLINE id_aa64pfr1_el1 = _swig_property(_param_ArmISA.ArmISAParams_id_aa64pfr1_el1_get, _param_ArmISA.ArmISAParams_id_aa64pfr1_el1_set)NEWLINE id_isar0 = _swig_property(_param_ArmISA.ArmISAParams_id_isar0_get, _param_ArmISA.ArmISAParams_id_isar0_set)NEWLINE id_isar1 = _swig_property(_param_ArmISA.ArmISAParams_id_isar1_get, _param_ArmISA.ArmISAParams_id_isar1_set)NEWLINE id_isar2 = _swig_property(_param_ArmISA.ArmISAParams_id_isar2_get, _param_ArmISA.ArmISAParams_id_isar2_set)NEWLINE id_isar3 = _swig_property(_param_ArmISA.ArmISAParams_id_isar3_get, _param_ArmISA.ArmISAParams_id_isar3_set)NEWLINE id_isar4 = _swig_property(_param_ArmISA.ArmISAParams_id_isar4_get, _param_ArmISA.ArmISAParams_id_isar4_set)NEWLINE id_isar5 = _swig_property(_param_ArmISA.ArmISAParams_id_isar5_get, _param_ArmISA.ArmISAParams_id_isar5_set)NEWLINE id_mmfr0 = _swig_property(_param_ArmISA.ArmISAParams_id_mmfr0_get, _param_ArmISA.ArmISAParams_id_mmfr0_set)NEWLINE id_mmfr1 = _swig_property(_param_ArmISA.ArmISAParams_id_mmfr1_get, _param_ArmISA.ArmISAParams_id_mmfr1_set)NEWLINE id_mmfr2 = _swig_property(_param_ArmISA.ArmISAParams_id_mmfr2_get, _param_ArmISA.ArmISAParams_id_mmfr2_set)NEWLINE id_mmfr3 = _swig_property(_param_ArmISA.ArmISAParams_id_mmfr3_get, _param_ArmISA.ArmISAParams_id_mmfr3_set)NEWLINE id_pfr0 = _swig_property(_param_ArmISA.ArmISAParams_id_pfr0_get, _param_ArmISA.ArmISAParams_id_pfr0_set)NEWLINE id_pfr1 = _swig_property(_param_ArmISA.ArmISAParams_id_pfr1_get, _param_ArmISA.ArmISAParams_id_pfr1_set)NEWLINE midr = _swig_property(_param_ArmISA.ArmISAParams_midr_get, _param_ArmISA.ArmISAParams_midr_set)NEWLINE pmu = _swig_property(_param_ArmISA.ArmISAParams_pmu_get, _param_ArmISA.ArmISAParams_pmu_set)NEWLINE system = _swig_property(_param_ArmISA.ArmISAParams_system_get, _param_ArmISA.ArmISAParams_system_set)NEWLINE def __init__(self): NEWLINE this = _param_ArmISA.new_ArmISAParams()NEWLINE try: self.this.append(this)NEWLINE except: self.this = thisNEWLINE __swig_destroy__ = _param_ArmISA.delete_ArmISAParamsNEWLINE __del__ = lambda self : None;NEWLINEArmISAParams_swigregister = _param_ArmISA.ArmISAParams_swigregisterNEWLINEArmISAParams_swigregister(ArmISAParams)NEWLINENEWLINENEWLINENEWLINE
# -*- coding:utf-8 -*-NEWLINENEWLINE# Copyright 2015 NEC Corporation. #NEWLINE# #NEWLINE# Licensed under the Apache License, Version 2.0 (the "License"); #NEWLINE# you may not use this file except in compliance with the License. #NEWLINE# You may obtain a copy of the License at #NEWLINE# #NEWLINE# http://www.apache.org/licenses/LICENSE-2.0 #NEWLINE# #NEWLINE# Unless required by applicable law or agreed to in writing, software #NEWLINE# distributed under the License is distributed on an "AS IS" BASIS, #NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #NEWLINE# See the License for the specific language governing permissions and #NEWLINE# limitations under the License. #NEWLINENEWLINEfrom org.o3project.odenos.core.component.network.flow.ofpflow.ofp_flow_action_push_pbb\NEWLINE import OFPFlowActionPushPbbNEWLINENEWLINEimport unittestNEWLINENEWLINENEWLINEclass OFPFlowActionPushPbbTest(unittest.TestCase):NEWLINENEWLINE def setUp(self):NEWLINE self.target = OFPFlowActionPushPbb("OFPFlowActionPushPbb",NEWLINE 1234)NEWLINENEWLINE def tearDown(self):NEWLINE self.target = NoneNEWLINENEWLINE def test_constractor(self):NEWLINE self.assertEqual(self.target._body[self.target.TYPE],NEWLINE "OFPFlowActionPushPbb")NEWLINE self.assertEqual(self.target._body[self.target.ETH_TYPE],NEWLINE 1234)NEWLINENEWLINE def test_eth_type(self):NEWLINE self.assertEqual(self.target.eth_type, 1234)NEWLINENEWLINE def test_create_from_packed(self):NEWLINE self.value = {self.target.TYPE: "OFPFlowActionPushPbb",NEWLINE self.target.ETH_TYPE: 4321}NEWLINENEWLINE self.result = OFPFlowActionPushPbb.create_from_packed(self.value)NEWLINENEWLINE self.assertEqual(self.result._body[self.target.TYPE],NEWLINE "OFPFlowActionPushPbb")NEWLINE self.assertEqual(self.result._body[self.target.ETH_TYPE],NEWLINE 4321)NEWLINENEWLINE def test_packed_object(self):NEWLINE self.result = self.target.packed_object()NEWLINENEWLINE self.assertEqual(self.result[self.target.TYPE],NEWLINE "OFPFlowActionPushPbb")NEWLINE self.assertEqual(self.result[self.target.ETH_TYPE],NEWLINE 1234)NEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE
import pyaf.Bench.TS_datasets as tsdsNEWLINEimport tests.artificial.process_artificial_dataset as artNEWLINENEWLINENEWLINENEWLINENEWLINEart.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 12, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 12);
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# ==============================================================================NEWLINE"""Image Ops."""NEWLINENEWLINEimport tensorflow as tfNEWLINENEWLINEfrom tensorflow_io.core.python.ops import core_opsNEWLINENEWLINENEWLINEdef draw_bounding_boxes(images, boxes, texts=None, colors=None, name=None):NEWLINE """NEWLINE Draw bounding boxes on a batch of images.NEWLINENEWLINE Args:NEWLINE images: A Tensor. Must be one of the following types: float32, half.NEWLINE 4-D with shape [batch, height, width, depth]. A batch of images.NEWLINE boxes: A Tensor of type float32. 3-D with shapeNEWLINE [batch, num_bounding_boxes, 4] containing bounding boxes.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE if texts is None:NEWLINE texts = []NEWLINE if colors is None:NEWLINE colors = [[]]NEWLINE return core_ops.io_draw_bounding_boxes_v3(images, boxes, colors, texts, name=name)NEWLINENEWLINENEWLINEdef decode_jpeg_exif(contents, name=None):NEWLINE """NEWLINE Decode Exif information from an JPEG image.NEWLINENEWLINE TODO: Add additional fields besides orientation.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The JPEG-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `int64` for orientation.NEWLINE """NEWLINE return core_ops.io_decode_jpeg_exif(contents, name=name)NEWLINENEWLINENEWLINEdef decode_tiff_info(contents, name=None):NEWLINE """NEWLINE Decode a TIFF-encoded image meta data.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The TIFF-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE shape, dtype = core_ops.io_decode_tiff_info(contents, name=name)NEWLINE return shape, dtypeNEWLINENEWLINENEWLINEdef decode_tiff(contents, index=0, name=None):NEWLINE """NEWLINE Decode a TIFF-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The TIFF-encoded image.NEWLINE index: A `Tensor` of type int64. 0-D. The 0-based index of the frameNEWLINE inside TIFF-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE return core_ops.io_decode_tiff(contents, index, name=name)NEWLINENEWLINENEWLINEdef decode_exr_info(contents, name=None):NEWLINE """NEWLINE Decode a EXR-encoded image meta data.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The EXR-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE shape, dtype, channel = core_ops.io_decode_exr_info(contents, name=name)NEWLINE return shape, dtype, channelNEWLINENEWLINENEWLINEdef decode_exr(contents, index, channel, dtype, name=None):NEWLINE """NEWLINE Decode a EXR-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The EXR-encoded image.NEWLINE index: A `Tensor` of type int64. 0-D. The 0-based index of the frameNEWLINE inside EXR-encoded image.NEWLINE channel: A `Tensor` of type string. 0-D. The channel inside the image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE return core_ops.io_decode_exr(NEWLINE contents, index=index, channel=channel, dtype=dtype, name=nameNEWLINE )NEWLINENEWLINENEWLINEdef decode_pnm(contents, dtype=tf.uint8, name=None):NEWLINE """NEWLINE Decode a PNM-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The PNM-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 4]` (RGBA).NEWLINE """NEWLINE return core_ops.io_decode_pnm(contents, dtype=dtype, name=name)NEWLINENEWLINENEWLINEdef decode_hdr(contents, name=None):NEWLINE """NEWLINE Decode a HDR-encoded image to a tf.float tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The HDR-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `float` and shape of `[height, width, 3]` (RGB).NEWLINE """NEWLINE return core_ops.io_decode_hdr(contents, name=name)NEWLINENEWLINENEWLINEdef decode_nv12(contents, size, name=None):NEWLINE """NEWLINE Decode a NV12-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The NV12-encoded image.NEWLINE size: A 1-D int32 Tensor of 2 elements: height, width. The sizeNEWLINE for the images.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 3]` (RGB).NEWLINE """NEWLINE return core_ops.io_decode_nv12(contents, size=size, name=name)NEWLINENEWLINENEWLINEdef decode_yuy2(contents, size, name=None):NEWLINE """NEWLINE Decode a YUY2-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The YUY2-encoded image.NEWLINE size: A 1-D int32 Tensor of 2 elements: height, width. The sizeNEWLINE for the images.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 3]` (RGB).NEWLINE """NEWLINE return core_ops.io_decode_yuy2(contents, size=size, name=name)NEWLINENEWLINENEWLINEdef decode_avif(contents, name=None):NEWLINE """NEWLINE Decode a AVIF-encoded image to a uint8 tensor.NEWLINENEWLINE Args:NEWLINE contents: A `Tensor` of type `string`. 0-D. The AVIF-encoded image.NEWLINE name: A name for the operation (optional).NEWLINENEWLINE Returns:NEWLINE A `Tensor` of type `uint8` and shape of `[height, width, 3]` (RGB).NEWLINE """NEWLINE return core_ops.io_decode_avif(contents, name=name)NEWLINE
import FWCore.ParameterSet.Config as cmsNEWLINENEWLINEprocess = cms.Process("TEST")NEWLINENEWLINEprocess.source = cms.Source("EmptySource",NEWLINE firstRun = cms.untracked.uint32(1),NEWLINE firstLuminosityBlock = cms.untracked.uint32(2),NEWLINE firstEvent = cms.untracked.uint32(15),NEWLINE numberEventsInRun = cms.untracked.uint32(100),NEWLINE numberEventsInLuminosityBlock = cms.untracked.uint32(100)NEWLINE)NEWLINENEWLINEprocess.maxEvents = cms.untracked.PSet(NEWLINE input = cms.untracked.int32(1)NEWLINE)NEWLINENEWLINEprocess.out = cms.OutputModule("PoolOutputModule",NEWLINE fileName = cms.untracked.string('testRandomServiceTest2.root')NEWLINE)NEWLINEprocess.RandomNumberGeneratorService = cms.Service("RandomNumberGeneratorService",NEWLINENEWLINE t1 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7)NEWLINE ),NEWLINE t2 = cms.PSet(NEWLINE engineName = cms.untracked.string('RanecuEngine'),NEWLINE initialSeedSet = cms.untracked.vuint32(7, 7)NEWLINE ),NEWLINE t3 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7),NEWLINE engineName = cms.untracked.string('TRandom3')NEWLINE ),NEWLINE t4 = cms.PSet(NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE initialSeed = cms.untracked.uint32(7)NEWLINE ),NEWLINE t5 = cms.PSet(NEWLINE initialSeed = cms.untracked.uint32(7),NEWLINE engineName = cms.untracked.string('TRandom3')NEWLINE ),NEWLINE enableChecking = cms.untracked.bool(True),NEWLINE restoreFileName = cms.untracked.string('StashState3.data')NEWLINE)NEWLINENEWLINEprocess.t1 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE seeds = cms.untracked.vuint32(81),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 82, 82, 202, 202)NEWLINE)NEWLINEprocess.t2 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('RanecuEngine'),NEWLINE seeds = cms.untracked.vuint32(1, 2),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 2, 2, 203, 203)NEWLINE)NEWLINEprocess.t3 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('TRandom3'),NEWLINE seeds = cms.untracked.vuint32(83),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 84, 84, 204, 204)NEWLINE)NEWLINEprocess.t4 = cms.EDAnalyzer("TestRandomNumberServiceGlobal",NEWLINE engineName = cms.untracked.string('HepJamesRandom'),NEWLINE seeds = cms.untracked.vuint32(84),NEWLINE offset = cms.untracked.uint32(2),NEWLINE maxEvents = cms.untracked.uint32(15),NEWLINE nStreams = cms.untracked.uint32(1),NEWLINE skippedEvents = cms.untracked.vuint32(4),NEWLINE seedByLumi = cms.untracked.vuint32(0, 85, 85, 205, 205)NEWLINE)NEWLINENEWLINEprocess.p = cms.Path(process.t1+process.t2+process.t3+process.t4)NEWLINEprocess.o = cms.EndPath(process.out)NEWLINE
# -*- coding: utf-8 -*-NEWLINENEWLINEfrom ..expr import *NEWLINENEWLINEdef_Topic(NEWLINE Title("Riemann zeta function"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "e0a6a2",NEWLINE ),NEWLINE Section("Illustrations"),NEWLINE Entries(NEWLINE "3131df",NEWLINE ),NEWLINE Section("Dirichlet series"),NEWLINE Entries(NEWLINE "da2fdb", # Dirichlet seriesNEWLINE "1d46d4",NEWLINE ),NEWLINE Section("Euler product"),NEWLINE Entries(NEWLINE "8f5e66", # Euler productNEWLINE ),NEWLINE Section("Laurent series"),NEWLINE Description("Related topic:", TopicReference("Stieltjes constants")),NEWLINE Entries(NEWLINE "b1a2e1",NEWLINE ),NEWLINE Section("Special values"),NEWLINE Entries(NEWLINE "a01b6e", # zeta(2)NEWLINE "e84983", # zeta(3) irrationalNEWLINE "72ccda", # zeta(2n)NEWLINE "51fd98", # zeta(-n)NEWLINE "7cb17f", # table of zeta(2n)NEWLINE "e50a56", # table of zeta(-n)NEWLINE "e93ca8", # table of zeta(n) to 50 digitsNEWLINE ),NEWLINE Section("Analytic properties"),NEWLINE Entries(NEWLINE "8b5ddb", # holomorphic domainNEWLINE "52c4ab", # polesNEWLINE "fdb94b", # essential singularitiesNEWLINE "36a095", # branch pointsNEWLINE "9a258f", # branch cutsNEWLINE ),NEWLINE Section("Zeros"),NEWLINE SeeTopics("Zeros of the Riemann zeta function"),NEWLINE Entries(NEWLINE "669509", # RiemannZetaZeroNEWLINE "c03de4", # RiemannHypothesisNEWLINE "49704a", # RH formulaNEWLINE "2e1ff3", # real zerosNEWLINE "a78abc", # nontrivial zerosNEWLINE "692e42", # complex zerosNEWLINE "cbbf16", # 0 < re < 1NEWLINE "e6ff64", # re = 1/2NEWLINE "60c2ec", # conjugate symmetryNEWLINE "71d9d9", # table of rho_n to 50 digitsNEWLINE ),NEWLINE Section("Complex parts"),NEWLINE Entries(NEWLINE "69348a", # conjugateNEWLINE ),NEWLINE Section("Functional equation"),NEWLINE Entries(NEWLINE "9ee8bc", # functional equationNEWLINE "1a63af",NEWLINE ),NEWLINE Section("Bounds and inequalities"),NEWLINE Entries(NEWLINE "809bc0", # bound in right planeNEWLINE "3a5eb6", # bound in critical stripNEWLINE ),NEWLINE Section("Euler-Maclaurin formula"),NEWLINE Entries(NEWLINE "792f7b", # Euler-Maclaurin formulaNEWLINE ),NEWLINE Section("Approximations"),NEWLINE Entries(NEWLINE "d31b04", # Euler-Maclaurin formulaNEWLINE "e37535", # BorweinNEWLINE ),NEWLINE #Section("Related topics"),NEWLINE #SeeTopics("Gamma function", "Bernoulli number"),NEWLINE)NEWLINENEWLINEdef_Topic(NEWLINE Title("Zeros of the Riemann zeta function"),NEWLINE Entries(NEWLINE "e0a6a2",NEWLINE "669509",NEWLINE "c03de4",NEWLINE ),NEWLINE Section("Main properties"),NEWLINE Description("See also: ", TopicReference("Riemann hypothesis")),NEWLINE Entries(NEWLINE "9fa2a1", # RH formulaNEWLINE "49704a", # RHNEWLINE "2e1ff3", # real zerosNEWLINE "a78abc", # nontrivial zerosNEWLINE "692e42", # complex zerosNEWLINE "cbbf16", # 0 < re < 1NEWLINE "e6ff64", # re = 1/2NEWLINE "60c2ec", # conjugate symmetryNEWLINE ),NEWLINE Section("Numerical values"),NEWLINE Entries(NEWLINE "945fa5", # rho_1 to 50 digitsNEWLINE "c0ae99", # rho_2 to 50 digitsNEWLINE "71d9d9", # table of rho_n to 50 digitsNEWLINE "dc558b", # table of rho_n to 10 digitsNEWLINE "2e1cc7" # table of rho_10^n to 50 digitsNEWLINE ),NEWLINE Section("Related topics"),NEWLINE SeeTopics("Riemann zeta function"),NEWLINE)NEWLINENEWLINEmake_entry(ID("e0a6a2"),NEWLINE SymbolDefinition(RiemannZeta, RiemannZeta(s), "Riemann zeta function"),NEWLINE Description("The Riemann zeta function", RiemannZeta(s), "is a function of one complex variable", s,NEWLINE ". It is a meromorphic function with a pole at", Equal(s, 1), ".",NEWLINE "The following table lists all conditions such that", SourceForm(RiemannZeta(s)), "is defined in Fungrim."),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE TableSection("Numbers"),NEWLINE Tuple(Element(s, OpenInterval(1, Infinity)), Element(RiemannZeta(s), OpenInterval(1, Infinity))),NEWLINE Tuple(Element(s, SetMinus(RR, Set(1))), Element(RiemannZeta(s), RR)),NEWLINE Tuple(Element(s, SetMinus(CC, Set(1))), Element(RiemannZeta(s), CC)),NEWLINE TableSection("Infinities"),NEWLINE Tuple(Element(s, Set(1)), Element(RiemannZeta(s), Set(UnsignedInfinity))),NEWLINE Tuple(Element(s, Set(Infinity)), Element(RiemannZeta(s), Set(1))),NEWLINE TableSection("Formal power series"),NEWLINE Tuple(And(Element(s, PowerSeries(RR, x)), NotEqual(SeriesCoefficient(s, x, 0), 1)),NEWLINE Element(RiemannZeta(s), PowerSeries(RR, x))),NEWLINE Tuple(And(Element(s, PowerSeries(CC, x)), NotEqual(SeriesCoefficient(s, x, 0), 1)),NEWLINE Element(RiemannZeta(s), PowerSeries(CC, x))),NEWLINE Tuple(And(Element(s, PowerSeries(RR, x)), NotEqual(s, 1)),NEWLINE Element(RiemannZeta(s), LaurentSeries(RR, x))),NEWLINE Tuple(And(Element(s, PowerSeries(CC, x)), NotEqual(s, 1)),NEWLINE Element(RiemannZeta(s), LaurentSeries(CC, x))),NEWLINE )),NEWLINE )NEWLINENEWLINEmake_entry(ID("669509"),NEWLINE SymbolDefinition(RiemannZetaZero, RiemannZetaZero(n), "Nontrivial zero of the Riemann zeta function"),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE Tuple(Element(n, SetMinus(ZZ, Set(0))), Element(RiemannZetaZero(n), CC))NEWLINE )))NEWLINENEWLINEmake_entry(ID("3131df"),NEWLINE Image(Description("X-ray of", RiemannZeta(s), "on", Element(s, ClosedInterval(-22,22) + ClosedInterval(-27,27)*ConstI), "with the critical strip highlighted"),NEWLINE ImageSource("xray_zeta")),NEWLINE description_xray,NEWLINE )NEWLINENEWLINEmake_entry(ID("da2fdb"),NEWLINE Formula(Equal(RiemannZeta(s), Sum(1/k**s, For(k, 1, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("1d46d4"),NEWLINE Formula(Equal(1/RiemannZeta(s), Sum(MoebiusMu(k)/k**s, For(k, 1, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("8f5e66"),NEWLINE Formula(Equal(RiemannZeta(s), PrimeProduct(1/(1-1/p**s), For(p)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("a01b6e"),NEWLINE Formula(Equal(RiemannZeta(2), Pi**2 / 6)))NEWLINENEWLINEmake_entry(ID("e84983"),NEWLINE Formula(NotElement(RiemannZeta(3), QQ)),NEWLINE References("R. Apéry (1979), Irrationalité de ζ(2) et ζ(3), Astérisque, 61: 11-13."))NEWLINENEWLINEmake_entry(ID("72ccda"),NEWLINE Formula(Equal(RiemannZeta(2*n), (-1)**(n+1) * BernoulliB(2*n) * (2*Pi)**(2*n) / (2 * Factorial(2*n)))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), GreaterEqual(n, 1))))NEWLINENEWLINEmake_entry(ID("51fd98"),NEWLINE Formula(Equal(RiemannZeta(-n), (-1)**n * BernoulliB(n+1) / (n+1))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), GreaterEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("9ee8bc"),NEWLINE Formula(Equal(RiemannZeta(s), 2 * (2*Pi)**(s-1) * Sin(Pi*s/2) * Gamma(1-s) * RiemannZeta(1-s))),NEWLINE Variables(s),NEWLINE Assumptions(NEWLINE And(Element(s, CC), NotElement(s, ZZGreaterEqual(0))),NEWLINE And(Element(s, PowerSeries(CC, SerX)), NotElement(s, ZZGreaterEqual(0))),NEWLINE ))NEWLINENEWLINEmake_entry(ID("1a63af"),NEWLINE Formula(Equal(RiemannZeta(1-s), (2 * Cos(Div(1,2)*Pi*s)) / (2*Pi)**(s) * Gamma(s) * RiemannZeta(s))),NEWLINE Variables(s),NEWLINE Assumptions(NEWLINE And(Element(s, CC), NotElement(s, ZZLessEqual(1))),NEWLINE And(Element(s, PowerSeries(CC, SerX)), NotElement(s, ZZLessEqual(1))),NEWLINE ))NEWLINENEWLINEmake_entry(ID("7cb17f"),NEWLINE Description("Table of", RiemannZeta(2*n), "for", LessEqual(1, n, 20)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing 2n and still parse table?NEWLINE TableValueHeadings(n, RiemannZeta(n)),NEWLINE TableSplit(2),NEWLINE List(NEWLINE Tuple(2, Div(1, 6) * Pi**2),NEWLINE Tuple(4, Div(1, 90) * Pi**4),NEWLINE Tuple(6, Div(1, 945) * Pi**6),NEWLINE Tuple(8, Div(1, 9450) * Pi**8),NEWLINE Tuple(10, Div(1, 93555) * Pi**10),NEWLINE Tuple(12, Div(691, 638512875) * Pi**12),NEWLINE Tuple(14, Div(2, 18243225) * Pi**14),NEWLINE Tuple(16, Div(3617, 325641566250) * Pi**16),NEWLINE Tuple(18, Div(43867, 38979295480125) * Pi**18),NEWLINE Tuple(20, Div(174611, 1531329465290625) * Pi**20),NEWLINE Tuple(22, Div(155366, 13447856940643125) * Pi**22),NEWLINE Tuple(24, Div(236364091, 201919571963756521875) * Pi**24),NEWLINE Tuple(26, Div(1315862, 11094481976030578125) * Pi**26),NEWLINE Tuple(28, Div(6785560294, 564653660170076273671875) * Pi**28),NEWLINE Tuple(30, Div(6892673020804, 5660878804669082674070015625) * Pi**30),NEWLINE Tuple(32, Div(7709321041217, 62490220571022341207266406250) * Pi**32),NEWLINE Tuple(34, Div(151628697551, 12130454581433748587292890625) * Pi**34),NEWLINE Tuple(36, Div(26315271553053477373, 20777977561866588586487628662044921875) * Pi**36),NEWLINE Tuple(38, Div(308420411983322, 2403467618492375776343276883984375) * Pi**38),NEWLINE Tuple(40, Div(261082718496449122051, 20080431172289638826798401128390556640625) * Pi**40))))NEWLINENEWLINEmake_entry(ID("e50a56"),NEWLINE Description("Table of", RiemannZeta(-n), "for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing -n and still parse table?NEWLINE TableValueHeadings(n, RiemannZeta(n)),NEWLINE TableSplit(3),NEWLINE List(NEWLINE Tuple(0, -Div(1, 2)),NEWLINE Tuple(-1, -Div(1, 12)),NEWLINE Tuple(-2, 0),NEWLINE Tuple(-3, Div(1, 120)),NEWLINE Tuple(-4, 0),NEWLINE Tuple(-5, -Div(1, 252)),NEWLINE Tuple(-6, 0),NEWLINE Tuple(-7, Div(1, 240)),NEWLINE Tuple(-8, 0),NEWLINE Tuple(-9, -Div(1, 132)),NEWLINE Tuple(-10, 0),NEWLINE Tuple(-11, Div(691, 32760)),NEWLINE Tuple(-12, 0),NEWLINE Tuple(-13, -Div(1, 12)),NEWLINE Tuple(-14, 0),NEWLINE Tuple(-15, Div(3617, 8160)),NEWLINE Tuple(-16, 0),NEWLINE Tuple(-17, -Div(43867, 14364)),NEWLINE Tuple(-18, 0),NEWLINE Tuple(-19, Div(174611, 6600)),NEWLINE Tuple(-20, 0),NEWLINE Tuple(-21, -Div(77683, 276)),NEWLINE Tuple(-22, 0),NEWLINE Tuple(-23, Div(236364091, 65520)),NEWLINE Tuple(-24, 0),NEWLINE Tuple(-25, -Div(657931, 12)),NEWLINE Tuple(-26, 0),NEWLINE Tuple(-27, Div(3392780147, 3480)),NEWLINE Tuple(-28, 0),NEWLINE Tuple(-29, -Div(1723168255201, 85932)),NEWLINE Tuple(-30, 0))))NEWLINENEWLINEmake_entry(ID("e93ca8"),NEWLINE Description("Table of", RiemannZeta(n), "to 50 digits for", LessEqual(2, n, 50)),NEWLINE Table(NEWLINE Var(n),NEWLINE # todo: support writing -n and still parse table?NEWLINE TableValueHeadings(n, NearestDecimal(RiemannZeta(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(2, Decimal("1.6449340668482264364724151666460251892189499012068")),NEWLINE Tuple(3, Decimal("1.2020569031595942853997381615114499907649862923405")),NEWLINE Tuple(4, Decimal("1.0823232337111381915160036965411679027747509519187")),NEWLINE Tuple(5, Decimal("1.0369277551433699263313654864570341680570809195019")),NEWLINE Tuple(6, Decimal("1.0173430619844491397145179297909205279018174900329")),NEWLINE Tuple(7, Decimal("1.0083492773819228268397975498497967595998635605652")),NEWLINE Tuple(8, Decimal("1.0040773561979443393786852385086524652589607906499")),NEWLINE Tuple(9, Decimal("1.0020083928260822144178527692324120604856058513949")),NEWLINE Tuple(10, Decimal("1.0009945751278180853371459589003190170060195315645")),NEWLINE Tuple(11, Decimal("1.0004941886041194645587022825264699364686064357582")),NEWLINE Tuple(12, Decimal("1.0002460865533080482986379980477396709604160884580")),NEWLINE Tuple(13, Decimal("1.0001227133475784891467518365263573957142751058955")),NEWLINE Tuple(14, Decimal("1.0000612481350587048292585451051353337474816961692")),NEWLINE Tuple(15, Decimal("1.0000305882363070204935517285106450625876279487069")),NEWLINE Tuple(16, Decimal("1.0000152822594086518717325714876367220232373889905")),NEWLINE Tuple(17, Decimal("1.0000076371976378997622736002935630292130882490903")),NEWLINE Tuple(18, Decimal("1.0000038172932649998398564616446219397304546972190")),NEWLINE Tuple(19, Decimal("1.0000019082127165539389256569577951013532585711448")),NEWLINE Tuple(20, Decimal("1.0000009539620338727961131520386834493459437941874")),NEWLINE Tuple(21, Decimal("1.0000004769329867878064631167196043730459664466948")),NEWLINE Tuple(22, Decimal("1.0000002384505027277329900036481867529949350418218")),NEWLINE Tuple(23, Decimal("1.0000001192199259653110730677887188823263872549978")),NEWLINE Tuple(24, Decimal("1.0000000596081890512594796124402079358012275039188")),NEWLINE Tuple(25, Decimal("1.0000000298035035146522801860637050693660118447309")),NEWLINE Tuple(26, Decimal("1.0000000149015548283650412346585066306986288647882")),NEWLINE Tuple(27, Decimal("1.0000000074507117898354294919810041706041194547190")),NEWLINE Tuple(28, Decimal("1.0000000037253340247884570548192040184024232328931")),NEWLINE Tuple(29, Decimal("1.0000000018626597235130490064039099454169480616653")),NEWLINE Tuple(30, Decimal("1.0000000009313274324196681828717647350212198135680")),NEWLINE Tuple(31, Decimal("1.0000000004656629065033784072989233251220071062692")),NEWLINE Tuple(32, Decimal("1.0000000002328311833676505492001455975940495024830")),NEWLINE Tuple(33, Decimal("1.0000000001164155017270051977592973835456309516522")),NEWLINE Tuple(34, Decimal("1.0000000000582077208790270088924368598910630541731")),NEWLINE Tuple(35, Decimal("1.0000000000291038504449709968692942522788404641070")),NEWLINE Tuple(36, Decimal("1.0000000000145519218910419842359296322453184209838")),NEWLINE Tuple(37, Decimal("1.0000000000072759598350574810145208690123380592649")),NEWLINE Tuple(38, Decimal("1.0000000000036379795473786511902372363558732735126")),NEWLINE Tuple(39, Decimal("1.0000000000018189896503070659475848321007300850306")),NEWLINE Tuple(40, Decimal("1.0000000000009094947840263889282533118386949087539")),NEWLINE Tuple(41, Decimal("1.0000000000004547473783042154026799112029488570339")),NEWLINE Tuple(42, Decimal("1.0000000000002273736845824652515226821577978691214")),NEWLINE Tuple(43, Decimal("1.0000000000001136868407680227849349104838025906437")),NEWLINE Tuple(44, Decimal("1.0000000000000568434198762758560927718296752406855")),NEWLINE Tuple(45, Decimal("1.0000000000000284217097688930185545507370494266207")),NEWLINE Tuple(46, Decimal("1.0000000000000142108548280316067698343071417395377")),NEWLINE Tuple(47, Decimal("1.0000000000000071054273952108527128773544799568000")),NEWLINE Tuple(48, Decimal("1.0000000000000035527136913371136732984695340593430")),NEWLINE Tuple(49, Decimal("1.0000000000000017763568435791203274733490144002796")),NEWLINE Tuple(50, Decimal("1.0000000000000008881784210930815903096091386391386")))))NEWLINENEWLINENEWLINEmake_entry(ID("809bc0"),NEWLINE Formula(LessEqual(Abs(RiemannZeta(s)), RiemannZeta(Re(s)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), Greater(Re(s), 1))))NEWLINENEWLINEmake_entry(ID("3a5eb6"),NEWLINE Formula(Less(Abs(RiemannZeta(s)), 3 * Abs((1+s)/(1-s)) * Abs((1+s)/(2*Pi))**((1+eta-Re(s))/2) * RiemannZeta(1+eta))),NEWLINE Variables(s, eta),NEWLINE Assumptions(NEWLINE And(Element(s, CC), Element(eta, RR), NotEqual(s, 1), Element(eta, OpenClosedInterval(0, Div(1,2))), LessEqual(-eta, Re(s), 1 + eta))),NEWLINE References("H. Rademacher, Topics in analytic number theory, Springer, 1973. Equation 43.3."))NEWLINENEWLINEmake_entry(ID("792f7b"),NEWLINE Formula(Equal(RiemannZeta(s),NEWLINE Sum(1/k**s, For(k, 1, N-1)) + N**(1-s)/(s-1) + 1/N**s * (Div(1,2) +NEWLINE Sum((BernoulliB(2*k) / Factorial(2*k)) * (RisingFactorial(s, 2*k-1) / N**(2*k-1)), For(k, 1, M))) -NEWLINE Integral((BernoulliPolynomial(2*M, t - Floor(t)) / Factorial(2 * M)) * (RisingFactorial(s, 2*M) / t**(s+2*M)), For(t, N, Infinity)))),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1), Element(N, ZZ), Element(M, ZZ), Greater(Re(s+2*M-1), 0), GreaterEqual(N, 1), GreaterEqual(M, 1))),NEWLINE Variables(s, N, M),NEWLINE References("""F. Johansson (2015), Rigorous high-precision computation of the Hurwitz zeta function and its derivatives, Numerical Algorithms 69:253, DOI: 10.1007/s11075-014-9893-1""",NEWLINE """F. W. J. Olver, Asymptotics and Special Functions, AK Peters, 1997. Chapter 8."""))NEWLINENEWLINEmake_entry(ID("d31b04"),NEWLINE Formula(LessEqual(Abs(RiemannZeta(s) -NEWLINE Parentheses(Sum(1/k**s, For(k, 1, N-1)) + N**(1-s)/(s-1) + 1/N**s * (Div(1,2) +NEWLINE Sum((BernoulliB(2*k) / Factorial(2*k)) * (RisingFactorial(s, 2*k-1) / N**(2*k-1)), For(k, 1, M))))),NEWLINE (4 * Abs(RisingFactorial(s, 2*M)) / (2*Pi)**(2*M)) * (N**(-Parentheses(Re(s)+2*M-1)) / (Re(s)+2*M-1)))),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1), Element(N, ZZ), Element(M, ZZ), Greater(Re(s+2*M-1), 0), GreaterEqual(N, 1), GreaterEqual(M, 1))),NEWLINE Variables(s, N, M),NEWLINE References("""F. Johansson (2015), Rigorous high-precision computation of the Hurwitz zeta function and its derivatives, Numerical Algorithms 69:253, DOI: 10.1007/s11075-014-9893-1""",NEWLINE """F. W. J. Olver, Asymptotics and Special Functions, AK Peters, 1997. Chapter 8."""))NEWLINENEWLINEmake_entry(ID("e37535"),NEWLINE Formula(Where(NEWLINE LessEqual(Abs((1-2**(1-s))*RiemannZeta(s) - Div(1,d(n)) * Sum(((-1)**k*(d(n)-d(k)))/(k+1)**s, For(k, 0, n-1))),NEWLINE (3*(1 + 2*Abs(Im(s)))/(3+Sqrt(8))**n) * Exp(Abs(Im(s))*Pi/2)),NEWLINE Equal(d(k), n*Sum(Factorial(n+i-1)*4**i/(Factorial(n-i)*Factorial(2*i)), For(i, 0, k))))),NEWLINE Variables(s, n),NEWLINE Assumptions(And(Element(s, CC), GreaterEqual(Re(s), Div(1,2)), NotEqual(s, 1), Element(n, ZZGreaterEqual(1)))),NEWLINE References("P. Borwein. An efficient algorithm for the Riemann zeta function. Canadian Mathematical Society Conference Proceedings, vol. 27, pp. 29-34. 2000.")NEWLINE )NEWLINENEWLINEmake_entry(ID("69348a"),NEWLINE Formula(Equal(RiemannZeta(Conjugate(s)), Conjugate(RiemannZeta(s)))),NEWLINE Variables(s),NEWLINE Assumptions(And(Element(s, CC), NotEqual(s, 1))))NEWLINENEWLINEmake_entry(ID("8b5ddb"),NEWLINE Formula(IsHolomorphic(RiemannZeta(s), ForElement(s, SetMinus(CC, Set(1))))))NEWLINENEWLINEmake_entry(ID("52c4ab"),NEWLINE Formula(Equal(Poles(RiemannZeta(s), ForElement(s, Union(CC, Set(UnsignedInfinity)))), Set(1))))NEWLINENEWLINEmake_entry(ID("fdb94b"),NEWLINE Formula(Equal(EssentialSingularities(RiemannZeta(s), s, Union(CC, Set(UnsignedInfinity))), Set(UnsignedInfinity))))NEWLINENEWLINEmake_entry(ID("36a095"),NEWLINE Formula(Equal(BranchPoints(RiemannZeta(s), s, Union(CC, Set(UnsignedInfinity))), Set())))NEWLINENEWLINEmake_entry(ID("9a258f"),NEWLINE Formula(Equal(BranchCuts(RiemannZeta(s), s, Union(CC)), Set())))NEWLINENEWLINEmake_entry(ID("2e1ff3"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, RR)), Set(-(2*n), ForElement(n, ZZGreaterEqual(1))))))NEWLINENEWLINEmake_entry(ID("a78abc"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, CC), LessEqual(0, Re(s), 1)), Set(RiemannZetaZero(n), For(n), And(Element(n, ZZ), NotEqual(n, 0))))))NEWLINENEWLINEmake_entry(ID("692e42"),NEWLINE Formula(Equal(Zeros(RiemannZeta(s), ForElement(s, CC)), Union(Set(-(2*n), ForElement(n, ZZGreaterEqual(1))),NEWLINE Set(RiemannZetaZero(n), For(n), And(Element(n, ZZ), NotEqual(n, 0)))))))NEWLINENEWLINEmake_entry(ID("cbbf16"),NEWLINE Formula(Less(0, Re(RiemannZetaZero(n)), 1)),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("60c2ec"),NEWLINE Formula(Equal(RiemannZetaZero(-n), Conjugate(RiemannZetaZero(n)))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0))))NEWLINENEWLINEmake_entry(ID("e6ff64"),NEWLINE Formula(Equal(Re(RiemannZetaZero(n)), Div(1,2))),NEWLINE Variables(n),NEWLINE Assumptions(And(Element(n, ZZ), NotEqual(n, 0), Or(Less(Abs(n), 103800788359), RiemannHypothesis))),NEWLINE References("""D. J. Platt (2016), Isolating some non-trivial zeros of zeta, Mathematics of Computation 86(307):1, DOI: 10.1090/mcom/3198"""))NEWLINENEWLINEmake_entry(ID("945fa5"),NEWLINE Formula(Element(RiemannZetaZero(1),NEWLINE Div(1,2) + RealBall(Decimal("14.134725141734693790457251983562470270784257115699"), Decimal("2.44e-49")) * ConstI)))NEWLINENEWLINEmake_entry(ID("c0ae99"),NEWLINE Formula(Element(RiemannZetaZero(2),NEWLINE Div(1,2) + RealBall(Decimal("21.022039638771554992628479593896902777334340524903"), Decimal("2.19e-49")) * ConstI)))NEWLINENEWLINEmake_entry(ID("dc558b"),NEWLINE Description("Table of", Im(RiemannZetaZero(n)), "to 10 digits for", LessEqual(1, n, 500)),NEWLINE Table(TableRelation(Tuple(n, y), And(Equal(Re(RiemannZetaZero(n)), Div(1,2)), Equal(NearestDecimal(Im(RiemannZetaZero(n)), 10), y))),NEWLINE TableHeadings(n, Im(RiemannZetaZero(n))), TableSplit(5),NEWLINE List(*(NEWLINE Tuple(1, Decimal("14.13472514")),NEWLINE Tuple(2, Decimal("21.02203964")),NEWLINE Tuple(3, Decimal("25.01085758")),NEWLINE Tuple(4, Decimal("30.42487613")),NEWLINE Tuple(5, Decimal("32.93506159")),NEWLINE Tuple(6, Decimal("37.58617816")),NEWLINE Tuple(7, Decimal("40.91871901")),NEWLINE Tuple(8, Decimal("43.32707328")),NEWLINE Tuple(9, Decimal("48.00515088")),NEWLINE Tuple(10, Decimal("49.77383248")),NEWLINE Tuple(11, Decimal("52.97032148")),NEWLINE Tuple(12, Decimal("56.44624770")),NEWLINE Tuple(13, Decimal("59.34704400")),NEWLINE Tuple(14, Decimal("60.83177852")),NEWLINE Tuple(15, Decimal("65.11254405")),NEWLINE Tuple(16, Decimal("67.07981053")),NEWLINE Tuple(17, Decimal("69.54640171")),NEWLINE Tuple(18, Decimal("72.06715767")),NEWLINE Tuple(19, Decimal("75.70469070")),NEWLINE Tuple(20, Decimal("77.14484007")),NEWLINE Tuple(21, Decimal("79.33737502")),NEWLINE Tuple(22, Decimal("82.91038085")),NEWLINE Tuple(23, Decimal("84.73549298")),NEWLINE Tuple(24, Decimal("87.42527461")),NEWLINE Tuple(25, Decimal("88.80911121")),NEWLINE Tuple(26, Decimal("92.49189927")),NEWLINE Tuple(27, Decimal("94.65134404")),NEWLINE Tuple(28, Decimal("95.87063423")),NEWLINE Tuple(29, Decimal("98.83119422")),NEWLINE Tuple(30, Decimal("101.3178510")),NEWLINE Tuple(31, Decimal("103.7255380")),NEWLINE Tuple(32, Decimal("105.4466231")),NEWLINE Tuple(33, Decimal("107.1686112")),NEWLINE Tuple(34, Decimal("111.0295355")),NEWLINE Tuple(35, Decimal("111.8746592")),NEWLINE Tuple(36, Decimal("114.3202209")),NEWLINE Tuple(37, Decimal("116.2266803")),NEWLINE Tuple(38, Decimal("118.7907829")),NEWLINE Tuple(39, Decimal("121.3701250")),NEWLINE Tuple(40, Decimal("122.9468293")),NEWLINE Tuple(41, Decimal("124.2568186")),NEWLINE Tuple(42, Decimal("127.5166839")),NEWLINE Tuple(43, Decimal("129.5787042")),NEWLINE Tuple(44, Decimal("131.0876885")),NEWLINE Tuple(45, Decimal("133.4977372")),NEWLINE Tuple(46, Decimal("134.7565098")),NEWLINE Tuple(47, Decimal("138.1160421")),NEWLINE Tuple(48, Decimal("139.7362090")),NEWLINE Tuple(49, Decimal("141.1237074")),NEWLINE Tuple(50, Decimal("143.1118458")),NEWLINE Tuple(51, Decimal("146.0009825")),NEWLINE Tuple(52, Decimal("147.4227653")),NEWLINE Tuple(53, Decimal("150.0535204")),NEWLINE Tuple(54, Decimal("150.9252576")),NEWLINE Tuple(55, Decimal("153.0246938")),NEWLINE Tuple(56, Decimal("156.1129093")),NEWLINE Tuple(57, Decimal("157.5975918")),NEWLINE Tuple(58, Decimal("158.8499882")),NEWLINE Tuple(59, Decimal("161.1889641")),NEWLINE Tuple(60, Decimal("163.0307097")),NEWLINE Tuple(61, Decimal("165.5370692")),NEWLINE Tuple(62, Decimal("167.1844400")),NEWLINE Tuple(63, Decimal("169.0945154")),NEWLINE Tuple(64, Decimal("169.9119765")),NEWLINE Tuple(65, Decimal("173.4115365")),NEWLINE Tuple(66, Decimal("174.7541915")),NEWLINE Tuple(67, Decimal("176.4414343")),NEWLINE Tuple(68, Decimal("178.3774078")),NEWLINE Tuple(69, Decimal("179.9164840")),NEWLINE Tuple(70, Decimal("182.2070785")),NEWLINE Tuple(71, Decimal("184.8744678")),NEWLINE Tuple(72, Decimal("185.5987837")),NEWLINE Tuple(73, Decimal("187.2289226")),NEWLINE Tuple(74, Decimal("189.4161587")),NEWLINE Tuple(75, Decimal("192.0266564")),NEWLINE Tuple(76, Decimal("193.0797266")),NEWLINE Tuple(77, Decimal("195.2653967")),NEWLINE Tuple(78, Decimal("196.8764818")),NEWLINE Tuple(79, Decimal("198.0153097")),NEWLINE Tuple(80, Decimal("201.2647519")),NEWLINE Tuple(81, Decimal("202.4935945")),NEWLINE Tuple(82, Decimal("204.1896718")),NEWLINE Tuple(83, Decimal("205.3946972")),NEWLINE Tuple(84, Decimal("207.9062589")),NEWLINE Tuple(85, Decimal("209.5765097")),NEWLINE Tuple(86, Decimal("211.6908626")),NEWLINE Tuple(87, Decimal("213.3479194")),NEWLINE Tuple(88, Decimal("214.5470448")),NEWLINE Tuple(89, Decimal("216.1695385")),NEWLINE Tuple(90, Decimal("219.0675963")),NEWLINE Tuple(91, Decimal("220.7149188")),NEWLINE Tuple(92, Decimal("221.4307056")),NEWLINE Tuple(93, Decimal("224.0070003")),NEWLINE Tuple(94, Decimal("224.9833247")),NEWLINE Tuple(95, Decimal("227.4214443")),NEWLINE Tuple(96, Decimal("229.3374133")),NEWLINE Tuple(97, Decimal("231.2501887")),NEWLINE Tuple(98, Decimal("231.9872353")),NEWLINE Tuple(99, Decimal("233.6934042")),NEWLINE Tuple(100, Decimal("236.5242297")),NEWLINE Tuple(101, Decimal("237.7698205")),NEWLINE Tuple(102, Decimal("239.5554776")),NEWLINE Tuple(103, Decimal("241.0491578")),NEWLINE Tuple(104, Decimal("242.8232719")),NEWLINE Tuple(105, Decimal("244.0708985")),NEWLINE Tuple(106, Decimal("247.1369901")),NEWLINE Tuple(107, Decimal("248.1019901")),NEWLINE Tuple(108, Decimal("249.5736896")),NEWLINE Tuple(109, Decimal("251.0149478")),NEWLINE Tuple(110, Decimal("253.0699867")),NEWLINE Tuple(111, Decimal("255.3062565")),NEWLINE Tuple(112, Decimal("256.3807137")),NEWLINE Tuple(113, Decimal("258.6104395")),NEWLINE Tuple(114, Decimal("259.8744070")),NEWLINE Tuple(115, Decimal("260.8050845")),NEWLINE Tuple(116, Decimal("263.5738939")),NEWLINE Tuple(117, Decimal("265.5578518")),NEWLINE Tuple(118, Decimal("266.6149738")),NEWLINE Tuple(119, Decimal("267.9219151")),NEWLINE Tuple(120, Decimal("269.9704490")),NEWLINE Tuple(121, Decimal("271.4940556")),NEWLINE Tuple(122, Decimal("273.4596092")),NEWLINE Tuple(123, Decimal("275.5874926")),NEWLINE Tuple(124, Decimal("276.4520495")),NEWLINE Tuple(125, Decimal("278.2507435")),NEWLINE Tuple(126, Decimal("279.2292509")),NEWLINE Tuple(127, Decimal("282.4651148")),NEWLINE Tuple(128, Decimal("283.2111857")),NEWLINE Tuple(129, Decimal("284.8359640")),NEWLINE Tuple(130, Decimal("286.6674454")),NEWLINE Tuple(131, Decimal("287.9119205")),NEWLINE Tuple(132, Decimal("289.5798549")),NEWLINE Tuple(133, Decimal("291.8462913")),NEWLINE Tuple(134, Decimal("293.5584341")),NEWLINE Tuple(135, Decimal("294.9653696")),NEWLINE Tuple(136, Decimal("295.5732549")),NEWLINE Tuple(137, Decimal("297.9792771")),NEWLINE Tuple(138, Decimal("299.8403261")),NEWLINE Tuple(139, Decimal("301.6493255")),NEWLINE Tuple(140, Decimal("302.6967496")),NEWLINE Tuple(141, Decimal("304.8643713")),NEWLINE Tuple(142, Decimal("305.7289126")),NEWLINE Tuple(143, Decimal("307.2194961")),NEWLINE Tuple(144, Decimal("310.1094631")),NEWLINE Tuple(145, Decimal("311.1651415")),NEWLINE Tuple(146, Decimal("312.4278012")),NEWLINE Tuple(147, Decimal("313.9852857")),NEWLINE Tuple(148, Decimal("315.4756161")),NEWLINE Tuple(149, Decimal("317.7348059")),NEWLINE Tuple(150, Decimal("318.8531043")),NEWLINE Tuple(151, Decimal("321.1601343")),NEWLINE Tuple(152, Decimal("322.1445587")),NEWLINE Tuple(153, Decimal("323.4669696")),NEWLINE Tuple(154, Decimal("324.8628661")),NEWLINE Tuple(155, Decimal("327.4439013")),NEWLINE Tuple(156, Decimal("329.0330717")),NEWLINE Tuple(157, Decimal("329.9532397")),NEWLINE Tuple(158, Decimal("331.4744676")),NEWLINE Tuple(159, Decimal("333.6453785")),NEWLINE Tuple(160, Decimal("334.2113548")),NEWLINE Tuple(161, Decimal("336.8418504")),NEWLINE Tuple(162, Decimal("338.3399929")),NEWLINE Tuple(163, Decimal("339.8582167")),NEWLINE Tuple(164, Decimal("341.0422611")),NEWLINE Tuple(165, Decimal("342.0548775")),NEWLINE Tuple(166, Decimal("344.6617029")),NEWLINE Tuple(167, Decimal("346.3478706")),NEWLINE Tuple(168, Decimal("347.2726776")),NEWLINE Tuple(169, Decimal("349.3162609")),NEWLINE Tuple(170, Decimal("350.4084193")),NEWLINE Tuple(171, Decimal("351.8786490")),NEWLINE Tuple(172, Decimal("353.4889005")),NEWLINE Tuple(173, Decimal("356.0175750")),NEWLINE Tuple(174, Decimal("357.1513023")),NEWLINE Tuple(175, Decimal("357.9526851")),NEWLINE Tuple(176, Decimal("359.7437550")),NEWLINE Tuple(177, Decimal("361.2893617")),NEWLINE Tuple(178, Decimal("363.3313306")),NEWLINE Tuple(179, Decimal("364.7360241")),NEWLINE Tuple(180, Decimal("366.2127103")),NEWLINE Tuple(181, Decimal("367.9935755")),NEWLINE Tuple(182, Decimal("368.9684381")),NEWLINE Tuple(183, Decimal("370.0509192")),NEWLINE Tuple(184, Decimal("373.0619284")),NEWLINE Tuple(185, Decimal("373.8648739")),NEWLINE Tuple(186, Decimal("375.8259128")),NEWLINE Tuple(187, Decimal("376.3240922")),NEWLINE Tuple(188, Decimal("378.4366802")),NEWLINE Tuple(189, Decimal("379.8729753")),NEWLINE Tuple(190, Decimal("381.4844686")),NEWLINE Tuple(191, Decimal("383.4435294")),NEWLINE Tuple(192, Decimal("384.9561168")),NEWLINE Tuple(193, Decimal("385.8613008")),NEWLINE Tuple(194, Decimal("387.2228902")),NEWLINE Tuple(195, Decimal("388.8461284")),NEWLINE Tuple(196, Decimal("391.4560836")),NEWLINE Tuple(197, Decimal("392.2450833")),NEWLINE Tuple(198, Decimal("393.4277438")),NEWLINE Tuple(199, Decimal("395.5828700")),NEWLINE Tuple(200, Decimal("396.3818542")),NEWLINE Tuple(201, Decimal("397.9187362")),NEWLINE Tuple(202, Decimal("399.9851199")),NEWLINE Tuple(203, Decimal("401.8392286")),NEWLINE Tuple(204, Decimal("402.8619178")),NEWLINE Tuple(205, Decimal("404.2364418")),NEWLINE Tuple(206, Decimal("405.1343875")),NEWLINE Tuple(207, Decimal("407.5814604")),NEWLINE Tuple(208, Decimal("408.9472455")),NEWLINE Tuple(209, Decimal("410.5138692")),NEWLINE Tuple(210, Decimal("411.9722678")),NEWLINE Tuple(211, Decimal("413.2627361")),NEWLINE Tuple(212, Decimal("415.0188098")),NEWLINE Tuple(213, Decimal("415.4552150")),NEWLINE Tuple(214, Decimal("418.3877058")),NEWLINE Tuple(215, Decimal("419.8613648")),NEWLINE Tuple(216, Decimal("420.6438276")),NEWLINE Tuple(217, Decimal("422.0767101")),NEWLINE Tuple(218, Decimal("423.7165796")),NEWLINE Tuple(219, Decimal("425.0698825")),NEWLINE Tuple(220, Decimal("427.2088251")),NEWLINE Tuple(221, Decimal("428.1279141")),NEWLINE Tuple(222, Decimal("430.3287454")),NEWLINE Tuple(223, Decimal("431.3013069")),NEWLINE Tuple(224, Decimal("432.1386417")),NEWLINE Tuple(225, Decimal("433.8892185")),NEWLINE Tuple(226, Decimal("436.1610064")),NEWLINE Tuple(227, Decimal("437.5816982")),NEWLINE Tuple(228, Decimal("438.6217387")),NEWLINE Tuple(229, Decimal("439.9184422")),NEWLINE Tuple(230, Decimal("441.6831992")),NEWLINE Tuple(231, Decimal("442.9045463")),NEWLINE Tuple(232, Decimal("444.3193363")),NEWLINE Tuple(233, Decimal("446.8606227")),NEWLINE Tuple(234, Decimal("447.4417042")),NEWLINE Tuple(235, Decimal("449.1485457")),NEWLINE Tuple(236, Decimal("450.1269458")),NEWLINE Tuple(237, Decimal("451.4033084")),NEWLINE Tuple(238, Decimal("453.9867378")),NEWLINE Tuple(239, Decimal("454.9746838")),NEWLINE Tuple(240, Decimal("456.3284267")),NEWLINE Tuple(241, Decimal("457.9038931")),NEWLINE Tuple(242, Decimal("459.5134153")),NEWLINE Tuple(243, Decimal("460.0879444")),NEWLINE Tuple(244, Decimal("462.0653673")),NEWLINE Tuple(245, Decimal("464.0572869")),NEWLINE Tuple(246, Decimal("465.6715392")),NEWLINE Tuple(247, Decimal("466.5702869")),NEWLINE Tuple(248, Decimal("467.4390462")),NEWLINE Tuple(249, Decimal("469.5360046")),NEWLINE Tuple(250, Decimal("470.7736555")),NEWLINE Tuple(251, Decimal("472.7991747")),NEWLINE Tuple(252, Decimal("473.8352323")),NEWLINE Tuple(253, Decimal("475.6003394")),NEWLINE Tuple(254, Decimal("476.7690152")),NEWLINE Tuple(255, Decimal("478.0752638")),NEWLINE Tuple(256, Decimal("478.9421815")),NEWLINE Tuple(257, Decimal("481.8303394")),NEWLINE Tuple(258, Decimal("482.8347828")),NEWLINE Tuple(259, Decimal("483.8514272")),NEWLINE Tuple(260, Decimal("485.5391481")),NEWLINE Tuple(261, Decimal("486.5287183")),NEWLINE Tuple(262, Decimal("488.3805671")),NEWLINE Tuple(263, Decimal("489.6617616")),NEWLINE Tuple(264, Decimal("491.3988216")),NEWLINE Tuple(265, Decimal("493.3144416")),NEWLINE Tuple(266, Decimal("493.9579978")),NEWLINE Tuple(267, Decimal("495.3588288")),NEWLINE Tuple(268, Decimal("496.4296962")),NEWLINE Tuple(269, Decimal("498.5807824")),NEWLINE Tuple(270, Decimal("500.3090849")),NEWLINE Tuple(271, Decimal("501.6044470")),NEWLINE Tuple(272, Decimal("502.2762703")),NEWLINE Tuple(273, Decimal("504.4997733")),NEWLINE Tuple(274, Decimal("505.4152317")),NEWLINE Tuple(275, Decimal("506.4641527")),NEWLINE Tuple(276, Decimal("508.8007003")),NEWLINE Tuple(277, Decimal("510.2642279")),NEWLINE Tuple(278, Decimal("511.5622897")),NEWLINE Tuple(279, Decimal("512.6231445")),NEWLINE Tuple(280, Decimal("513.6689856")),NEWLINE Tuple(281, Decimal("515.4350572")),NEWLINE Tuple(282, Decimal("517.5896686")),NEWLINE Tuple(283, Decimal("518.2342231")),NEWLINE Tuple(284, Decimal("520.1063104")),NEWLINE Tuple(285, Decimal("521.5251934")),NEWLINE Tuple(286, Decimal("522.4566962")),NEWLINE Tuple(287, Decimal("523.9605309")),NEWLINE Tuple(288, Decimal("525.0773857")),NEWLINE Tuple(289, Decimal("527.9036416")),NEWLINE Tuple(290, Decimal("528.4062139")),NEWLINE Tuple(291, Decimal("529.8062263")),NEWLINE Tuple(292, Decimal("530.8669179")),NEWLINE Tuple(293, Decimal("532.6881830")),NEWLINE Tuple(294, Decimal("533.7796308")),NEWLINE Tuple(295, Decimal("535.6643141")),NEWLINE Tuple(296, Decimal("537.0697591")),NEWLINE Tuple(297, Decimal("538.4285262")),NEWLINE Tuple(298, Decimal("540.2131664")),NEWLINE Tuple(299, Decimal("540.6313902")),NEWLINE Tuple(300, Decimal("541.8474371")),NEWLINE Tuple(301, Decimal("544.3238901")),NEWLINE Tuple(302, Decimal("545.6368332")),NEWLINE Tuple(303, Decimal("547.0109121")),NEWLINE Tuple(304, Decimal("547.9316134")),NEWLINE Tuple(305, Decimal("549.4975676")),NEWLINE Tuple(306, Decimal("550.9700100")),NEWLINE Tuple(307, Decimal("552.0495722")),NEWLINE Tuple(308, Decimal("553.7649721")),NEWLINE Tuple(309, Decimal("555.7920206")),NEWLINE Tuple(310, Decimal("556.8994764")),NEWLINE Tuple(311, Decimal("557.5646592")),NEWLINE Tuple(312, Decimal("559.3162370")),NEWLINE Tuple(313, Decimal("560.2408075")),NEWLINE Tuple(314, Decimal("562.5592076")),NEWLINE Tuple(315, Decimal("564.1608791")),NEWLINE Tuple(316, Decimal("564.5060559")),NEWLINE Tuple(317, Decimal("566.6987877")),NEWLINE Tuple(318, Decimal("567.7317579")),NEWLINE Tuple(319, Decimal("568.9239552")),NEWLINE Tuple(320, Decimal("570.0511148")),NEWLINE Tuple(321, Decimal("572.4199841")),NEWLINE Tuple(322, Decimal("573.6146105")),NEWLINE Tuple(323, Decimal("575.0938860")),NEWLINE Tuple(324, Decimal("575.8072471")),NEWLINE Tuple(325, Decimal("577.0390035")),NEWLINE Tuple(326, Decimal("579.0988347")),NEWLINE Tuple(327, Decimal("580.1369594")),NEWLINE Tuple(328, Decimal("581.9465763")),NEWLINE Tuple(329, Decimal("583.2360882")),NEWLINE Tuple(330, Decimal("584.5617059")),NEWLINE Tuple(331, Decimal("585.9845632")),NEWLINE Tuple(332, Decimal("586.7427719")),NEWLINE Tuple(333, Decimal("588.1396633")),NEWLINE Tuple(334, Decimal("590.6603975")),NEWLINE Tuple(335, Decimal("591.7258581")),NEWLINE Tuple(336, Decimal("592.5713583")),NEWLINE Tuple(337, Decimal("593.9747147")),NEWLINE Tuple(338, Decimal("595.7281537")),NEWLINE Tuple(339, Decimal("596.3627683")),NEWLINE Tuple(340, Decimal("598.4930773")),NEWLINE Tuple(341, Decimal("599.5456404")),NEWLINE Tuple(342, Decimal("601.6021367")),NEWLINE Tuple(343, Decimal("602.5791679")),NEWLINE Tuple(344, Decimal("603.6256189")),NEWLINE Tuple(345, Decimal("604.6162185")),NEWLINE Tuple(346, Decimal("606.3834604")),NEWLINE Tuple(347, Decimal("608.4132173")),NEWLINE Tuple(348, Decimal("609.3895752")),NEWLINE Tuple(349, Decimal("610.8391629")),NEWLINE Tuple(350, Decimal("611.7742096")),NEWLINE Tuple(351, Decimal("613.5997787")),NEWLINE Tuple(352, Decimal("614.6462379")),NEWLINE Tuple(353, Decimal("615.5385634")),NEWLINE Tuple(354, Decimal("618.1128314")),NEWLINE Tuple(355, Decimal("619.1844826")),NEWLINE Tuple(356, Decimal("620.2728937")),NEWLINE Tuple(357, Decimal("621.7092945")),NEWLINE Tuple(358, Decimal("622.3750027")),NEWLINE Tuple(359, Decimal("624.2699000")),NEWLINE Tuple(360, Decimal("626.0192834")),NEWLINE Tuple(361, Decimal("627.2683969")),NEWLINE Tuple(362, Decimal("628.3258624")),NEWLINE Tuple(363, Decimal("630.4738874")),NEWLINE Tuple(364, Decimal("630.8057809")),NEWLINE Tuple(365, Decimal("632.2251412")),NEWLINE Tuple(366, Decimal("633.5468583")),NEWLINE Tuple(367, Decimal("635.5238003")),NEWLINE Tuple(368, Decimal("637.3971932")),NEWLINE Tuple(369, Decimal("637.9255140")),NEWLINE Tuple(370, Decimal("638.9279383")),NEWLINE Tuple(371, Decimal("640.6947947")),NEWLINE Tuple(372, Decimal("641.9454997")),NEWLINE Tuple(373, Decimal("643.2788838")),NEWLINE Tuple(374, Decimal("644.9905782")),NEWLINE Tuple(375, Decimal("646.3481916")),NEWLINE Tuple(376, Decimal("647.7617530")),NEWLINE Tuple(377, Decimal("648.7864009")),NEWLINE Tuple(378, Decimal("650.1975193")),NEWLINE Tuple(379, Decimal("650.6686839")),NEWLINE Tuple(380, Decimal("653.6495716")),NEWLINE Tuple(381, Decimal("654.3019206")),NEWLINE Tuple(382, Decimal("655.7094630")),NEWLINE Tuple(383, Decimal("656.9640846")),NEWLINE Tuple(384, Decimal("658.1756144")),NEWLINE Tuple(385, Decimal("659.6638460")),NEWLINE Tuple(386, Decimal("660.7167326")),NEWLINE Tuple(387, Decimal("662.2965864")),NEWLINE Tuple(388, Decimal("664.2446047")),NEWLINE Tuple(389, Decimal("665.3427631")),NEWLINE Tuple(390, Decimal("666.5151477")),NEWLINE Tuple(391, Decimal("667.1484949")),NEWLINE Tuple(392, Decimal("668.9758488")),NEWLINE Tuple(393, Decimal("670.3235852")),NEWLINE Tuple(394, Decimal("672.4581836")),NEWLINE Tuple(395, Decimal("673.0435783")),NEWLINE Tuple(396, Decimal("674.3558978")),NEWLINE Tuple(397, Decimal("676.1396744")),NEWLINE Tuple(398, Decimal("677.2301807")),NEWLINE Tuple(399, Decimal("677.8004447")),NEWLINE Tuple(400, Decimal("679.7421979")),NEWLINE Tuple(401, Decimal("681.8949915")),NEWLINE Tuple(402, Decimal("682.6027350")),NEWLINE Tuple(403, Decimal("684.0135498")),NEWLINE Tuple(404, Decimal("684.9726299")),NEWLINE Tuple(405, Decimal("686.1632236")),NEWLINE Tuple(406, Decimal("687.9615432")),NEWLINE Tuple(407, Decimal("689.3689414")),NEWLINE Tuple(408, Decimal("690.4747350")),NEWLINE Tuple(409, Decimal("692.4516844")),NEWLINE Tuple(410, Decimal("693.1769701")),NEWLINE Tuple(411, Decimal("694.5339087")),NEWLINE Tuple(412, Decimal("695.7263359")),NEWLINE Tuple(413, Decimal("696.6260699")),NEWLINE Tuple(414, Decimal("699.1320955")),NEWLINE Tuple(415, Decimal("700.2967391")),NEWLINE Tuple(416, Decimal("701.3017430")),NEWLINE Tuple(417, Decimal("702.2273431")),NEWLINE Tuple(418, Decimal("704.0338393")),NEWLINE Tuple(419, Decimal("705.1258140")),NEWLINE Tuple(420, Decimal("706.1846548")),NEWLINE Tuple(421, Decimal("708.2690709")),NEWLINE Tuple(422, Decimal("709.2295886")),NEWLINE Tuple(423, Decimal("711.1302742")),NEWLINE Tuple(424, Decimal("711.9002899")),NEWLINE Tuple(425, Decimal("712.7493835")),NEWLINE Tuple(426, Decimal("714.0827718")),NEWLINE Tuple(427, Decimal("716.1123965")),NEWLINE Tuple(428, Decimal("717.4825697")),NEWLINE Tuple(429, Decimal("718.7427865")),NEWLINE Tuple(430, Decimal("719.6971010")),NEWLINE Tuple(431, Decimal("721.3511622")),NEWLINE Tuple(432, Decimal("722.2775050")),NEWLINE Tuple(433, Decimal("723.8458210")),NEWLINE Tuple(434, Decimal("724.5626139")),NEWLINE Tuple(435, Decimal("727.0564032")),NEWLINE Tuple(436, Decimal("728.4054816")),NEWLINE Tuple(437, Decimal("728.7587498")),NEWLINE Tuple(438, Decimal("730.4164821")),NEWLINE Tuple(439, Decimal("731.4173549")),NEWLINE Tuple(440, Decimal("732.8180527")),NEWLINE Tuple(441, Decimal("734.7896433")),NEWLINE Tuple(442, Decimal("735.7654592")),NEWLINE Tuple(443, Decimal("737.0529289")),NEWLINE Tuple(444, Decimal("738.5804212")),NEWLINE Tuple(445, Decimal("739.9095237")),NEWLINE Tuple(446, Decimal("740.5738074")),NEWLINE Tuple(447, Decimal("741.7573356")),NEWLINE Tuple(448, Decimal("743.8950131")),NEWLINE Tuple(449, Decimal("745.3449896")),NEWLINE Tuple(450, Decimal("746.4993059")),NEWLINE Tuple(451, Decimal("747.6745636")),NEWLINE Tuple(452, Decimal("748.2427545")),NEWLINE Tuple(453, Decimal("750.6559504")),NEWLINE Tuple(454, Decimal("750.9663811")),NEWLINE Tuple(455, Decimal("752.8876216")),NEWLINE Tuple(456, Decimal("754.3223705")),NEWLINE Tuple(457, Decimal("755.8393090")),NEWLINE Tuple(458, Decimal("756.7682484")),NEWLINE Tuple(459, Decimal("758.1017292")),NEWLINE Tuple(460, Decimal("758.9002382")),NEWLINE Tuple(461, Decimal("760.2823670")),NEWLINE Tuple(462, Decimal("762.7000332")),NEWLINE Tuple(463, Decimal("763.5930662")),NEWLINE Tuple(464, Decimal("764.3075227")),NEWLINE Tuple(465, Decimal("766.0875401")),NEWLINE Tuple(466, Decimal("767.2184722")),NEWLINE Tuple(467, Decimal("768.2814618")),NEWLINE Tuple(468, Decimal("769.6934073")),NEWLINE Tuple(469, Decimal("771.0708393")),NEWLINE Tuple(470, Decimal("772.9616176")),NEWLINE Tuple(471, Decimal("774.1177446")),NEWLINE Tuple(472, Decimal("775.0478471")),NEWLINE Tuple(473, Decimal("775.9997120")),NEWLINE Tuple(474, Decimal("777.2997485")),NEWLINE Tuple(475, Decimal("779.1570769")),NEWLINE Tuple(476, Decimal("780.3489250")),NEWLINE Tuple(477, Decimal("782.1376644")),NEWLINE Tuple(478, Decimal("782.5979439")),NEWLINE Tuple(479, Decimal("784.2888226")),NEWLINE Tuple(480, Decimal("785.7390897")),NEWLINE Tuple(481, Decimal("786.4611475")),NEWLINE Tuple(482, Decimal("787.4684638")),NEWLINE Tuple(483, Decimal("790.0590924")),NEWLINE Tuple(484, Decimal("790.8316205")),NEWLINE Tuple(485, Decimal("792.4277076")),NEWLINE Tuple(486, Decimal("792.8886526")),NEWLINE Tuple(487, Decimal("794.4837919")),NEWLINE Tuple(488, Decimal("795.6065962")),NEWLINE Tuple(489, Decimal("797.2634700")),NEWLINE Tuple(490, Decimal("798.7075702")),NEWLINE Tuple(491, Decimal("799.6543362")),NEWLINE Tuple(492, Decimal("801.6042465")),NEWLINE Tuple(493, Decimal("802.5419849")),NEWLINE Tuple(494, Decimal("803.2430962")),NEWLINE Tuple(495, Decimal("804.7622391")),NEWLINE Tuple(496, Decimal("805.8616357")),NEWLINE Tuple(497, Decimal("808.1518149")),NEWLINE Tuple(498, Decimal("809.1977834")),NEWLINE Tuple(499, Decimal("810.0818049")),NEWLINE Tuple(500, Decimal("811.1843588"))))))NEWLINENEWLINENEWLINEmake_entry(ID("2e1cc7"),NEWLINE Description("Table of", Im(RiemannZetaZero(10**n)), "to 50 digits for", LessEqual(0, n, 16)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(Im(RiemannZetaZero(10**n)), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("14.134725141734693790457251983562470270784257115699")),NEWLINE Tuple(1, Decimal("49.773832477672302181916784678563724057723178299677")),NEWLINE Tuple(2, Decimal("236.52422966581620580247550795566297868952949521219")),NEWLINE Tuple(3, Decimal("1419.4224809459956864659890380799168192321006010642")),NEWLINE Tuple(4, Decimal("9877.7826540055011427740990706901235776224680517811")),NEWLINE Tuple(5, Decimal("74920.827498994186793849200946918346620223555216802")),NEWLINE Tuple(6, Decimal("600269.67701244495552123391427049074396819125790619")),NEWLINE Tuple(7, Decimal("4992381.0140031786660182508391600932712387635814368")),NEWLINE Tuple(8, Decimal("42653549.760951553903050309232819667982595130452178")),NEWLINE Tuple(9, Decimal("371870203.83702805273405479598662519100082698522485")),NEWLINE Tuple(10, Decimal("3293531632.3971367042089917031338769677069644102625")),NEWLINE Tuple(11, Decimal("29538618431.613072810689561192671546108506486777642")),NEWLINE Tuple(12, Decimal("267653395648.62594824214264940920070899588029633790")),NEWLINE Tuple(13, Decimal("2445999556030.2468813938032396773514175248139258741")),NEWLINE Tuple(14, Decimal("22514484222485.729124253904444090280880182979014905")),NEWLINE Tuple(15, Decimal("208514052006405.46942460229754774510609948399247941")),NEWLINE Tuple(16, Decimal("1941393531395154.7112809113883108073327538053720311")))))NEWLINENEWLINEmake_entry(ID("71d9d9"),NEWLINE Description("Table of", Im(RiemannZetaZero(n)), "to 50 digits for", LessEqual(1, n, 50)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(Im(RiemannZetaZero(n)), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(1, Decimal("14.134725141734693790457251983562470270784257115699")),NEWLINE Tuple(2, Decimal("21.022039638771554992628479593896902777334340524903")),NEWLINE Tuple(3, Decimal("25.010857580145688763213790992562821818659549672558")),NEWLINE Tuple(4, Decimal("30.424876125859513210311897530584091320181560023715")),NEWLINE Tuple(5, Decimal("32.935061587739189690662368964074903488812715603517")),NEWLINE Tuple(6, Decimal("37.586178158825671257217763480705332821405597350831")),NEWLINE Tuple(7, Decimal("40.918719012147495187398126914633254395726165962777")),NEWLINE Tuple(8, Decimal("43.327073280914999519496122165406805782645668371837")),NEWLINE Tuple(9, Decimal("48.005150881167159727942472749427516041686844001144")),NEWLINE Tuple(10, Decimal("49.773832477672302181916784678563724057723178299677")),NEWLINE Tuple(11, Decimal("52.970321477714460644147296608880990063825017888821")),NEWLINE Tuple(12, Decimal("56.446247697063394804367759476706127552782264471717")),NEWLINE Tuple(13, Decimal("59.347044002602353079653648674992219031098772806467")),NEWLINE Tuple(14, Decimal("60.831778524609809844259901824524003802910090451219")),NEWLINE Tuple(15, Decimal("65.112544048081606660875054253183705029348149295167")),NEWLINE Tuple(16, Decimal("67.079810529494173714478828896522216770107144951746")),NEWLINE Tuple(17, Decimal("69.546401711173979252926857526554738443012474209603")),NEWLINE Tuple(18, Decimal("72.067157674481907582522107969826168390480906621457")),NEWLINE Tuple(19, Decimal("75.704690699083933168326916762030345922811903530697")),NEWLINE Tuple(20, Decimal("77.144840068874805372682664856304637015796032449234")),NEWLINE Tuple(21, Decimal("79.337375020249367922763592877116228190613246743120")),NEWLINE Tuple(22, Decimal("82.910380854086030183164837494770609497508880593782")),NEWLINE Tuple(23, Decimal("84.735492980517050105735311206827741417106627934241")),NEWLINE Tuple(24, Decimal("87.425274613125229406531667850919213252171886401269")),NEWLINE Tuple(25, Decimal("88.809111207634465423682348079509378395444893409819")),NEWLINE Tuple(26, Decimal("92.491899270558484296259725241810684878721794027731")),NEWLINE Tuple(27, Decimal("94.651344040519886966597925815208153937728027015655")),NEWLINE Tuple(28, Decimal("95.870634228245309758741029219246781695256461224988")),NEWLINE Tuple(29, Decimal("98.831194218193692233324420138622327820658039063428")),NEWLINE Tuple(30, Decimal("101.31785100573139122878544794029230890633286638430")),NEWLINE Tuple(31, Decimal("103.72553804047833941639840810869528083448117306950")),NEWLINE Tuple(32, Decimal("105.44662305232609449367083241411180899728275392854")),NEWLINE Tuple(33, Decimal("107.16861118427640751512335196308619121347670788140")),NEWLINE Tuple(34, Decimal("111.02953554316967452465645030994435041534596839007")),NEWLINE Tuple(35, Decimal("111.87465917699263708561207871677059496031174987339")),NEWLINE Tuple(36, Decimal("114.32022091545271276589093727619107980991765772383")),NEWLINE Tuple(37, Decimal("116.22668032085755438216080431206475512732985123238")),NEWLINE Tuple(38, Decimal("118.79078286597621732297913970269982434730621059281")),NEWLINE Tuple(39, Decimal("121.37012500242064591894553297049992272300131063173")),NEWLINE Tuple(40, Decimal("122.94682929355258820081746033077001649621438987386")),NEWLINE Tuple(41, Decimal("124.25681855434576718473200796612992444157353877469")),NEWLINE Tuple(42, Decimal("127.51668387959649512427932376690607626808830988155")),NEWLINE Tuple(43, Decimal("129.57870419995605098576803390617997360864095326466")),NEWLINE Tuple(44, Decimal("131.08768853093265672356637246150134905920354750298")),NEWLINE Tuple(45, Decimal("133.49773720299758645013049204264060766497417494390")),NEWLINE Tuple(46, Decimal("134.75650975337387133132606415716973617839606861365")),NEWLINE Tuple(47, Decimal("138.11604205453344320019155519028244785983527462415")),NEWLINE Tuple(48, Decimal("139.73620895212138895045004652338246084679005256538")),NEWLINE Tuple(49, Decimal("141.12370740402112376194035381847535509030066087975")),NEWLINE Tuple(50, Decimal("143.11184580762063273940512386891392996623310243035")))))NEWLINENEWLINEdef_Topic(NEWLINE Title("Riemann hypothesis"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "c03de4",NEWLINE ),NEWLINE Section("Formal statement"),NEWLINE Description("Related topics:",NEWLINE TopicReference("Riemann zeta function"), ",",NEWLINE TopicReference("Zeros of the Riemann zeta function"),NEWLINE ),NEWLINE Entries(NEWLINE "9fa2a1",NEWLINE "49704a",NEWLINE ),NEWLINE Section("Statements equivalent to the Riemann hypothesis"),NEWLINE Subsection("Prime counting function"),NEWLINE Description("Related topic:",NEWLINE TopicReference("Prime numbers"),NEWLINE ),NEWLINE Entries(NEWLINE "bfaeb5",NEWLINE ),NEWLINE Subsection("Robin's criterion"),NEWLINE Entries(NEWLINE "3142ec",NEWLINE "e4287f",NEWLINE ),NEWLINE Subsection("Li's criterion"),NEWLINE Description("Related topic:", TopicReference("Keiper-Li coefficients")),NEWLINE Entries(NEWLINE "e68f82",NEWLINE "a5d65f",NEWLINE ),NEWLINE Subsection("Landau's function"),NEWLINE Description("Related topic:", TopicReference("Landau's function")),NEWLINE Entries(NEWLINE "65fa9f", # included from landau's functionNEWLINE ),NEWLINE Subsection("Definite integrals"),NEWLINE Entries(NEWLINE "7783f9",NEWLINE "cf70ce",NEWLINE ),NEWLINE Subsection("De Bruijn-Newman constant"),NEWLINE Entries(NEWLINE "22ab47",NEWLINE "a71ddd",NEWLINE ),NEWLINE Section("Formulas conditional on the Riemann hypothesis"),NEWLINE Entries(NEWLINE "e6ff64",NEWLINE "375afe",NEWLINE ),NEWLINE Section("Generalizations"),NEWLINE Description("Related topic:",NEWLINE TopicReference("Dirichlet L-functions"),NEWLINE ),NEWLINE Entries(NEWLINE "dc593e",NEWLINE "e2a734",NEWLINE ),NEWLINE)NEWLINENEWLINEmake_entry(ID("c03de4"),NEWLINE SymbolDefinition(RiemannHypothesis, RiemannHypothesis, "Riemann hypothesis"),NEWLINE Description("Represents the truth value of the Riemann hypothesis, defined in ", EntryReference("49704a"), "."),NEWLINE Description("Semantically, ", Element(RiemannHypothesis, Set(True_, False_)), "."),NEWLINE Description("This symbol can be used in an assumption to express that a formula is valid conditionally on the truth of the Riemann hypothesis."))NEWLINENEWLINEmake_entry(ID("9fa2a1"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Equal(Re(s), Div(1,2)), ForElement(s, CC), And(LessEqual(0, Re(s), 1), Equal(RiemannZeta(s), 0))))))NEWLINENEWLINEmake_entry(ID("49704a"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Equal(Re(RiemannZetaZero(n)), Div(1,2)), ForElement(n, ZZGreaterEqual(1))))))NEWLINENEWLINEmake_entry(ID("bfaeb5"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(Abs(PrimePi(x) - LogIntegral(x)), Sqrt(x) * Log(x)), ForElement(x, ClosedOpenInterval(2, Infinity))))),NEWLINE References("https://mathoverflow.net/q/338066"))NEWLINENEWLINEmake_entry(ID("3142ec"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(DivisorSigma(1,n), Exp(ConstGamma) * n*Log(Log(n))), ForElement(n, ZZGreaterEqual(5041))))))NEWLINENEWLINEmake_entry(ID("e4287f"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Less(DivisorSigma(1,n), HarmonicNumber(n) + Exp(HarmonicNumber(n)) * Log(HarmonicNumber(n))), ForElement(n, ZZGreaterEqual(2))))),NEWLINE References("https://doi.org/10.2307/2695443"))NEWLINENEWLINEmake_entry(ID("22ab47"),NEWLINE SymbolDefinition(DeBruijnNewmanLambda, DeBruijnNewmanLambda, "De Bruijn-Newman constant"))NEWLINENEWLINEmake_entry(ID("a71ddd"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(DeBruijnNewmanLambda, 0))),NEWLINE References("https://arxiv.org/abs/1801.05914"))NEWLINENEWLINEmake_entry(ID("7783f9"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(NEWLINE (1/Pi) * Integral(Log(Abs(RiemannZeta(Div(1,2)+ConstI*t)/RiemannZeta(Div(1,2)))) * Div(1,t**2), For(t, 0, Infinity)),NEWLINE Pi/8 + ConstGamma/4 + Log(8*Pi)/4 - 2))),NEWLINE References("https://mathoverflow.net/q/279936"))NEWLINENEWLINEmake_entry(ID("cf70ce"),NEWLINE Formula(Equivalent(RiemannHypothesis, Equal(NEWLINE Integral((1-12*t**2)/(1+4*t**2)**3 * Integral(Log(Abs(RiemannZeta(sigma + ConstI*t))), For(sigma, Div(1,2), Infinity)), For(t, 0, Infinity)),NEWLINE Pi * (3-ConstGamma) / 32))),NEWLINE References("https://doi.org/10.1007/BF01056314"))NEWLINENEWLINENEWLINEdef_Topic(NEWLINE Title("Keiper-Li coefficients"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "432bee",NEWLINE ),NEWLINE Section("Representations"),NEWLINE Entries(NEWLINE "fcab61",NEWLINE "cce75b",NEWLINE ),NEWLINE Section("Specific values"),NEWLINE Entries(NEWLINE "081205",NEWLINE "d8d820",NEWLINE "faf448",NEWLINE "706f66",NEWLINE ),NEWLINE Section("Asymptotics"),NEWLINE Entries(NEWLINE "64bd32",NEWLINE ),NEWLINE Section("Riemann hypothesis (Li's criterion)"),NEWLINE EntriesNEWLINE (NEWLINE "e68f82",NEWLINE "a5d65f",NEWLINE "8f8fb7",NEWLINE ),NEWLINE)NEWLINENEWLINEmake_entry(ID("432bee"),NEWLINE SymbolDefinition(KeiperLiLambda, KeiperLiLambda(n), "Keiper-Li coefficient"),NEWLINE Description(SourceForm(KeiperLiLambda(n)), ", rendered as", KeiperLiLambda(n),NEWLINE ", denotes a power series coefficient associated with the Riemann zeta function. "),NEWLINE Description("The definition", EntryReference("fcab61"), "follows Keiper (1992). Li (1997) defines the coefficients with a different scaling factor, equivalent to", n*KeiperLiLambda(n), "in Keiper's (and Fungrim's) notation."),NEWLINE References("https://doi.org/10.2307/2153215", "https://doi.org/10.1006/jnth.1997.2137", "https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("fcab61"),NEWLINE Formula(Equal(KeiperLiLambda(n), (1/Factorial(n)) * ComplexDerivative(Log(2 * RiemannXi(s/(s-1))), For(s, 0, n)))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(0))))NEWLINENEWLINE# todo: absolute convergence? need to encode order of summation?NEWLINEmake_entry(ID("cce75b"),NEWLINE Formula(Equal(KeiperLiLambda(n), (1/n) * Sum(Parentheses(1 - (RiemannZetaZero(k) / (RiemannZetaZero(k) - 1))**n), ForElement(k, ZZ), NotEqual(k, 0)))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(1))))NEWLINENEWLINEmake_entry(ID("081205"),NEWLINE Formula(Equal(KeiperLiLambda(0), 0)))NEWLINENEWLINEmake_entry(ID("d8d820"),NEWLINE Formula(Equal(KeiperLiLambda(1), (ConstGamma/2 + 1) - Log(4*Pi)/2)))NEWLINENEWLINEmake_entry(ID("faf448"),NEWLINE Description("Table of", KeiperLiLambda(n), "to 50 digits for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(KeiperLiLambda(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0")),NEWLINE Tuple(1, Decimal("0.023095708966121033814310247906495291621932127152051")),NEWLINE Tuple(2, Decimal("0.046172867614023335192864243096033943387066108314123")),NEWLINE Tuple(3, Decimal("0.069212973518108267930497348872601068994212026393200")),NEWLINE Tuple(4, Decimal("0.092197619873060409647627872409439018065541673490213")),NEWLINE Tuple(5, Decimal("0.11510854289223549048622128109857276671349132303596")),NEWLINE Tuple(6, Decimal("0.13792766871372988290416713700341666356138966078654")),NEWLINE Tuple(7, Decimal("0.16063715965299421294040287257385366292282442046163")),NEWLINE Tuple(8, Decimal("0.18321945964338257908193931774721859848998098273432")),NEWLINE Tuple(9, Decimal("0.20565733870917046170289387421343304741236553410044")),NEWLINE Tuple(10, Decimal("0.22793393631931577436930340573684453380748385942738")),NEWLINE Tuple(11, Decimal("0.25003280347456327821404973571398176484638012641151")),NEWLINE Tuple(12, Decimal("0.27193794338538498733992383249265390667786600994911")),NEWLINE Tuple(13, Decimal("0.29363385060368815285418215009889439246684857721098")),NEWLINE Tuple(14, Decimal("0.31510554847718560800576009263276843951188505373007")),NEWLINE Tuple(15, Decimal("0.33633862480178623056900742916909716316435743073656")),NEWLINE Tuple(16, Decimal("0.35731926555429953996369166686545971896237127626351")),NEWLINE Tuple(17, Decimal("0.37803428659512958242032593887899541131751543174423")),NEWLINE Tuple(18, Decimal("0.39847116323842905329183170701797400318996274958010")),NEWLINE Tuple(19, Decimal("0.41861805759536317393727500409965507879749928476235")),NEWLINE Tuple(20, Decimal("0.43846384360466075647997306767236011141956127351910")),NEWLINE Tuple(21, Decimal("0.45799812967347233249339981618322155418048244629837")),NEWLINE Tuple(22, Decimal("0.47721127886067612259488922142809435229670372335579")),NEWLINE Tuple(23, Decimal("0.49609442654413481917007764284527175942412402470703")),NEWLINE Tuple(24, Decimal("0.51463949552297154237641907033478550942000739520745")),NEWLINE Tuple(25, Decimal("0.53283920851566303199773431527093937195060386800653")),NEWLINE Tuple(26, Decimal("0.55068709802460266427322142354105110711472096137358")),NEWLINE Tuple(27, Decimal("0.56817751354772529773768642819955547787404863111699")),NEWLINE Tuple(28, Decimal("0.58530562612777004271739082427374534543603950676386")),NEWLINE Tuple(29, Decimal("0.60206743023974549532618306036749838157067445931420")),NEWLINE Tuple(30, Decimal("0.61845974302711452077115586049317787034309975741269")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("706f66"),NEWLINE Description("Table of", KeiperLiLambda(10**n), "to 50 digits for", LessEqual(0, n, 5)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(KeiperLiLambda(10**n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0.023095708966121033814310247906495291621932127152051")),NEWLINE Tuple(1, Decimal("0.22793393631931577436930340573684453380748385942738")),NEWLINE Tuple(2, Decimal("1.1860377537679132992736469839793792693298702359323")),NEWLINE Tuple(3, Decimal("2.3260531616864664574065046940832238158044982041693")),NEWLINE Tuple(4, Decimal("3.4736579732241613740180609478145593215167373519711")),NEWLINE Tuple(5, Decimal("4.6258078240690223140941603808334320467617286152507")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("64bd32"),NEWLINE Formula(Implies(RiemannHypothesis, AsymptoticTo(KeiperLiLambda(n), Log(n)/2 - (Log(2*Pi) + 1 - ConstGamma)/2, n, Infinity))),NEWLINE References("https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("e68f82"),NEWLINE Formula(Equivalent(RiemannHypothesis, All(Greater(KeiperLiLambda(n), 0), ForElement(n, ZZGreaterEqual(1))))),NEWLINE References("https://doi.org/10.1006/jnth.1997.2137"))NEWLINENEWLINEmake_entry(ID("a5d65f"),NEWLINE Formula(Equivalent(RiemannHypothesis, Where(Less(Sum(Abs(KeiperLiLambda(n) - a(n))**2, For(n, 1, Infinity)), Infinity),NEWLINE Equal(a(n), Log(n)/2 - (Log(2*Pi) + 1 - ConstGamma)/2)))),NEWLINE References("https://doi.org/10.7169/facm/1317045228"))NEWLINENEWLINEmake_entry(ID("8f8fb7"),NEWLINE Formula(Implies(NEWLINE All(Equal(Re(RiemannZetaZero(n)), Div(1,2)), ForElement(n, ZZGreaterEqual(1)), Less(Im(RiemannZetaZero(n)), T)),NEWLINE All(GreaterEqual(KeiperLiLambda(n), 0), ForElement(n, ZZGreaterEqual(0)), LessEqual(n, T**2)))),NEWLINE Variables(T),NEWLINE Assumptions(Element(T, ClosedOpenInterval(0, Infinity))),NEWLINE References("https://arxiv.org/abs/1703.02844"))NEWLINENEWLINENEWLINEdef_Topic(NEWLINE Title("Stieltjes constants"),NEWLINE Section("Definitions"),NEWLINE Entries(NEWLINE "d10029",NEWLINE ),NEWLINE Section("Generating functions"),NEWLINE Entries(NEWLINE "b1a2e1",NEWLINE "60c6da",NEWLINE ),NEWLINE Section("Limit representations"),NEWLINE Entries(NEWLINE "411f3b",NEWLINE ),NEWLINE Section("Specific values"),NEWLINE Entries(NEWLINE "51206a",NEWLINE "8ae153",NEWLINE "b6808d",NEWLINE "70a705",NEWLINE "e5bd3c",NEWLINE "569d5c",NEWLINE ),NEWLINE Section("Recurrence relations"),NEWLINE Entries(NEWLINE "687b4d",NEWLINE ),NEWLINE Section("Integral representations"),NEWLINE Entries(NEWLINE "a41c92",NEWLINE ),NEWLINE Section("Bounds and inequalities"),NEWLINE Entries(NEWLINE "1dec0d",NEWLINE )NEWLINE)NEWLINENEWLINEmake_entry(ID("d10029"),NEWLINE SymbolDefinition(StieltjesGamma, StieltjesGamma(n, a), "Stieltjes constant"),NEWLINE Description(SourceForm(StieltjesGamma(n)), ", rendered as", StieltjesGamma(n), ", represents the Stieltjes constant of index", n, "."),NEWLINE Description(SourceForm(StieltjesGamma(n, a)), ", rendered as", StieltjesGamma(n, a), ", represents the generalized Stieltjes constant of index", n, " with parameter", a, "."),NEWLINE Table(TableRelation(Tuple(P, Q), Implies(P, Q)),NEWLINE TableHeadings(Description("Domain"), Description("Codomain")),NEWLINE List(NEWLINE Tuple(Element(n, ZZGreaterEqual(0)), Element(StieltjesGamma(n), RR)),NEWLINE Tuple(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0))), Element(StieltjesGamma(n, a), CC)),NEWLINE ))NEWLINE)NEWLINENEWLINE# Generating functionsNEWLINENEWLINEmake_entry(ID("b1a2e1"),NEWLINE Formula(Equal(RiemannZeta(s), 1/(s-1) + Sum((-1)**n/Factorial(n) * StieltjesGamma(n) * (s-1)**n, For(n, 0, Infinity)))),NEWLINE Variables(s),NEWLINE Assumptions(Element(s, CC)))NEWLINENEWLINEmake_entry(ID("60c6da"),NEWLINE Formula(Equal(HurwitzZeta(s, a), 1/(s-1) + Sum((-1)**n/Factorial(n) * StieltjesGamma(n, a) * (s-1)**n, For(n, 0, Infinity)))),NEWLINE Variables(s, a),NEWLINE Assumptions(And(Element(s, CC), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Limit representationsNEWLINENEWLINEmake_entry(ID("411f3b"),NEWLINE Formula(Equal(StieltjesGamma(n, a), SequenceLimit(Brackets(Parentheses(Sum(Log(k+a)**n / (k+a), For(k, 0, N))) - Log(N+a)**(n+1)/(n+1)), For(N, Infinity)))),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Specific valuesNEWLINENEWLINEmake_entry(ID("51206a"),NEWLINE Formula(Equal(StieltjesGamma(n, 1), StieltjesGamma(n))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(0))))NEWLINENEWLINEmake_entry(ID("8ae153"),NEWLINE Formula(Equal(StieltjesGamma(0, 1), StieltjesGamma(0), ConstGamma)))NEWLINENEWLINEmake_entry(ID("b6808d"),NEWLINE Formula(Equal(StieltjesGamma(0, a), -DigammaFunction(a))),NEWLINE Variables(a),NEWLINE Assumptions(And(Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINEmake_entry(ID("70a705"),NEWLINE Formula(Equal(StieltjesGamma(1, Div(1,2)), StieltjesGamma(1) - 2*ConstGamma*Log(2) - Log(2)**2)))NEWLINENEWLINEmake_entry(ID("e5bd3c"),NEWLINE Description("Table of", StieltjesGamma(n), "to 50 digits for", LessEqual(0, n, 30)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(StieltjesGamma(n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("0.57721566490153286060651209008240243104215933593992")),NEWLINE Tuple(1, Decimal("-0.072815845483676724860586375874901319137736338334338")),NEWLINE Tuple(2, Decimal("-0.0096903631928723184845303860352125293590658061013407")),NEWLINE Tuple(3, Decimal("0.0020538344203033458661600465427533842857158044454106")),NEWLINE Tuple(4, Decimal("0.0023253700654673000574681701775260680009044694137849")),NEWLINE Tuple(5, Decimal("0.00079332381730106270175333487744444483073153940458489")),NEWLINE Tuple(6, Decimal("-0.00023876934543019960987242184190800427778371515635808")),NEWLINE Tuple(7, Decimal("-0.00052728956705775104607409750547885828199625347296990")),NEWLINE Tuple(8, Decimal("-0.00035212335380303950960205216500120874172918053379235")),NEWLINE Tuple(9, Decimal("-3.4394774418088048177914623798227390620789538594442e-5")),NEWLINE Tuple(10, Decimal("0.00020533281490906479468372228923706530295985377416676")),NEWLINE Tuple(11, Decimal("0.00027018443954390352667290208206795567382784205868840")),NEWLINE Tuple(12, Decimal("0.00016727291210514019335350154334118344660780663280557")),NEWLINE Tuple(13, Decimal("-2.7463806603760158860007603693355181526785337670396e-5")),NEWLINE Tuple(14, Decimal("-0.00020920926205929994583713969734458495783154421150607")),NEWLINE Tuple(15, Decimal("-0.00028346865532024144664293447499712697706870298071768")),NEWLINE Tuple(16, Decimal("-0.00019969685830896977470778456320324039191576497403406")),NEWLINE Tuple(17, Decimal("2.6277037109918336699466597630510122816078692929114e-5")),NEWLINE Tuple(18, Decimal("0.00030736840814925282659275475194862564552381129073146")),NEWLINE Tuple(19, Decimal("0.00050360545304735562905559643771716003532126980764950")),NEWLINE Tuple(20, Decimal("0.00046634356151155944940059482443355052511314347392569")),NEWLINE Tuple(21, Decimal("0.00010443776975600011581079567436772049104442825070555")),NEWLINE Tuple(22, Decimal("-0.00054159958220399770165519617317410558454386092870075")),NEWLINE Tuple(23, Decimal("-0.0012439620904082457792997415995371658091470281139646")),NEWLINE Tuple(24, Decimal("-0.0015885112789035615619061966115211158573187228221441")),NEWLINE Tuple(25, Decimal("-0.0010745919527384888247242919873531730892739793314532")),NEWLINE Tuple(26, Decimal("0.00065680351863715443150477300335621524888606506047754")),NEWLINE Tuple(27, Decimal("0.0034778369136185382090073595742588115476629156638859")),NEWLINE Tuple(28, Decimal("0.0064000685317006294581072282219458636666371981445885")),NEWLINE Tuple(29, Decimal("0.0073711517704722391344124024235594021578413274885128")),NEWLINE Tuple(30, Decimal("0.0035577288555731609479135377489084026108096506495221")),NEWLINE )))NEWLINENEWLINEmake_entry(ID("569d5c"),NEWLINE Description("Table of", StieltjesGamma(10**n), "to 50 digits for", LessEqual(0, n, 20)),NEWLINE Table(NEWLINE Var(n),NEWLINE TableValueHeadings(n, NearestDecimal(StieltjesGamma(10**n), 50)),NEWLINE TableSplit(1),NEWLINE List(NEWLINE Tuple(0, Decimal("-0.072815845483676724860586375874901319137736338334338")),NEWLINE Tuple(1, Decimal("0.00020533281490906479468372228923706530295985377416676")),NEWLINE Tuple(2, Decimal("-425340157170802696.23144385197278358247028931053473")),NEWLINE Tuple(3, Decimal("-1.5709538442047449345494023425120825242380299554570e+486")),NEWLINE Tuple(4, Decimal("-2.2104970567221060862971082857536501900234397174729e+6883")),NEWLINE Tuple(5, Decimal("1.9919273063125410956582272431568589205211659777533e+83432")),NEWLINE Tuple(6, Decimal("-4.4209504730980210273285480902514758066667150603243e+947352")),NEWLINE Tuple(7, Decimal("-2.7882974834697458134414289662704891120456603986498e+10390401")),NEWLINE Tuple(8, Decimal("2.7324629454457814909592178706122081982218137653871e+111591574")),NEWLINE Tuple(9, Decimal("2.1048416655418517821363600001419516191053973500980e+1181965380")),NEWLINE Tuple(10, Decimal("7.5883621237131051948224033799125486921750410324510e+12397849705")),NEWLINE Tuple(11, Decimal("3.4076163168007069203916546697422088077748515862016e+129115149508")),NEWLINE Tuple(12, Decimal("-1.1713923594956898094830946178584108308869819425684e+1337330792656")),NEWLINE Tuple(13, Decimal("5.1442844004429501778205029347495102582243127602569e+13792544216233")),NEWLINE Tuple(14, Decimal("-5.8565687699062182176274937548885177768345135170181e+141762672271719")),NEWLINE Tuple(15, Decimal("1.8441017255847322907032695598351364885675746553316e+1452992510427658")),NEWLINE Tuple(16, Decimal("1.0887949866822670316936532894122644696901837098117e+14857814744168222")),NEWLINE Tuple(17, Decimal("-9.0932573236841531922129808939176217547651121139948e+151633823511792145")),NEWLINE Tuple(18, Decimal("2.6314370018873515830151010192294307578971415626833e+1544943249673388947")),NEWLINE Tuple(19, Decimal("4.8807917914447513336887536981308809263719031557975e+15718277029330950920")),NEWLINE Tuple(20, Decimal("2.3945266166432844875810628102042011083015231233149e+159718433793014252763")),NEWLINE )))NEWLINENEWLINE# Recurrence relationsNEWLINENEWLINEmake_entry(ID("687b4d"),NEWLINE Formula(Equal(StieltjesGamma(n, a+1), StieltjesGamma(n, a) - Log(a)**n / a)),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), NotElement(a, ZZLessEqual(0)))))NEWLINENEWLINE# Integral representationsNEWLINENEWLINEmake_entry(ID("a41c92"),NEWLINE Formula(Equal(StieltjesGamma(n, a), -((Pi/(2*(n+1))) * Integral((Log(a-Div(1,2)+ConstI*x)**(n+1) + Log(a-Div(1,2)-ConstI*x)**(n+1))/Cosh(Pi*x)**2, For(x, 0, Infinity))))),NEWLINE Variables(n, a),NEWLINE Assumptions(And(Element(n, ZZGreaterEqual(0)), Element(a, CC), Greater(Re(a), Div(1,2)))))NEWLINENEWLINE# Bounds and inequalitiesNEWLINENEWLINEmake_entry(ID("1dec0d"),NEWLINE Formula(Less(Abs(StieltjesGamma(n)), Pow(10,-4) * Exp(n*Log(Log(n))))),NEWLINE Variables(n),NEWLINE Assumptions(Element(n, ZZGreaterEqual(5))))NEWLINENEWLINE
from .extractor import DateExtractor, ExtractedData, ExtractorExceptionNEWLINENEWLINENEWLINEclass AmazonPrimeExtractorException(ExtractorException):NEWLINENEWLINE def __init__(self, *args, **kwargs):NEWLINE ExtractorException.__init__(self, *args, **kwargs)NEWLINENEWLINENEWLINEclass AmazonPrimeDateExtractor(DateExtractor):NEWLINENEWLINE EXCEPTION = AmazonPrimeExtractorExceptionNEWLINE MATCH_TEXT = 'www.chase.com/amazon'NEWLINE PRE_DATE_TEXT = 'Opening/Closing Date'NEWLINE POST_DATE_TEXT = 'Credit Access Line'NEWLINE FILE_FORMAT = '{}-{:02} AmazonPrime Statement.pdf'NEWLINE DATE_FORMAT = '%m/%d/%y'NEWLINE SPLIT_TEXT = ' - 'NEWLINENEWLINE @staticmethodNEWLINE def match(text):NEWLINE return (__class__.MATCH_TEXT in text)NEWLINENEWLINE def extract(self, text):NEWLINE return self._pre_post_split_extraction_(text)NEWLINE
# Copyright (c) ZenML GmbH 2021. All Rights Reserved.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License at:NEWLINE#NEWLINE# https://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressNEWLINE# or implied. See the License for the specific language governingNEWLINE# permissions and limitations under the License.NEWLINENEWLINEimport platformNEWLINEfrom contextlib import ExitStack as does_not_raiseNEWLINENEWLINEfrom zenml.constants import VALID_OPERATING_SYSTEMSNEWLINEfrom zenml.utils.analytics_utils import (NEWLINE EVENT_TEST,NEWLINE OPT_IN_ANALYTICS,NEWLINE OPT_OUT_ANALYTICS,NEWLINE get_segment_key,NEWLINE get_system_info,NEWLINE track_event,NEWLINE)NEWLINENEWLINENEWLINEdef test_get_segment_key():NEWLINE """Checks the get_segment_key method returns a value"""NEWLINE with does_not_raise():NEWLINE get_segment_key()NEWLINENEWLINENEWLINEdef test_get_system_info_type():NEWLINE """Checks that the return value is a dictionary"""NEWLINE assert isinstance(get_system_info(), dict)NEWLINENEWLINENEWLINEdef test_platform_info_correctness():NEWLINE """Checks that the method returns the correct platform"""NEWLINE system_id = platform.system()NEWLINENEWLINE if system_id == "Darwin":NEWLINE system_id = "mac"NEWLINE elif system_id not in VALID_OPERATING_SYSTEMS:NEWLINE system_id = "unknown"NEWLINENEWLINE system_info = get_system_info()NEWLINE assert system_id.lower() == system_info["os"]NEWLINENEWLINENEWLINEdef test_track_event_conditions():NEWLINE """It should return true for the analytics events but false for everythingNEWLINE else."""NEWLINE assert track_event(OPT_OUT_ANALYTICS)NEWLINE assert track_event(OPT_IN_ANALYTICS)NEWLINE assert not track_event(EVENT_TEST)NEWLINE
# Functions to load ODELAY generated MATFILESNEWLINENEWLINE# Internal LibrariesNEWLINEimport clickNEWLINEimport csvNEWLINEfrom datetime import datetimeNEWLINEimport jsonNEWLINEimport osNEWLINEimport pathlibNEWLINEimport reNEWLINEimport sysNEWLINEimport timeNEWLINENEWLINE# External LibrariesNEWLINEimport cv2NEWLINEfrom fast_histogram import histogram1dNEWLINEimport h5pyNEWLINEimport scipy.io as sioNEWLINEimport matplotlib.pyplot as pltNEWLINEimport numpy as npNEWLINEimport pandas as pdNEWLINENEWLINEimport tools.imagepl as oplNEWLINEimport tools.odelayplot as odpNEWLINEfrom PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QFileDialogNEWLINEfrom PyQt5.QtCore import QDirNEWLINENEWLINEdef getStrings(str_array):NEWLINE '''Make a str_array into character list'''NEWLINENEWLINE return ''.join(chr(c) for c in str_array)NEWLINENEWLINEdef getHDF5str(str_array):NEWLINE '''Generate a string array from individual bchar values'''NEWLINENEWLINE return ''.join(c.astype(str) for c in str_array.squeeze())NEWLINENEWLINEdef _mat_check_keys(d):NEWLINE '''NEWLINE checks if entries in dictionary are mat-objects. If yesNEWLINE todict is called to change them to nested dictionariesNEWLINE '''NEWLINE for key in d:NEWLINE if isinstance(d[key], sio.matlab.mio5_params.mat_struct):NEWLINE d[key] = _mattodict(d[key])NEWLINE return dNEWLINENEWLINEdef _mattodict(matobj):NEWLINE '''NEWLINE A recursive function which constructs from matobjects nested dictionariesNEWLINE '''NEWLINE d = {}NEWLINE for strg in matobj._fieldnames:NEWLINE elem = matobj.__dict__[strg]NEWLINE if isinstance(elem, sio.matlab.mio5_params.mat_struct):NEWLINE d[strg] = _mattodict(elem)NEWLINE NEWLINE else:NEWLINE d[strg] = elemNEWLINE return dNEWLINENEWLINEdef _mattolist(ndarray):NEWLINE '''NEWLINE A recursive function which constructs lists from cellarraysNEWLINE (which are loaded as numpy ndarrays), recursing into the elementsNEWLINE if they contain matobjects.NEWLINE '''NEWLINE elem_list = []NEWLINE for sub_elem in ndarray:NEWLINE if isinstance(sub_elem, sio.matlab.mio5_params.mat_struct):NEWLINE elem_list.append(_mattodict(sub_elem))NEWLINE elif isinstance(sub_elem, np.ndarray):NEWLINE elem_list.append(_mattolist(sub_elem))NEWLINE else:NEWLINE elem_list.append(sub_elem)NEWLINE return elem_listNEWLINENEWLINEdef _mat_parseData(group_Obj, hd5_file):NEWLINE '''NEWLINE Matlab -v7.3 data parser. If the data is a object then it could be a cell array or a nested structure.NEWLINE '''NEWLINE group_Attrs = dir(group_Obj)NEWLINE attrs_Keys = [key for key in group_Obj.attrs.keys()]NEWLINE numeric_list = ['double', 'uint8','uint16','logical','int8', 'int16']NEWLINENEWLINE if 'dtype' in group_Attrs:NEWLINE # First test for Objects if the object reference NEWLINE if group_Obj.dtype == 'object':NEWLINE data = _matcell_todict(group_Obj,hd5_file)NEWLINENEWLINE elif 'MATLAB_class' in attrs_Keys:NEWLINE # Luckily they put the MATLAB_class in attributes so that can define the data type as numeric char or cellsNEWLINE group_attrs = group_Obj.attrs['MATLAB_class'].decode('utf-8')NEWLINE data = []NEWLINENEWLINE if group_attrs in numeric_list:NEWLINE data.append(np.array(group_Obj, dtype = group_Obj.dtype).squeeze())NEWLINENEWLINE elif group_attrs == 'char':NEWLINE data.append(getStrings(group_Obj))NEWLINE NEWLINE elif group_attrs == 'cell':NEWLINE del dataNEWLINE data = {}NEWLINE data = _matcell_todict(group_Obj, hd5_file) NEWLINE NEWLINE return dataNEWLINENEWLINEdef _mat_hd5ToDict(group_Obj, hd5_file):NEWLINE '''NEWLINE Import MATLAB hd5f files from MATLAB -v7.3. This will parse the data into nested python dictionaries NEWLINE '''NEWLINE group_Dict = {}NEWLINE for name, elem in group_Obj.items():NEWLINE # Iterate through items and check if they are groups or datasetsNEWLINE NEWLINE if type(elem) is h5py.Group:NEWLINE group_Dict[name] = _mat_hd5ToDict(elem, hd5_file)NEWLINE NEWLINE elif type(elem) is h5py.Dataset:NEWLINE group_Dict[name] = _mat_parseData(elem, hd5_file)NEWLINENEWLINE return group_DictNEWLINENEWLINEdef _matcell_todict(group_Obj,hd5_file):NEWLINENEWLINE objShape = group_Obj.shapeNEWLINENEWLINE if (objShape[0] == 1 or objShape[1] == 1):NEWLINE data= []NEWLINE for objRef in group_Obj:NEWLINE for ref_elem in objRef:NEWLINE if hd5_file[ref_elem].dtype == 'object':NEWLINE data.append(_matcell_todict(hd5_file[ref_elem], hd5_file))NEWLINE else:NEWLINE data.append(_mat_parseData(hd5_file[ref_elem], hd5_file))NEWLINENEWLINE else:NEWLINE data = {}NEWLINE for row in range(objShape[1]):NEWLINE name = getStrings(hd5_file[group_Obj[0][row]])NEWLINE str_array = []NEWLINE NEWLINE for col in range(1,objShape[0]):NEWLINE str_array.append(getStrings(hd5_file[group_Obj[col][row]]))NEWLINE NEWLINE data[name] = str_arrayNEWLINENEWLINE return dataNEWLINENEWLINEdef _decomment(csvfile):NEWLINE for row in csvfile:NEWLINE raw = row.split('#')[0].strip()NEWLINE if raw: yield rawNEWLINENEWLINEdef _saveDict(dic, hdf5Obj):NEWLINE """NEWLINE Recursively save a python dictionary to a HDF5 file. NEWLINE input: dic - is the dictionary to saveNEWLINE hdf5Obj - is the current hdf5 group or file handle to save the data to. NEWLINE """NEWLINE for key, item in dic.items():NEWLINENEWLINE NEWLINE if isinstance(item, (np.ndarray, np.int32, np.uint16, np.int64, np.float64)):NEWLINENEWLINE hdf5Obj.create_dataset(key, data = item)NEWLINENEWLINE elif isinstance(item, (bytes, bool, int, float)):NEWLINENEWLINE hdf5Obj.create_dataset(key, data = np.array(item, dtype=type(item)))NEWLINENEWLINENEWLINE elif isinstance(item, str):NEWLINE # breakpoint()NEWLINE asciiList = [el.encode("ascii", "ignore") for el in item]NEWLINE hdf5Obj.create_dataset(key, (len(asciiList),1),'S10', asciiList)NEWLINENEWLINE elif isinstance(item, dict):NEWLINE # if the item is a dictionary, create a new hdf5 group and then recursively continueNEWLINE grpObj = hdf5Obj.create_group(key)NEWLINE _saveDict(item, grpObj)NEWLINENEWLINE else:NEWLINE raise ValueError('Cannot save %s of %s type' %(key,type(item)))NEWLINENEWLINEdef _getHDF5Data(hdf5Obj):NEWLINE """NEWLINE Recursively load data from HDF5 file. NEWLINE """NEWLINE d = {}NEWLINE for key, item in hdf5Obj.items():NEWLINE NEWLINE if isinstance(item, h5py.Dataset):NEWLINE if item.dtype == 'S10':NEWLINE d[key] = getHDF5str(item[()])NEWLINE else: NEWLINE NEWLINE d[key] = item[()]NEWLINE NEWLINE elif isinstance(item, h5py.Group):NEWLINE d[key] = _getHDF5Data(item)NEWLINENEWLINE return dNEWLINENEWLINEdef loadmatlab(filename):NEWLINE '''NEWLINE loadmat opens MATLAB® formatted binary file (MAT-file) NEWLINE loadmat should be called instead of direct sio.loadmat because it recoveres NEWLINE python dictionaries from mat files. It calls the function _check_keys to curate all entriesNEWLINE which are still mat-objectsNEWLINE '''NEWLINE data = sio.loadmat(filename, struct_as_record=False, squeeze_me=True, verify_compressed_data_integrity=False)NEWLINE return _mat_check_keys(data)NEWLINENEWLINEdef math5py(filename):NEWLINE '''NEWLINE Load HDF5 saved file in ODELAY. Not all files are this type so it tends NEWLINE to be problematicNEWLINE '''NEWLINE f = h5py.File(filename,'r') NEWLINE d = _mat_hd5ToDict(f,f)NEWLINE f.close()NEWLINE return dNEWLINENEWLINEdef saveDict(fileName, saveDic):NEWLINENEWLINE with h5py.File(fileName,'w') as hdf5Obj:NEWLINE _saveDict(saveDic, hdf5Obj)NEWLINENEWLINEdef saveROI(fileLocation, roiDict):NEWLINE '''Steps to save a file:NEWLINE 1. Save HFD5 file from entered dictionaryNEWLINE '''NEWLINE filePath = pathlib.Path(fileLocation) NEWLINE if 'roiLabel' in roiDict.keys():NEWLINENEWLINE fileName = filePath /(roiDict['roiLabel'] +'.hdf5')NEWLINENEWLINE with h5py.File(fileName,'w') as hdf5Obj:NEWLINE _saveDict(roiDict, hdf5Obj)NEWLINE NEWLINE return NoneNEWLINENEWLINEdef loadData(filename):NEWLINE """NEWLINE Load data from HDF5 file into a python DictionaryNEWLINE This function will attempt to load MATLAB *.mat files based on thier NEWLINE file names.NEWLINE There maybe problems with the dictionary returned in that it may need NEWLINE to be squeezed.NEWLINE """NEWLINE d = {}NEWLINENEWLINE if '.mat' in filename.name:NEWLINE NEWLINE try:NEWLINE d = math5py(filename) NEWLINE except:NEWLINE d = loadmatlab(filename)NEWLINENEWLINE elif '.hdf5' in filename.name:NEWLINE with h5py.File(filename, 'r') as hdf5Obj:NEWLINE d = _getHDF5Data(hdf5Obj)NEWLINE NEWLINE return dNEWLINENEWLINEdef summarizeMatLabExp(dataPath, saveSwitch):NEWLINE expDict = {}NEWLINE if isinstance(dataPath, str):NEWLINE dataPath = pathlib.Path(dataPath)NEWLINE else:NEWLINE dataPath = dataPathNEWLINE NEWLINE checkPath = dataPath / 'ODELAY Well Data'NEWLINE NEWLINE expIndexPath = list(dataPath.glob('*Index_ODELAYData.mat'))NEWLINE NEWLINE if pathlib.Path.exists(checkPath):NEWLINE expData = loadData(expIndexPath[0])NEWLINE NEWLINE expName = expData['ExperimentName'][0]NEWLINE savePath = dataPath /f'{expName} summary.hdf5'NEWLINENEWLINE fileList = sorted(checkPath.glob('*.mat'))NEWLINE NEWLINE expDict = {}NEWLINE with click.progressbar(fileList) as fileBar:NEWLINE for dataFile in fileBar:NEWLINENEWLINE roiData = loadData(dataFile)NEWLINENEWLINE roi = roiData['WellDataTemp']['WellID']NEWLINE if 'FitDataGompDT' in list(roiData['Tracks2Temp']['ObjectInfo'].keys()):NEWLINE fitDataKey = 'FitDataGompDT'NEWLINE colList = ['a', 'b', 't-lag', 'dT', 'fssq', 'Tlag', 'Td', 'Tex', 'ATex', 'Aplateau', 'TdFlag', 'TexFlag', 'TVmax', 'Tplat','exitflag','fssq per obs','empty']NEWLINE fitDataCols = {colList[val] : val for val in range(len(colList))}NEWLINE NEWLINE elif 'FitDataGomp' in list(roiData['Tracks2Temp']['ObjectInfo'].keys()):NEWLINE fitDataKey = 'FitDataGomp'NEWLINE colList = ['a', 'b', 'vmax', 't-lag', 'fssq', 'Tlag', 'Td', 'Tex', 'ATex', 'Aplateau', 'TdFlag', 'TexFlag', 'TVmax', 'Tplat','exitflag','fssq per obs','empty']NEWLINE fitDataCols = {colList[val] : val for val in range(len(colList))}NEWLINENEWLINE elif 'FitData' in list(roiData['Tracks2Temp']['ObjectInfo'].keys()):NEWLINE fitDataKey = 'FitData'NEWLINE colList = ['a', 'b', 'c', 'd', 'fssq', 'Tlag', 'Td', 'Tex', 'ATex', 'Aplateau', 'TdFlag', 'TexFlag', 'TVmax', 'Tplat','exitflag','fssq per obs','empty']NEWLINE fitDataCols = {colList[val] : val for val in range(len(colList))}NEWLINENEWLINE NEWLINE NEWLINE rc = roiData['Tracks2Temp']['ObjectInfo'][fitDataKey].shapeNEWLINE NEWLINE idVec = np.arange(rc[0], dtype = 'uint32')NEWLINE inds = ~np.isnan(roiData['Tracks2Temp']['ObjectInfo'][fitDataKey][:,1])NEWLINE NEWLINE roiDict = {}NEWLINE try:NEWLINE roiDict['fitDataCols']= fitDataColsNEWLINE roiDict['objectArea'] = roiData['Tracks2Temp']['ObjectInfo']['ObjectArea'][inds,:]NEWLINE roiDict['timePoints'] = roiData['Tracks2Temp']['ObjectInfo']['TimePoints']NEWLINE roiDict['fitData'] = roiData['Tracks2Temp']['ObjectInfo'][fitDataKey][inds,:]NEWLINE roiDict['objID'] = idVec[inds]NEWLINE except IndexError:NEWLINE roiDict['fitDataCols']= fitDataColsNEWLINE roiDict['objectArea'] = roiData['Tracks2Temp']['ObjectInfo']['ObjectArea']NEWLINE roiDict['timePoints'] = roiData['Tracks2Temp']['ObjectInfo']['TimePoints']NEWLINE roiDict['fitData'] = roiData['Tracks2Temp']['ObjectInfo'][fitDataKey]NEWLINE roiDict['objID'] = idVecNEWLINE NEWLINENEWLINE roiDict['roi'] = roiNEWLINE roiDict['roiInfo'] = {}NEWLINE NEWLINE expDict[roi] = roiDictNEWLINENEWLINE spotlayoutPath = [*dataPath.glob('*ODELAYExpDisc.xlsx')]NEWLINE if len(spotlayoutPath)==1:NEWLINE NEWLINE strainID = pd.read_excel(spotlayoutPath[0], sheet_name='Sheet1', header=29, usecols="B:J").set_index('ODELAY Well')NEWLINE columnID = 'Strain ID'NEWLINE strainInfo1 = 'Plot Name'NEWLINE strainInfo2 = 'Misc1'NEWLINE NEWLINE for roi in expDict.keys():NEWLINE NEWLINE expDict[roi]['roiInfo'][columnID] = f'{strainID.loc[roi][columnID]}-{strainID.loc[roi][strainInfo1]}-{strainID.loc[roi][strainInfo2]}-{roi}'NEWLINENEWLINE NEWLINE if saveSwitch:NEWLINE saveDict(savePath, expDict)NEWLINENEWLINE else:NEWLINE print('Could Not Find ODELAY Data Folder')NEWLINENEWLINE return expDictNEWLINENEWLINEdef summarizeExp(dataPath, saveSwitch):NEWLINENEWLINE if isinstance(dataPath, str):NEWLINE dataPath = pathlib.Path(dataPath)NEWLINE else:NEWLINE dataPath = dataPathNEWLINENEWLINE indexList = [k for k in dataPath.glob('*Index_ODELAYData.*')]NEWLINE if len(indexList)==1:NEWLINE expIndexPath = dataPath / indexList[0]NEWLINE else:NEWLINE print('Could not find the correct index file or there were more than one in the diretory')NEWLINENEWLINE expData = loadData(expIndexPath)NEWLINENEWLINE expName = expData['experiment_name']NEWLINE savePath = dataPath /f'{expName} summary.hdf5'NEWLINENEWLINE roiList = list(expData['roiFiles'].keys())NEWLINE roiList.sort()NEWLINENEWLINE # generate nested dictionary of FitData, ObjectArea, and TimePointsNEWLINE expDict = {}NEWLINE with click.progressbar(roiList) as roiBar:NEWLINE for roi in roiBar:NEWLINE roiPath = dataPath / 'ODELAY Roi Data' / f'{roi}.hdf5'NEWLINE if roiPath.exists():NEWLINE roiData = loadData(roiPath)NEWLINE rc = roiData['fitData'].shapeNEWLINE idVec = np.arange(rc[0], dtype = 'uint32')NEWLINE inds = roiData['fitData'][:,0]>0NEWLINE roiDict = {}NEWLINE roiDict['fitDataCols']= roiData['fitDataCols']NEWLINE roiDict['fitData'] = roiData['fitData'][inds,:]NEWLINE roiDict['objectArea'] = roiData['objectArea'][inds,:]NEWLINE roiDict['timePoints'] = roiData['timePoints']NEWLINE roiDict['objID'] = idVec[inds]NEWLINE roiDict['roi'] = roiNEWLINE roiDict['roiInfo'] = {}NEWLINENEWLINE expDict[roi] = roiDictNEWLINENEWLINENEWLINE spotlayoutPath = [*dataPath.glob('*Spot-Layout.xlsx')]NEWLINE NEWLINE if len(spotlayoutPath)==1:NEWLINE columnID = 'Strain ID'NEWLINE strainID = pd.read_excel(spotlayoutPath[0], sheet_name='Sheet1', header=0, usecols="A:L").set_index('ROI')NEWLINE columnList = ['Strain ID','Strain Info 1','Strain Info 2' ]NEWLINE for roi in expDict.keys():NEWLINENEWLINE strainInfo = ' '.join(str(strainID.loc[roi][colID]) for colID in columnList) + ' ' + roiNEWLINE expDict[roi]['roiInfo'][columnID] = strainInfoNEWLINE NEWLINE if saveSwitch:NEWLINE saveDict(savePath, expDict)NEWLINENEWLINE return expDictNEWLINENEWLINEdef exportcsv(dataPath, roiList=None):NEWLINE ''' Export csv files of object area and fit data. All data is exported including non-fit data.'''NEWLINE # TODO: Add ability to filter data and export data label vectors.NEWLINE # TODO: Add ability to look for summary data to shorten export timNEWLINENEWLINE dateString = datetime.today().strftime("%Y-%m-%d")NEWLINE directoryName = f'{dateString}_csvOut'NEWLINENEWLINE saveLocation = dataPath / directoryNameNEWLINE if not saveLocation.exists():NEWLINE saveLocation.mkdir()NEWLINE NEWLINE summaryList = list(dataPath.glob('*summary.hdf5'))NEWLINE NEWLINE if len(summaryList)==1:NEWLINE expDict = loadData(summaryList[0])NEWLINE print('summary loaded')NEWLINENEWLINE for roi in expDict.keys():NEWLINE roiData = expDict[roi]NEWLINE NEWLINE rc = roiData['fitData'].shapeNEWLINE idVec = np.arange(rc[0], dtype = 'uint32')NEWLINE inds = roiData['fitData'][:,0]>0NEWLINENEWLINE timePoints = roiData['timePoints']NEWLINE objectArea = roiData['objectArea'][inds,:]NEWLINE NEWLINE fitDataCols = roiData['fitDataCols']NEWLINE fitDataHeader = [key for key, value in sorted(fitDataCols.items(), key=lambda item: item[1])]NEWLINENEWLINE fitData = roiData['fitData'][inds,:len(fitDataHeader)]NEWLINENEWLINE fitDataFrame = pd.DataFrame(fitData, columns = fitDataHeader)NEWLINE objAreaFrame = pd.DataFrame(objectArea, columns = timePoints)NEWLINE fitDataFrame['object ID'] = roiData['objID']NEWLINE NEWLINE NEWLINE objArea_csv_Path = saveLocation / f'{roi}-objectArea.csv'NEWLINE fitData_csv_Path = saveLocation / f'{roi}-FitData.csv'NEWLINENEWLINE fitDataFrame.to_csv(fitData_csv_Path, index = None, header=True)NEWLINE objAreaFrame.to_csv(objArea_csv_Path, index = None, header=True)NEWLINE NEWLINE else:NEWLINE for roi in roiList:NEWLINE roiPath = dataPath / 'ODELAY Roi Data' / f'{roi}.hdf5'NEWLINE if roiPath.exists():NEWLINE roiData = loadData(roiPath)NEWLINENEWLINE rc = roiData['fitData'].shapeNEWLINE idVec = np.arange(rc[0], dtype = 'uint32')NEWLINE inds = roiData['fitData'][:,0]>0NEWLINENEWLINE timePoints = roiData['timePoints']NEWLINE objectArea = roiData['objectArea'][inds,:]NEWLINE fitData = roiData['fitData'][inds,0:15]NEWLINE fitDataCols = roiData['fitDataCols']NEWLINE fitDataHeader = [key for key, value in sorted(fitDataCols.items(), key=lambda item: item[1])]NEWLINE NEWLINE fitDataFrame = pd.DataFrame(fitData, columns = fitDataHeader)NEWLINE objAreaFrame = pd.DataFrame(objectArea, columns = timePoints)NEWLINE fitDataFrame['object ID'] = idVec[inds]NEWLINE objAreaFrame['object ID'] = idVec[inds]NEWLINENEWLINE objArea_csv_Path = saveLocation / f'{roi}-objectArea.csv'NEWLINE fitData_csv_Path = saveLocation / f'{roi}-FitData.csv'NEWLINENEWLINE fitDataFrame.to_csv(fitData_csv_Path, index = None, header=True)NEWLINE objAreaFrame.to_csv(objArea_csv_Path, index = None, header=True)NEWLINE else:NEWLINE print(f"{roi} did not process as its data file doesn't exist")NEWLINENEWLINE return NoneNEWLINENEWLINEdef exportavi( imagepath, datapath, roi, objID = None):NEWLINENEWLINE '''Write XVID encoded *.avi movie for timecourse images.'''NEWLINENEWLINENEWLINE dataPath = pathlib.Path(datapath)NEWLINE imagePath = pathlib.Path(imagepath)NEWLINENEWLINE directoryName = 'ODELAY Roi AVI'NEWLINENEWLINE saveLocation = dataPath / directoryNameNEWLINE if not saveLocation.exists():NEWLINE pathlib.Path.mkdir(saveLocation)NEWLINE # '''Write an AVI file that shows the ROI over time'''NEWLINE # TODO: figure out way to zoom in on colony area, add time code, and scale barNEWLINENEWLINE indexList = [k for k in dataPath.glob('*Index_ODELAYData.*')]NEWLINE if len(indexList)==1:NEWLINE expIndexPath = dataPath / indexList[0]NEWLINE else:NEWLINE print('Could not find the correct index file or there were more than one in the diretory')NEWLINENEWLINE expIndex = loadData(expIndexPath)NEWLINENEWLINE roiPath = dataPath / 'ODELAY Roi Data' / f'{roi}.hdf5'NEWLINE roiData = loadData(roiPath)NEWLINENEWLINE imageList = list(expIndex['roiFiles'][roi].keys())NEWLINE imageList.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])NEWLINE numImage = len(imageList)NEWLINE # Determin size of stitched imageNEWLINENEWLINE stitchDim = np.zeros((numImage,2), dtype = 'float')NEWLINE magnification = expIndex['magnification']NEWLINE pixSize = expIndex['pixSize']NEWLINE background = expIndex['backgroundImage']NEWLINENEWLINE for ai in roiData['stitchMeta'].keys():NEWLINE stitchDim[int(ai),:] = roiData['stitchMeta'][ai]['stitchDim']NEWLINENEWLINE vidDim = np.median(stitchDim,0).astype('uint')NEWLINE NEWLINE fps = 10.0NEWLINENEWLINE vidFileName = str(saveLocation / f'{roi}.avi')NEWLINENEWLINE fcc = cv2.VideoWriter_fourcc(*'XVID')NEWLINENEWLINE aviOut = cv2.VideoWriter(vidFileName,fcc, fps, (vidDim[1],vidDim[0]),1)NEWLINE imInd = 0NEWLINE NEWLINE NEWLINE for im in imageList:NEWLINENEWLINE # load imageNEWLINE # rectify umageDimsNEWLINE # Adjust Contrast to uint8NEWLINE # write frame in aviNEWLINE roiKey = f'{imInd:03d}'NEWLINE imPix = roiData['stitchMeta'][roiKey]['imPix']NEWLINE imageFilePath = imagePath / roi / imNEWLINE rawImage = opl.assembleImage(imageFilePath, pixSize, magnification, background, imPix)NEWLINENEWLINE # Generate histogram of the loaded imageNEWLINE imageHist = histogram1d(rawImage['Bf'].ravel(),2**16,[0,2**16],weights = None).astype('float')NEWLINE # Calculate the cumulative probability ignoring zero values NEWLINE cumHist = np.cumsum(imageHist)NEWLINE cumProb = (cumHist-cumHist[0])/(cumHist[2**16-1]-cumHist[0])NEWLINE # set low and high values ot normalize image contrast. NEWLINE loval = np.argmax(cumProb>0.00001)NEWLINE hival = np.argmax(cumProb>=0.9995)NEWLINENEWLINE rc = np.min((stitchDim[imInd,:],vidDim),axis=0).astype('int')NEWLINE adjIm = np.zeros((vidDim[0],vidDim[1]), dtype = 'float')NEWLINE adjIm[:rc[0],:rc[1]] = (rawImage['Bf'][:rc[0],:rc[1]].astype('float') - loval.astype('float'))/(hival.astype('float') - loval.astype('float'))*254NEWLINE lim = np.iinfo('uint8')NEWLINE scIm = np.clip(adjIm, lim.min, lim.max) NEWLINENEWLINE vidIm = np.stack([scIm, scIm, scIm], axis=2).astype('uint8')NEWLINENEWLINE aviOut.write(vidIm)NEWLINE imInd +=1NEWLINE NEWLINE NEWLINE aviOut.release()NEWLINE NEWLINENEWLINE NEWLINE return NoneNEWLINENEWLINEdef exporttiffs(imagepath, datapath, roi, objID = None):NEWLINE '''NEWLINE Data from Experiment Dictionary or ObjectNEWLINE '''NEWLINE if isinstance(imagepath, str):NEWLINE imagePath = pathlib.Path(imagepath)NEWLINE else:NEWLINE imagePath = imagepathNEWLINENEWLINE if isinstance(datapath, str):NEWLINE dataPath = pathlib.Path(datapath)NEWLINE else:NEWLINE dataPath = datapathNEWLINENEWLINE indexList = [*dataPath.glob('*Index_ODELAYData.*')]NEWLINENEWLINE if len(indexList)==1:NEWLINE expIndexPath = dataPath / indexList[0]NEWLINE else:NEWLINE print('Could not find the correct index file or there were more than one in the diretory')NEWLINENEWLINE expData = loadData(expIndexPath)NEWLINE #####################################NEWLINE # Load Dictionary variables There has to be a way to dynamically add theseNEWLINE #####################################NEWLINE background = expData['backgroundImage']NEWLINE numTimePoints = expData['numTimePoints'] # number of timepontsNEWLINE pixSize = expData['pixSize']NEWLINE magnification = expData['magnification']NEWLINE roiFiles = expData['roiFiles']NEWLINE odelayDataPath = dataPath / 'ODELAY Roi Data'NEWLINENEWLINE # Else this will crashNEWLINE NEWLINE roiList = [*roiFiles]NEWLINENEWLINE tiffPath = dataPath / 'ODELAY Tiff Images'NEWLINE if not tiffPath.exists():NEWLINE tiffPath.mkdir()NEWLINE NEWLINE if roi in roiList:NEWLINE roiPath = imagePath / roiNEWLINE fileList = os.listdir(roiPath)NEWLINE imageFileList = [fileName for fileName in fileList if '.mat' in fileName]NEWLINE # Understand this gem of a regular expression sort.NEWLINE imageFileList.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])NEWLINE numImages = len(imageFileList)NEWLINE NEWLINE tiffRoiPath = tiffPath / roiNEWLINE if not tiffRoiPath.exists():NEWLINE tiffRoiPath.mkdir()NEWLINENEWLINE # Start Processing Data HereNEWLINE for aI in range(numImages):NEWLINENEWLINE imageFilePath = roiPath / imageFileList[aI]NEWLINE NEWLINE anImage = opl.stitchImage(imageFilePath, pixSize, magnification, background)NEWLINE NEWLINE for imlbl in anImage['imageLabels'].keys():NEWLINE saveFilePath = tiffRoiPath / f'{roi}_{imlbl}_{aI+1:03d}.tiff'NEWLINE uint8Image = odp.scaleImage(anImage[imlbl])NEWLINE retVal = cv2.imwrite(str(saveFilePath), uint8Image)NEWLINE NEWLINE NEWLINE return NoneNEWLINENEWLINEdef readExpDisc(dataPath):NEWLINENEWLINE '''Reads formatted excell spreadsheet and returns a dataframe with the experiment orgainsation.'''NEWLINENEWLINE spotlayoutPath = [*dataPath.glob('*Spot-Layout.xlsx')]NEWLINE if len(spotlayoutPath)==1:NEWLINE strainID = pd.read_excel(spotlayoutPath, sheet_name='Sheet1', header=0, usecols="A:L").set_index('ROI')NEWLINENEWLINE return strainIDNEWLINENEWLINEdef setdatadir(loc_data_dir):NEWLINE '''Set the directory where processed ODELAY data is loaded/saved'''NEWLINE configfilePath = pathlib.Path( pathlib.Path.home() / '.odelayconfig' )NEWLINENEWLINE with open(configfilePath, 'r') as fileIn:NEWLINE odelayConfig = json.load(fileIn)NEWLINENEWLINE localDataPath = pathlib.Path(loc_data_dir)NEWLINENEWLINE if localDataPath.exists:NEWLINE resolvedPath = localDataPath.resolve()NEWLINE LocalDataPathstr = str(resolvedPath)NEWLINENEWLINE HPCDataPath = LocalDataPathstr.replace('\\','/').replace('//helens','/')NEWLINENEWLINE odelayConfig['LocalDataDir'] = loc_data_dirNEWLINE odelayConfig['HPCDataDir'] = HPCDataPath NEWLINE print(f'Data Directory path from local computer is: {loc_data_dir}')NEWLINE print(f'Data Directory path from HPC computer is: {HPCDataPath}')NEWLINE NEWLINENEWLINE odelayConfig['PathCheck'] = FalseNEWLINENEWLINE with open(configfilePath, 'w') as fileOut:NEWLINE json.dump(odelayConfig, fileOut)NEWLINENEWLINE return resolvedPathNEWLINENEWLINEdef setimagedir(loc_image_dir):NEWLINE '''Set the directory where the experiment's images are located'''NEWLINENEWLINE configfilePath = pathlib.Path( pathlib.Path.home() / '.odelayconfig' )NEWLINENEWLINE with open(configfilePath, 'r') as fileIn:NEWLINE odelayConfig = json.load(fileIn)NEWLINENEWLINE localImagePath = pathlib.Path(loc_image_dir)NEWLINE NEWLINE if localImagePath.exists():NEWLINE NEWLINE resolvedPath = pathlib.Path(loc_image_dir).resolve()NEWLINE LocalImagePathstr = str(resolvedPath)NEWLINE NEWLINE HPCImagePath = LocalImagePathstr.replace('\\','/').replace('//pplhpc1ces','/gpfs/scratch')NEWLINENEWLINE odelayConfig['LocalImageDir'] = loc_image_dirNEWLINE odelayConfig['HPCImageDir'] = HPCImagePath NEWLINE print(f'Image Directory path from local computer is: {loc_image_dir}')NEWLINE print(f'Image Directory path from HPC computer is: {HPCImagePath}')NEWLINENEWLINENEWLINE odelayConfig['PathCheck'] = FalseNEWLINE NEWLINE with open(configfilePath, 'w') as fileOut:NEWLINE json.dump(odelayConfig, fileOut)NEWLINENEWLINENEWLINE return resolvedPathNEWLINENEWLINEdef loadConfig():NEWLINE configfilePath = pathlib.Path( pathlib.Path.home() / '.odelayconfig' )NEWLINENEWLINE with open(configfilePath, 'r') as fileIn:NEWLINE odelayConfig = json.load(fileIn)NEWLINENEWLINE return odelayConfigNEWLINENEWLINEdef saveConfig(odelayConfig):NEWLINENEWLINE configfilePath = pathlib.Path( pathlib.Path.home() / '.odelayconfig' )NEWLINE odelayConfig['PathCheck'] = FalseNEWLINENEWLINE with open(configfilePath, 'w') as fileOut:NEWLINE json.dump(odelayConfig, fileOut)NEWLINENEWLINE return odelayConfigNEWLINENEWLINEdef readMMConfigFile(filePath):NEWLINENEWLINE configFiltPath = pathlib.Path(filePath)NEWLINENEWLINE configList = []NEWLINENEWLINE configDict = {NEWLINE 'Device':{},NEWLINE 'Parent':{},NEWLINE 'Label':{},NEWLINE 'Group':{}NEWLINE }NEWLINENEWLINE with open(configFilePath) as csvfile:NEWLINE reader = csv.reader(_decomment(csvfile))NEWLINE for row in reader:NEWLINE configList.append(row)NEWLINENEWLINE for row in configList:NEWLINE NEWLINE if row[0] == 'Device':NEWLINE configDict['Device'].update({row[1]: [row[2],row[3]]})NEWLINENEWLINE elif row[0] == 'Parent':NEWLINE configDict['Parent'].update({row[1]:row[2]})NEWLINENEWLINE elif row[0] == 'Label':NEWLINE if row[1] in testDict[row[0]].keys():NEWLINE configDict[row[0]][row[1]].update({row[2]:row[3]})NEWLINENEWLINE else:NEWLINE configDict[row[0]].update({row[1]:{row[2]:row[3]}})NEWLINENEWLINE elif row[0] == 'Group':NEWLINE configDict['Group'].update({row[1]:{row[2]: row[3]}})NEWLINENEWLINE return configDictNEWLINENEWLINE# Print iterations progressNEWLINEdef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):NEWLINE """NEWLINE Call in a loop to create terminal progress barNEWLINE @params:NEWLINE iteration - Required : current iteration (Int)NEWLINE total - Required : total iterations (Int)NEWLINE prefix - Optional : prefix string (Str)NEWLINE suffix - Optional : suffix string (Str)NEWLINE decimals - Optional : positive number of decimals in percent complete (Int)NEWLINE length - Optional : character length of bar (Int)NEWLINE fill - Optional : bar fill character (Str)NEWLINE printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)NEWLINE """NEWLINE percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))NEWLINE filledLength = int(length * iteration // total)NEWLINE bar = fill * filledLength + '-' * (length - filledLength)NEWLINE print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)NEWLINE # Print New Line on CompleteNEWLINE if iteration == total: NEWLINE print()NEWLINENEWLINEdef openFileDialog():NEWLINENEWLINE app = QApplication(sys.argv)NEWLINE options = QFileDialog.Options()NEWLINE fileName, _ = QFileDialog.getOpenFileName(None,"Select ODELAY Data Set", "","ODELAYExpDisc (*Index_ODELAYData.mat);; Mat-Files (*.mat)", options=options)NEWLINE app.quit()NEWLINE return fileName
from django.contrib.sites.models import SiteNEWLINEfrom django.db import modelsNEWLINEfrom django.urls import NoReverseMatch, get_script_prefix, reverseNEWLINEfrom django.utils.encoding import iri_to_uriNEWLINEfrom django.utils.translation import gettext_lazy as _NEWLINENEWLINENEWLINEclass FlatPage(models.Model):NEWLINE url = models.CharField(_("URL"), max_length=100, db_index=True)NEWLINE title = models.CharField(_("title"), max_length=200)NEWLINE content = models.TextField(_("content"), blank=True)NEWLINE enable_comments = models.BooleanField(_("enable comments"), default=False)NEWLINE template_name = models.CharField(NEWLINE _("template name"),NEWLINE max_length=70,NEWLINE blank=True,NEWLINE help_text=_(NEWLINE "Example: “flatpages/contact_page.html”. If this isn’t provided, "NEWLINE "the system will use “flatpages/default.html”."NEWLINE ),NEWLINE )NEWLINE registration_required = models.BooleanField(NEWLINE _("registration required"),NEWLINE help_text=_(NEWLINE "If this is checked, only logged-in users will be able to view the page."NEWLINE ),NEWLINE default=False,NEWLINE )NEWLINE sites = models.ManyToManyField(Site, verbose_name=_("sites"))NEWLINENEWLINE class Meta:NEWLINE db_table = "django_flatpage"NEWLINE verbose_name = _("flat page")NEWLINE verbose_name_plural = _("flat pages")NEWLINE ordering = ["url"]NEWLINENEWLINE def __str__(self):NEWLINE return "%s -- %s" % (self.url, self.title)NEWLINENEWLINE def get_absolute_url(self):NEWLINE from .views import flatpageNEWLINENEWLINE for url in (self.url.lstrip("/"), self.url):NEWLINE try:NEWLINE return reverse(flatpage, kwargs={"url": url})NEWLINE except NoReverseMatch:NEWLINE passNEWLINE # Handle script prefix manually because we bypass reverse()NEWLINE return iri_to_uri(get_script_prefix().rstrip("/") + self.url)NEWLINE
# Copyright (C) 2021 CyberUserBotNEWLINE# This file is a part of < https://github.com/CyberUserBot/Installer/ >NEWLINE# Please read the MIT license inNEWLINE# <https://www.github.com/CyberUserBot/Installer/blob/master/LICENSE/>.NEWLINENEWLINE# Təkrar istifadəyə icazə verilmir.NEWLINE# Yeniden kullanıma izin verilmiyor.NEWLINE# Reuse is not allowed.NEWLINENEWLINEimport osNEWLINEfrom requests import getNEWLINENEWLINEclass CyberConfig(object):NEWLINE REPO_BRANCH = "master"NEWLINE DESTINATION = "./cyberuserbot/"NEWLINE NEWLINENEWLINE NEWLINE# TEST = get('https://raw.githubusercontent.com/FaridDadashzade/deploy/main/installer.py').json()NEWLINE
from typing import Any, Iterable, Mapping, MutableMappingNEWLINENEWLINEfrom ghaudit.query.sub_query import SubQuery, ValidValueTypeNEWLINEfrom ghaudit.query.utils import PageInfo, jinja_envNEWLINENEWLINENEWLINEclass SubQueryCommon(SubQuery):NEWLINE def __init__(NEWLINE self,NEWLINE fragments: Iterable[str],NEWLINE entry: str,NEWLINE params: MutableMapping[str, str],NEWLINE ) -> None:NEWLINE SubQuery.__init__(self)NEWLINE self._entry = entryNEWLINE self._params = paramsNEWLINE self._values = {} # type: MutableMapping[str, ValidValueType]NEWLINENEWLINE env = jinja_env()NEWLINE self._templates = [env.get_template(frag) for frag in fragments]NEWLINENEWLINE def entry(self) -> str:NEWLINE return self._entryNEWLINENEWLINE def params(self) -> Mapping[str, str]:NEWLINE return self._paramsNEWLINENEWLINE def render(self, args: Mapping[str, ValidValueType]) -> str:NEWLINE frags = [frag.render(args) for frag in self._templates]NEWLINE return "".join(frags)NEWLINENEWLINE def update_page_info(self, response: Mapping[str, Any]) -> None:NEWLINE raise NotImplementedError("abstract function call")NEWLINENEWLINE def params_values(self) -> Mapping[str, ValidValueType]:NEWLINE return self._valuesNEWLINENEWLINE def __repr__(self) -> str:NEWLINE return "{}({}): {}".format(NEWLINE self._entry, self._count, repr(self._page_info)NEWLINE )NEWLINENEWLINE def _iterate(self, page_info: PageInfo, cursor_name: str) -> None:NEWLINE self._page_info = page_infoNEWLINE self._values[cursor_name] = self._page_info["endCursor"]NEWLINE self._count += 1NEWLINE
from math import ceilNEWLINENEWLINEimport numpy as npNEWLINEfrom numpy.testing import assert_array_equalNEWLINEimport pytestNEWLINENEWLINEfrom sklearn.ensemble import StackingClassifierNEWLINEfrom sklearn.exceptions import NotFittedErrorNEWLINEfrom sklearn.neighbors import KNeighborsClassifierNEWLINEfrom sklearn.svm import SVCNEWLINEfrom sklearn.model_selection import train_test_splitNEWLINEfrom sklearn.datasets import load_iris, make_blobsNEWLINEfrom sklearn.metrics import accuracy_scoreNEWLINENEWLINEfrom sklearn.semi_supervised import SelfTrainingClassifierNEWLINENEWLINE# Author: Oliver Rausch <rauscho@ethz.ch>NEWLINE# License: BSD 3 clauseNEWLINENEWLINE# load the iris dataset and randomly permute itNEWLINEiris = load_iris()NEWLINEX_train, X_test, y_train, y_test = train_test_split(NEWLINE iris.data, iris.target, random_state=0NEWLINE)NEWLINENEWLINEn_labeled_samples = 50NEWLINENEWLINEy_train_missing_labels = y_train.copy()NEWLINEy_train_missing_labels[n_labeled_samples:] = -1NEWLINEmapping = {0: "A", 1: "B", 2: "C", -1: "-1"}NEWLINEy_train_missing_strings = np.vectorize(mapping.get)(y_train_missing_labels).astype(NEWLINE objectNEWLINE)NEWLINEy_train_missing_strings[y_train_missing_labels == -1] = -1NEWLINENEWLINENEWLINEdef test_missing_predict_proba():NEWLINE # Check that an error is thrown if predict_proba is not implementedNEWLINE base_estimator = SVC(probability=False, gamma="scale")NEWLINE self_training = SelfTrainingClassifier(base_estimator)NEWLINENEWLINE with pytest.raises(ValueError, match=r"base_estimator \(SVC\) should"):NEWLINE self_training.fit(X_train, y_train_missing_labels)NEWLINENEWLINENEWLINEdef test_none_classifier():NEWLINE st = SelfTrainingClassifier(None)NEWLINE with pytest.raises(ValueError, match="base_estimator cannot be None"):NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("max_iter, threshold", [(-1, 1.0), (-100, -2), (-10, 10)])NEWLINEdef test_invalid_params(max_iter, threshold):NEWLINE # Test negative iterationsNEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(base_estimator, max_iter=max_iter)NEWLINE with pytest.raises(ValueError, match="max_iter must be >= 0 or None"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(base_estimator, threshold=threshold)NEWLINE with pytest.raises(ValueError, match="threshold must be in"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINENEWLINEdef test_invalid_params_selection_crit():NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), criterion="foo")NEWLINENEWLINE with pytest.raises(ValueError, match="criterion must be either"):NEWLINE st.fit(X_train, y_train)NEWLINENEWLINENEWLINEdef test_warns_k_best():NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), criterion="k_best", k_best=1000)NEWLINE with pytest.warns(UserWarning, match="k_best is larger than"):NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "base_estimator",NEWLINE [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],NEWLINE)NEWLINE@pytest.mark.parametrize("selection_crit", ["threshold", "k_best"])NEWLINEdef test_classification(base_estimator, selection_crit):NEWLINE # Check classification for various parameter settings.NEWLINE # Also assert that predictions for strings and numerical labels are equal.NEWLINE # Also test for multioutput classificationNEWLINE threshold = 0.75NEWLINE max_iter = 10NEWLINE st = SelfTrainingClassifier(NEWLINE base_estimator, max_iter=max_iter, threshold=threshold, criterion=selection_critNEWLINE )NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINE pred = st.predict(X_test)NEWLINE proba = st.predict_proba(X_test)NEWLINENEWLINE st_string = SelfTrainingClassifier(NEWLINE base_estimator, max_iter=max_iter, criterion=selection_crit, threshold=thresholdNEWLINE )NEWLINE st_string.fit(X_train, y_train_missing_strings)NEWLINE pred_string = st_string.predict(X_test)NEWLINE proba_string = st_string.predict_proba(X_test)NEWLINENEWLINE assert_array_equal(np.vectorize(mapping.get)(pred), pred_string)NEWLINE assert_array_equal(proba, proba_string)NEWLINENEWLINE assert st.termination_condition_ == st_string.termination_condition_NEWLINE # Check consistency between labeled_iter, n_iter and max_iterNEWLINE labeled = y_train_missing_labels != -1NEWLINE # assert that labeled samples have labeled_iter = 0NEWLINE assert_array_equal(st.labeled_iter_ == 0, labeled)NEWLINE # assert that labeled samples do not change label during trainingNEWLINE assert_array_equal(y_train_missing_labels[labeled], st.transduction_[labeled])NEWLINENEWLINE # assert that the max of the iterations is less than the total amount ofNEWLINE # iterationsNEWLINE assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iterNEWLINE assert np.max(st_string.labeled_iter_) <= st_string.n_iter_ <= max_iterNEWLINENEWLINE # check shapesNEWLINE assert st.labeled_iter_.shape == st.transduction_.shapeNEWLINE assert st_string.labeled_iter_.shape == st_string.transduction_.shapeNEWLINENEWLINENEWLINEdef test_k_best():NEWLINE st = SelfTrainingClassifier(NEWLINE KNeighborsClassifier(n_neighbors=1),NEWLINE criterion="k_best",NEWLINE k_best=10,NEWLINE max_iter=None,NEWLINE )NEWLINE y_train_only_one_label = np.copy(y_train)NEWLINE y_train_only_one_label[1:] = -1NEWLINE n_samples = y_train.shape[0]NEWLINENEWLINE n_expected_iter = ceil((n_samples - 1) / 10)NEWLINE st.fit(X_train, y_train_only_one_label)NEWLINE assert st.n_iter_ == n_expected_iterNEWLINENEWLINE # Check labeled_iter_NEWLINE assert np.sum(st.labeled_iter_ == 0) == 1NEWLINE for i in range(1, n_expected_iter):NEWLINE assert np.sum(st.labeled_iter_ == i) == 10NEWLINE assert np.sum(st.labeled_iter_ == n_expected_iter) == (n_samples - 1) % 10NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINEdef test_sanity_classification():NEWLINE base_estimator = SVC(gamma="scale", probability=True)NEWLINE base_estimator.fit(X_train[n_labeled_samples:], y_train[n_labeled_samples:])NEWLINENEWLINE st = SelfTrainingClassifier(base_estimator)NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE pred1, pred2 = base_estimator.predict(X_test), st.predict(X_test)NEWLINE assert not np.array_equal(pred1, pred2)NEWLINE score_supervised = accuracy_score(base_estimator.predict(X_test), y_test)NEWLINE score_self_training = accuracy_score(st.predict(X_test), y_test)NEWLINENEWLINE assert score_self_training > score_supervisedNEWLINENEWLINENEWLINEdef test_none_iter():NEWLINE # Check that the all samples were labeled after a 'reasonable' number ofNEWLINE # iterations.NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), threshold=0.55, max_iter=None)NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE assert st.n_iter_ < 10NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINE@pytest.mark.parametrize(NEWLINE "base_estimator",NEWLINE [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],NEWLINE)NEWLINE@pytest.mark.parametrize("y", [y_train_missing_labels, y_train_missing_strings])NEWLINEdef test_zero_iterations(base_estimator, y):NEWLINE # Check classification for zero iterations.NEWLINE # Fitting a SelfTrainingClassifier with zero iterations should give theNEWLINE # same results as fitting a supervised classifier.NEWLINE # This also asserts that string arrays work as expected.NEWLINENEWLINE clf1 = SelfTrainingClassifier(base_estimator, max_iter=0)NEWLINENEWLINE clf1.fit(X_train, y)NEWLINENEWLINE clf2 = base_estimator.fit(X_train[:n_labeled_samples], y[:n_labeled_samples])NEWLINENEWLINE assert_array_equal(clf1.predict(X_test), clf2.predict(X_test))NEWLINE assert clf1.termination_condition_ == "max_iter"NEWLINENEWLINENEWLINEdef test_prefitted_throws_error():NEWLINE # Test that passing a pre-fitted classifier and calling predict throws anNEWLINE # errorNEWLINE knn = KNeighborsClassifier()NEWLINE knn.fit(X_train, y_train)NEWLINE st = SelfTrainingClassifier(knn)NEWLINE with pytest.raises(NEWLINE NotFittedError,NEWLINE match="This SelfTrainingClassifier instance is not fitted yet",NEWLINE ):NEWLINE st.predict(X_train)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("max_iter", range(1, 5))NEWLINEdef test_labeled_iter(max_iter):NEWLINE # Check that the amount of datapoints labeled in iteration 0 is equal toNEWLINE # the amount of labeled datapoints we passed.NEWLINE st = SelfTrainingClassifier(KNeighborsClassifier(), max_iter=max_iter)NEWLINENEWLINE st.fit(X_train, y_train_missing_labels)NEWLINE amount_iter_0 = len(st.labeled_iter_[st.labeled_iter_ == 0])NEWLINE assert amount_iter_0 == n_labeled_samplesNEWLINE # Check that the max of the iterations is less than the total amount ofNEWLINE # iterationsNEWLINE assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iterNEWLINENEWLINENEWLINEdef test_no_unlabeled():NEWLINE # Test that training on a fully labeled dataset produces the same resultsNEWLINE # as training the classifier by itself.NEWLINE knn = KNeighborsClassifier()NEWLINE knn.fit(X_train, y_train)NEWLINE st = SelfTrainingClassifier(knn)NEWLINE with pytest.warns(UserWarning, match="y contains no unlabeled samples"):NEWLINE st.fit(X_train, y_train)NEWLINE assert_array_equal(knn.predict(X_test), st.predict(X_test))NEWLINE # Assert that all samples were labeled in iteration 0 (since there were noNEWLINE # unlabeled samples).NEWLINE assert np.all(st.labeled_iter_ == 0)NEWLINE assert st.termination_condition_ == "all_labeled"NEWLINENEWLINENEWLINEdef test_early_stopping():NEWLINE svc = SVC(gamma="scale", probability=True)NEWLINE st = SelfTrainingClassifier(svc)NEWLINE X_train_easy = [[1], [0], [1], [0.5]]NEWLINE y_train_easy = [1, 0, -1, -1]NEWLINE # X = [[0.5]] cannot be predicted on with a high confidence, so trainingNEWLINE # stops earlyNEWLINE st.fit(X_train_easy, y_train_easy)NEWLINE assert st.n_iter_ == 1NEWLINE assert st.termination_condition_ == "no_change"NEWLINENEWLINENEWLINEdef test_strings_dtype():NEWLINE clf = SelfTrainingClassifier(KNeighborsClassifier())NEWLINE X, y = make_blobs(n_samples=30, random_state=0, cluster_std=0.1)NEWLINE labels_multiclass = ["one", "two", "three"]NEWLINENEWLINE y_strings = np.take(labels_multiclass, y)NEWLINENEWLINE with pytest.raises(ValueError, match="dtype"):NEWLINE clf.fit(X, y_strings)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("verbose", [True, False])NEWLINEdef test_verbose(capsys, verbose):NEWLINE clf = SelfTrainingClassifier(KNeighborsClassifier(), verbose=verbose)NEWLINE clf.fit(X_train, y_train_missing_labels)NEWLINENEWLINE captured = capsys.readouterr()NEWLINENEWLINE if verbose:NEWLINE assert "iteration" in captured.outNEWLINE else:NEWLINE assert "iteration" not in captured.outNEWLINENEWLINENEWLINEdef test_verbose_k_best(capsys):NEWLINE st = SelfTrainingClassifier(NEWLINE KNeighborsClassifier(n_neighbors=1),NEWLINE criterion="k_best",NEWLINE k_best=10,NEWLINE verbose=True,NEWLINE max_iter=None,NEWLINE )NEWLINENEWLINE y_train_only_one_label = np.copy(y_train)NEWLINE y_train_only_one_label[1:] = -1NEWLINE n_samples = y_train.shape[0]NEWLINENEWLINE n_expected_iter = ceil((n_samples - 1) / 10)NEWLINE st.fit(X_train, y_train_only_one_label)NEWLINENEWLINE captured = capsys.readouterr()NEWLINENEWLINE msg = "End of iteration {}, added {} new labels."NEWLINE for i in range(1, n_expected_iter):NEWLINE assert msg.format(i, 10) in captured.outNEWLINENEWLINE assert msg.format(n_expected_iter, (n_samples - 1) % 10) in captured.outNEWLINENEWLINENEWLINEdef test_k_best_selects_best():NEWLINE # Tests that the labels added by st really are the 10 best labels.NEWLINE svc = SVC(gamma="scale", probability=True, random_state=0)NEWLINE st = SelfTrainingClassifier(svc, criterion="k_best", max_iter=1, k_best=10)NEWLINE has_label = y_train_missing_labels != -1NEWLINE st.fit(X_train, y_train_missing_labels)NEWLINENEWLINE got_label = ~has_label & (st.transduction_ != -1)NEWLINENEWLINE svc.fit(X_train[has_label], y_train_missing_labels[has_label])NEWLINE pred = svc.predict_proba(X_train[~has_label])NEWLINE max_proba = np.max(pred, axis=1)NEWLINENEWLINE most_confident_svc = X_train[~has_label][np.argsort(max_proba)[-10:]]NEWLINE added_by_st = X_train[np.where(got_label)].tolist()NEWLINENEWLINE for row in most_confident_svc.tolist():NEWLINE assert row in added_by_stNEWLINENEWLINENEWLINEdef test_base_estimator_meta_estimator():NEWLINE # Check that a meta-estimator relying on an estimator implementingNEWLINE # `predict_proba` will work even if it does expose this method before beingNEWLINE # fitted.NEWLINE # Non-regression test for:NEWLINE # https://github.com/scikit-learn/scikit-learn/issues/19119NEWLINENEWLINE base_estimator = StackingClassifier(NEWLINE estimators=[NEWLINE ("svc_1", SVC(probability=True)),NEWLINE ("svc_2", SVC(probability=True)),NEWLINE ],NEWLINE final_estimator=SVC(probability=True),NEWLINE cv=2,NEWLINE )NEWLINENEWLINE # make sure that the `base_estimator` does not expose `predict_proba`NEWLINE # without being fittedNEWLINE assert not hasattr(base_estimator, "predict_proba")NEWLINENEWLINE clf = SelfTrainingClassifier(base_estimator=base_estimator)NEWLINE clf.fit(X_train, y_train_missing_labels)NEWLINE clf.predict_proba(X_test)NEWLINE
# MIT LICENSENEWLINE#NEWLINE# Copyright 1997 - 2020 by IXIA KeysightNEWLINE#NEWLINE# Permission is hereby granted, free of charge, to any person obtaining a copyNEWLINE# of this software and associated documentation files (the "Software"),NEWLINE# to deal in the Software without restriction, including without limitationNEWLINE# the rights to use, copy, modify, merge, publish, distribute, sublicense,NEWLINE# and/or sell copies of the Software, and to permit persons to whom theNEWLINE# Software is furnished to do so, subject to the following conditions:NEWLINE#NEWLINE# The above copyright notice and this permission notice shall be included inNEWLINE# all copies or substantial portions of the Software.NEWLINE#NEWLINE# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORNEWLINE# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,NEWLINE# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THENEWLINE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERNEWLINE# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,NEWLINE# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INNEWLINE# THE SOFTWARE. NEWLINEfrom ixnetwork_restpy.base import BaseNEWLINEfrom ixnetwork_restpy.files import FilesNEWLINENEWLINENEWLINEclass SubTlv(Base):NEWLINE """Sub Tlv containerNEWLINE The SubTlv class encapsulates a list of subTlv resources that are managed by the system.NEWLINE A list of resources can be retrieved from the server using the SubTlv.find() method.NEWLINE """NEWLINENEWLINE __slots__ = ()NEWLINE _SDM_NAME = 'subTlv'NEWLINE _SDM_ATT_MAP = {NEWLINE 'Description': 'description',NEWLINE 'EnablePerSession': 'enablePerSession',NEWLINE 'IsEnabled': 'isEnabled',NEWLINE 'Name': 'name',NEWLINE }NEWLINENEWLINE def __init__(self, parent):NEWLINE super(SubTlv, self).__init__(parent)NEWLINENEWLINE @propertyNEWLINE def Value(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.tlvprofile.value_ac1d7b13584a86b9cf1c28dca3390bca.Value): An instance of the Value classNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE from ixnetwork_restpy.testplatform.sessions.ixnetwork.topology.tlvprofile.value_ac1d7b13584a86b9cf1c28dca3390bca import ValueNEWLINE return Value(self)._select()NEWLINENEWLINE @propertyNEWLINE def Description(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - str: Description of the tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['Description'])NEWLINE @Description.setterNEWLINE def Description(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['Description'], value)NEWLINENEWLINE @propertyNEWLINE def EnablePerSession(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - obj(ixnetwork_restpy.multivalue.Multivalue): Enable TLV per sessionNEWLINE """NEWLINE from ixnetwork_restpy.multivalue import MultivalueNEWLINE return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['EnablePerSession']))NEWLINENEWLINE @propertyNEWLINE def IsEnabled(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - bool: Enables/disables this tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['IsEnabled'])NEWLINE @IsEnabled.setterNEWLINE def IsEnabled(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['IsEnabled'], value)NEWLINENEWLINE @propertyNEWLINE def Name(self):NEWLINE """NEWLINE ReturnsNEWLINE -------NEWLINE - str: Name of the tlvNEWLINE """NEWLINE return self._get_attribute(self._SDM_ATT_MAP['Name'])NEWLINE @Name.setterNEWLINE def Name(self, value):NEWLINE self._set_attribute(self._SDM_ATT_MAP['Name'], value)NEWLINENEWLINE def update(self, Description=None, IsEnabled=None, Name=None):NEWLINE """Updates subTlv resource on the server.NEWLINENEWLINE This method has some named parameters with a type: obj (Multivalue).NEWLINE The Multivalue class has documentation that details the possible values for those named parameters.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - Description (str): Description of the tlvNEWLINE - IsEnabled (bool): Enables/disables this tlvNEWLINE - Name (str): Name of the tlvNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))NEWLINENEWLINE def find(self, Description=None, IsEnabled=None, Name=None):NEWLINE """Finds and retrieves subTlv resources from the server.NEWLINENEWLINE All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve subTlv resources from the server.NEWLINE To retrieve an exact match ensure the parameter value starts with ^ and ends with $NEWLINE By default the find method takes no parameters and will retrieve all subTlv resources from the server.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - Description (str): Description of the tlvNEWLINE - IsEnabled (bool): Enables/disables this tlvNEWLINE - Name (str): Name of the tlvNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - self: This instance with matching subTlv resources retrieved from the server available through an iterator or indexNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))NEWLINENEWLINE def read(self, href):NEWLINE """Retrieves a single instance of subTlv data from the server.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - href (str): An href to the instance to be retrievedNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - self: This instance with the subTlv resources from the server available through an iterator or indexNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - NotFoundError: The requested resource does not exist on the serverNEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._read(href)NEWLINENEWLINE def get_device_ids(self, PortNames=None, EnablePerSession=None):NEWLINE """Base class infrastructure that gets a list of subTlv device ids encapsulated by this object.NEWLINENEWLINE Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object.NEWLINENEWLINE ArgsNEWLINE ----NEWLINE - PortNames (str): optional regex of port namesNEWLINE - EnablePerSession (str): optional regex of enablePerSessionNEWLINENEWLINE ReturnsNEWLINE -------NEWLINE - list(int): A list of device ids that meets the regex criteria provided in the method parametersNEWLINENEWLINE RaisesNEWLINE ------NEWLINE - ServerError: The server has encountered an uncategorized error conditionNEWLINE """NEWLINE return self._get_ngpf_device_ids(locals())NEWLINE
# Copyright 2019, Google LLC.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINEimport collectionsNEWLINENEWLINEfrom absl.testing import parameterizedNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom tensorflow_federated.python.core.backends.native import execution_contextsNEWLINEfrom tensorflow_federated.python.simulation.baselines import client_specNEWLINEfrom tensorflow_federated.python.simulation.baselines.stackoverflow import word_prediction_preprocessingNEWLINENEWLINENEWLINETEST_DATA = collections.OrderedDict(NEWLINE creation_date=(['unused date']),NEWLINE score=([tf.constant(0, dtype=tf.int64)]),NEWLINE tags=(['unused test tag']),NEWLINE title=(['unused title']),NEWLINE tokens=(['one must imagine']),NEWLINE type=(['unused type']),NEWLINE)NEWLINENEWLINENEWLINEdef _compute_length_of_dataset(ds):NEWLINE return ds.reduce(0, lambda x, _: x + 1)NEWLINENEWLINENEWLINEclass SplitInputTest(tf.test.TestCase):NEWLINENEWLINE def test_split_input_returns_expected_result(self):NEWLINE tokens = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE expected_input = [[0, 1, 2, 3]]NEWLINE expected_target = [[1, 2, 3, 4]]NEWLINE split = word_prediction_preprocessing.split_input_target(tokens)NEWLINE self.assertAllEqual(self.evaluate(split[0]), expected_input)NEWLINE self.assertAllEqual(self.evaluate(split[1]), expected_target)NEWLINENEWLINENEWLINEclass ToIDsFnTest(tf.test.TestCase):NEWLINENEWLINE def test_ids_fn_truncates_on_input_longer_than_sequence_length(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 1NEWLINE bos = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab)).beginning_of_sentenceNEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertAllEqual(self.evaluate(processed), [bos, 1])NEWLINENEWLINE def test_build_to_ids_fn_embeds_all_vocab(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE special_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab))NEWLINE bos = special_tokens.beginning_of_sentenceNEWLINE eos = special_tokens.end_of_sentenceNEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertAllEqual(self.evaluate(processed), [bos, 1, 2, 3, eos])NEWLINENEWLINE def test_pad_token_correct(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len)NEWLINE special_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab))NEWLINE pad = special_tokens.paddingNEWLINE bos = special_tokens.beginning_of_sentenceNEWLINE eos = special_tokens.end_of_sentenceNEWLINE data = {'tokens': 'A B C'}NEWLINE processed = to_ids_fn(data)NEWLINE batched_ds = tf.data.Dataset.from_tensor_slices([processed]).padded_batch(NEWLINE 1, padded_shapes=[6])NEWLINE sample_elem = next(iter(batched_ds))NEWLINE self.assertAllEqual(self.evaluate(sample_elem), [[bos, 1, 2, 3, eos, pad]])NEWLINENEWLINE def test_out_of_vocab_tokens_are_correct(self):NEWLINE vocab = ['A', 'B', 'C']NEWLINE max_seq_len = 5NEWLINE num_out_of_vocab_buckets = 2NEWLINE to_ids_fn = word_prediction_preprocessing.build_to_ids_fn(NEWLINE vocab, max_seq_len, num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINE out_of_vocab_tokens = word_prediction_preprocessing.get_special_tokens(NEWLINE len(vocab),NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets).out_of_vocabNEWLINE data = {'tokens': 'A B D'}NEWLINE processed = to_ids_fn(data)NEWLINE self.assertLen(out_of_vocab_tokens, num_out_of_vocab_buckets)NEWLINE self.assertIn(self.evaluate(processed)[3], out_of_vocab_tokens)NEWLINENEWLINENEWLINEclass BatchAndSplitTest(tf.test.TestCase):NEWLINENEWLINE def test_batch_and_split_fn_returns_dataset_with_correct_type_spec(self):NEWLINE token = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE ds = tf.data.Dataset.from_tensor_slices(token)NEWLINE padded_and_batched = word_prediction_preprocessing.batch_and_split(NEWLINE ds, sequence_length=6, batch_size=1)NEWLINE self.assertIsInstance(padded_and_batched, tf.data.Dataset)NEWLINE self.assertEqual(padded_and_batched.element_spec, (tf.TensorSpec(NEWLINE [None, 6], dtype=tf.int64), tf.TensorSpec([None, 6], dtype=tf.int64)))NEWLINENEWLINE def test_batch_and_split_fn_returns_dataset_yielding_expected_elements(self):NEWLINE token = tf.constant([[0, 1, 2, 3, 4]], dtype=tf.int64)NEWLINE ds = tf.data.Dataset.from_tensor_slices(token)NEWLINE padded_and_batched = word_prediction_preprocessing.batch_and_split(NEWLINE ds, sequence_length=6, batch_size=1)NEWLINE num_elems = 0NEWLINE for elem in padded_and_batched:NEWLINE self.assertAllEqual(NEWLINE self.evaluate(elem[0]),NEWLINE tf.constant([[0, 1, 2, 3, 4, 0]], dtype=tf.int64))NEWLINE self.assertAllEqual(NEWLINE self.evaluate(elem[1]),NEWLINE tf.constant([[1, 2, 3, 4, 0, 0]], dtype=tf.int64))NEWLINE num_elems += 1NEWLINE self.assertEqual(num_elems, 1)NEWLINENEWLINENEWLINEclass PreprocessFnTest(tf.test.TestCase, parameterized.TestCase):NEWLINENEWLINE def test_preprocess_fn_with_empty_vocab_raises(self):NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(ValueError, 'vocab must be non-empty'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=[], sequence_length=10)NEWLINENEWLINE @parameterized.named_parameters(('zero_value', 0), ('negative_value1', -1),NEWLINE ('negative_value2', -2))NEWLINE def test_nonpositive_sequence_length_raises(self, sequence_length):NEWLINE del sequence_length # Unused.NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(ValueError,NEWLINE 'sequence_length must be a positive integer'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'], sequence_length=0)NEWLINENEWLINE @parameterized.named_parameters(('zero_value', 0), ('negative_value1', -1),NEWLINE ('negative_value2', -2))NEWLINE def test_nonpositive_num_out_of_vocab_buckets_length_raises(NEWLINE self, num_out_of_vocab_buckets):NEWLINE preprocess_spec = client_spec.ClientSpec(num_epochs=1, batch_size=1)NEWLINE with self.assertRaisesRegex(NEWLINE ValueError, 'num_out_of_vocab_buckets must be a positive integer'):NEWLINE word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE vocab=['A'],NEWLINE sequence_length=10,NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINENEWLINE @parameterized.named_parameters(('param1', 1, 1), ('param2', 4, 2),NEWLINE ('param3', 100, 3))NEWLINE def test_preprocess_fn_returns_correct_dataset_element_spec(NEWLINE self, sequence_length, num_out_of_vocab_buckets):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=sequence_length,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=num_out_of_vocab_buckets)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE preprocessed_ds.element_spec,NEWLINE (tf.TensorSpec(shape=[None, sequence_length], dtype=tf.int64),NEWLINE tf.TensorSpec(shape=[None, sequence_length], dtype=tf.int64)))NEWLINENEWLINE def test_preprocess_fn_returns_correct_sequence_with_1_out_of_vocab_bucket(NEWLINE self):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=6,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=1)NEWLINENEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE element = next(iter(preprocessed_ds))NEWLINENEWLINE # BOS is len(vocab)+2, EOS is len(vocab)+3, pad is 0, OOV is len(vocab)+1NEWLINE self.assertAllEqual(NEWLINE self.evaluate(element[0]),NEWLINE tf.constant([[4, 1, 2, 3, 5, 0]], dtype=tf.int64))NEWLINENEWLINE def test_preprocess_fn_returns_correct_sequence_with_3_out_of_vocab_buckets(NEWLINE self):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=1, batch_size=32, max_elements=100)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec,NEWLINE sequence_length=6,NEWLINE vocab=['one', 'must'],NEWLINE num_out_of_vocab_buckets=3)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE element = next(iter(preprocessed_ds))NEWLINE # BOS is len(vocab)+3+1NEWLINE self.assertEqual(self.evaluate(element[0])[0][0], 6)NEWLINE self.assertEqual(self.evaluate(element[0])[0][1], 1)NEWLINE self.assertEqual(self.evaluate(element[0])[0][2], 2)NEWLINE # OOV is [len(vocab)+1, len(vocab)+2, len(vocab)+3]NEWLINE self.assertIn(self.evaluate(element[0])[0][3], [3, 4, 5])NEWLINE # EOS is len(vocab)+3+2NEWLINE self.assertEqual(self.evaluate(element[0])[0][4], 7)NEWLINE # pad is 0NEWLINE self.assertEqual(self.evaluate(element[0])[0][5], 0)NEWLINENEWLINE @parameterized.named_parameters(NEWLINE ('num_epochs_1_batch_size_1', 1, 1),NEWLINE ('num_epochs_4_batch_size_2', 4, 2),NEWLINE ('num_epochs_9_batch_size_3', 9, 3),NEWLINE ('num_epochs_12_batch_size_1', 12, 1),NEWLINE ('num_epochs_3_batch_size_5', 3, 5),NEWLINE ('num_epochs_7_batch_size_2', 7, 2),NEWLINE )NEWLINE def test_ds_length_is_ceil_num_epochs_over_batch_size(self, num_epochs,NEWLINE batch_size):NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=num_epochs, batch_size=batch_size)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'], sequence_length=10)NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE _compute_length_of_dataset(preprocessed_ds),NEWLINE tf.cast(tf.math.ceil(num_epochs / batch_size), tf.int32))NEWLINENEWLINE @parameterized.named_parameters(NEWLINE ('max_elements1', 1),NEWLINE ('max_elements3', 3),NEWLINE ('max_elements7', 7),NEWLINE ('max_elements11', 11),NEWLINE ('max_elements18', 18),NEWLINE )NEWLINE def test_ds_length_with_max_elements(self, max_elements):NEWLINE repeat_size = 10NEWLINE ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)NEWLINE preprocess_spec = client_spec.ClientSpec(NEWLINE num_epochs=repeat_size, batch_size=1, max_elements=max_elements)NEWLINE preprocess_fn = word_prediction_preprocessing.create_preprocess_fn(NEWLINE preprocess_spec, vocab=['A'])NEWLINE preprocessed_ds = preprocess_fn(ds)NEWLINE self.assertEqual(NEWLINE _compute_length_of_dataset(preprocessed_ds),NEWLINE min(repeat_size, max_elements))NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE execution_contexts.set_local_python_execution_context()NEWLINE tf.test.main()NEWLINE
#!/usr/bin/env pythonNEWLINE#NEWLINE# __COPYRIGHT__NEWLINE#NEWLINE# Permission is hereby granted, free of charge, to any person obtainingNEWLINE# a copy of this software and associated documentation files (theNEWLINE# "Software"), to deal in the Software without restriction, includingNEWLINE# without limitation the rights to use, copy, modify, merge, publish,NEWLINE# distribute, sublicense, and/or sell copies of the Software, and toNEWLINE# permit persons to whom the Software is furnished to do so, subject toNEWLINE# the following conditions:NEWLINE#NEWLINE# The above copyright notice and this permission notice shall be includedNEWLINE# in all copies or substantial portions of the Software.NEWLINE#NEWLINE# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANYNEWLINE# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THENEWLINE# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNEWLINE# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BENEWLINE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONNEWLINE# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIONNEWLINE# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.NEWLINE#NEWLINENEWLINE__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"NEWLINENEWLINE"""NEWLINEVerify basic use of CPPPDEFINES with various data types.NEWLINE"""NEWLINENEWLINEimport TestSConsNEWLINENEWLINEtest = TestSCons.TestSCons()NEWLINENEWLINEtest.write('SConstruct', """\NEWLINEtest_list = [NEWLINE 'xyz',NEWLINE ['x', 'y', 'z'],NEWLINE ['x', ['y', 123], 'z', ('int', '$INTEGER')],NEWLINE { 'c' : 3, 'b': None, 'a' : 1 },NEWLINE "${TESTDEFS}",NEWLINE]NEWLINEfor i in test_list:NEWLINE env = Environment(CPPDEFPREFIX='-D', CPPDEFSUFFIX='', INTEGER=0, TESTDEFS=["FOO", "BAR=1"])NEWLINE print(env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS'))NEWLINEfor i in test_list:NEWLINE env = Environment(CPPDEFPREFIX='|', CPPDEFSUFFIX='|', INTEGER=1, TESTDEFS=["FOO", "BAR=1"])NEWLINE print(env.Clone(CPPDEFINES=i).subst('$_CPPDEFFLAGS'))NEWLINE""")NEWLINENEWLINEexpect = test.wrap_stdout(build_str="scons: `.' is up to date.\n",NEWLINE read_str = """\NEWLINE-DxyzNEWLINE-Dx -Dy -DzNEWLINE-Dx -Dy=123 -Dz -Dint=0NEWLINE-Da=1 -Db -Dc=3NEWLINE-DFOO -DBAR=1NEWLINE|xyz|NEWLINE|x| |y| |z|NEWLINE|x| |y=123| |z| |int=1|NEWLINE|a=1| |b| |c=3|NEWLINE|FOO| |BAR=1|NEWLINE""")NEWLINENEWLINEtest.run(arguments = '.', stdout=expect)NEWLINENEWLINEtest.pass_test()NEWLINENEWLINE# Local Variables:NEWLINE# tab-width:4NEWLINE# indent-tabs-mode:nilNEWLINE# End:NEWLINE# vim: set expandtab tabstop=4 shiftwidth=4:NEWLINE
###SRNDNANEWLINE###shared reward, block designNEWLINENEWLINEfrom psychopy import visual, core, event, gui, data, sound, loggingNEWLINEimport csvNEWLINEimport datetimeNEWLINEimport randomNEWLINEimport numpyNEWLINEimport osNEWLINENEWLINE#maindir = os.getcwd()NEWLINENEWLINENEWLINE#parametersNEWLINEuseFullScreen = TrueNEWLINEuseDualScreen=1NEWLINEDEBUG = FalseNEWLINENEWLINEframe_rate=1NEWLINEdecision_dur=2.5NEWLINEoutcome_dur=1NEWLINENEWLINEresponseKeys=('2','3','z')NEWLINENEWLINE#get subjIDNEWLINEsubjDlg=gui.Dlg(title="Shared Reward Task")NEWLINEsubjDlg.addField('Enter Subject ID: ')NEWLINEsubjDlg.addField('Enter Friend Name: ') #1NEWLINEsubjDlg.addField('Enter Partner Name: ') #NOTE: PARTNER IS THE CONFEDERATE/STRANGER #2NEWLINEsubjDlg.show()NEWLINENEWLINEif gui.OK:NEWLINE subj_id=subjDlg.data[0]NEWLINE friend_id=subjDlg.data[1]NEWLINE stranger_id=subjDlg.data[2]NEWLINENEWLINEelse:NEWLINE sys.exit()NEWLINENEWLINErun_data = {NEWLINE 'Participant ID': subj_id,NEWLINE 'Date': str(datetime.datetime.now()),NEWLINE 'Description': 'SRNDNA Pilot - SharedReward Task'NEWLINE }NEWLINENEWLINE#window setupNEWLINEwin = visual.Window([800,600], monitor="testMonitor", units="deg", fullscr=useFullScreen, allowGUI=False, screen=useDualScreen)NEWLINENEWLINE#checkpointNEWLINEprint "got to check 1"NEWLINENEWLINE#define stimulusNEWLINEfixation = visual.TextStim(win, text="+", height=2)NEWLINENEWLINE#waiting for triggerNEWLINEready_screen = visual.TextStim(win, text="Please wait for the block of trials to begin. \n\nRemember to keep your head still!", height=1.5)NEWLINENEWLINE#decision screenNEWLINEnameStim = visual.TextStim(win=win,font='Arial',pos=(0, 6.0), height=1, color='white', colorSpace='rgb', opacity=1,depth=-1.0);NEWLINEcardStim = visual.Rect(win=win, name='polygon', width=(8.0,8.0)[0], height=(10.0,10.0)[1], ori=0, pos=(0, 0),lineWidth=5, lineColor=[1,1,1], lineColorSpace='rgb',fillColor=[0,0,0], fillColorSpace='rgb',opacity=1, depth=0.0, interpolate=True)NEWLINEquestion = visual.TextStim(win=win, name='text',text='?',font='Arial',pos=(0, 0), height=1, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1,depth=-1.0);NEWLINEpictureStim = visual.ImageStim(win, pos=(0,9.0), size=(6.65,6.65))NEWLINENEWLINE#outcome screenNEWLINEoutcome_cardStim = visual.Rect(win=win, name='polygon', width=(8.0,8.0)[0], height=(10.0,10.0)[1], ori=0, pos=(0, 0),lineWidth=5, lineColor=[1,1,1], lineColorSpace='rgb',fillColor=[0,0,0], fillColorSpace='rgb',opacity=1, depth=0.0, interpolate=True)NEWLINEoutcome_text = visual.TextStim(win=win, name='text',text='',font='Arial',pos=(0, 0), height=2, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1,depth=-1.0);NEWLINEoutcome_money = visual.TextStim(win=win, name='text',text='',font='Wingdings 3',pos=(0, 2.0), height=2, wrapWidth=None, ori=0, colorSpace='rgb', opacity=1,depth=-1.0);NEWLINENEWLINE#instructionsNEWLINEinstruct_screen = visual.TextStim(win, text='Welcome to the experiment.\n\nIn this task you will be guessing the numerical value of a card.\n\nPress Button 2 to guess low and press Button 3 to guess high.\n\nCorrect responses will result in a monetary gain of $10, and incorrect responses will result in a monetary loss of $5.\n\nRemember, you will be sharing monetary outcomes on each trial with the partner displayed at the top of the screen.', pos = (0,1), wrapWidth=20, height = 1.2)NEWLINENEWLINE#exitNEWLINEexit_screen = visual.TextStim(win, text='Thanks for playing! Please wait for instructions from the experimenter.', pos = (0,1), wrapWidth=20, height = 1.2)NEWLINENEWLINE#loggingNEWLINEexpdir = os.getcwd()NEWLINEsubjdir = '%s/logs/%s' % (expdir, subj_id)NEWLINEif not os.path.exists(subjdir):NEWLINE os.makedirs(subjdir)NEWLINElog_file = os.path.join(subjdir,'sub{}_task-sharedreward_raw.csv')NEWLINENEWLINEglobalClock = core.Clock()NEWLINElogging.setDefaultClock(globalClock)NEWLINENEWLINEtimer = core.Clock()NEWLINENEWLINE#trial handlerNEWLINEtrial_data = [r for r in csv.DictReader(open('SharedReward_design.csv','rU'))]NEWLINEtrials = data.TrialHandler(trial_data[:], 1, method="sequential") #change to [] for full runNEWLINENEWLINE#set partner namesNEWLINE# 3 = friend, 2 = confederate, 1 = computerNEWLINE# change names accordingly hereNEWLINENEWLINEstim_map = {NEWLINE '3': friend_id,NEWLINE '2': stranger_id,NEWLINE '1': 'Computer',NEWLINE }NEWLINENEWLINEimage_map = {NEWLINE '3': 'friend',NEWLINE '2': 'stranger',NEWLINE '1': 'computer',NEWLINE}NEWLINENEWLINEoutcome_map = {NEWLINE '3': 'reward',NEWLINE '2': 'neutral',NEWLINE '1': 'punish',NEWLINE }NEWLINENEWLINE#checkpointNEWLINEprint "got to check 2"NEWLINENEWLINEruns=[]NEWLINEfor run in range(1):NEWLINE run_data = []NEWLINE for t in range(8):NEWLINE sample = random.sample(range(len(trial_data)),1)[0]NEWLINE run_data.append(trial_data.pop(sample))NEWLINE runs.append(run_data)NEWLINENEWLINE# main task loopNEWLINE# InstructionsNEWLINEinstruct_screen.draw()NEWLINEwin.flip()NEWLINEevent.waitKeys(keyList=('space'))NEWLINENEWLINENEWLINEdef do_run(trial_data, run_num):NEWLINE resp=[]NEWLINE fileName=log_file.format(subj_id)NEWLINENEWLINE #wait for triggerNEWLINE ready_screen.draw()NEWLINE win.flip()NEWLINE event.waitKeys(keyList=('equal'))NEWLINE globalClock.reset()NEWLINENEWLINENEWLINE for trial in trials:NEWLINE condition_label = stim_map[trial['Partner']]NEWLINE image_label = image_map[trial['Partner']]NEWLINE imagepath = os.path.join(expdir,'Images')NEWLINE image = os.path.join(imagepath, "%s.png") % image_labelNEWLINE nameStim.setText(condition_label)NEWLINE pictureStim.setImage(image)NEWLINENEWLINENEWLINE #ITINEWLINE logging.log(level=logging.DATA, msg='ITI') #send fixation log eventNEWLINE timer.reset()NEWLINE ITI_onset = globalClock.getTime()NEWLINE iti_for_trial = float(trial['ITI'])NEWLINE while timer.getTime() < iti_for_trial:NEWLINE fixation.draw()NEWLINE win.flip()NEWLINENEWLINE #decision phaseNEWLINE timer.reset()NEWLINE event.clearEvents()NEWLINENEWLINE resp=[]NEWLINE resp_val=NoneNEWLINE resp_onset=NoneNEWLINENEWLINE trial_onset = globalClock.getTime()NEWLINENEWLINE while timer.getTime() < decision_dur:NEWLINE cardStim.draw()NEWLINE question.draw()NEWLINE pictureStim.draw()NEWLINE nameStim.draw()NEWLINE win.flip()NEWLINENEWLINE resp = event.getKeys(keyList = responseKeys)NEWLINENEWLINE if len(resp)>0:NEWLINE if resp[0] == 'z':NEWLINE #trials.saveAsText(fileName=log_file.format(subj_id),delim=',',dataOut='all_raw')NEWLINE os.chdir(subjdir)NEWLINE trials.saveAsWideText(fileName)NEWLINE os.chdir(expdir)NEWLINE win.close()NEWLINE core.quit()NEWLINE resp_val = int(resp[0])NEWLINE resp_onset = globalClock.getTime()NEWLINE rt = resp_onset - trial_onsetNEWLINE NEWLINE trials.addData('resp', int(resp_val))NEWLINE trials.addData('resp_onset', resp_onset)NEWLINE trials.addData('onset', trial_onset)NEWLINE trials.addData('ITIonset', ITI_onset)NEWLINE trials.addData('rt', rt)NEWLINE else:NEWLINE resp_val = 0NEWLINE resp_onset = '999'NEWLINE rt = '999'NEWLINENEWLINE trials.addData('resp', int(resp_val))NEWLINE trials.addData('resp_onset', resp_onset)NEWLINE trials.addData('onset', trial_onset)NEWLINE trials.addData('ITIonset', ITI_onset)NEWLINE trials.addData('rt', rt)NEWLINENEWLINENEWLINE#outcome phaseNEWLINE timer.reset()NEWLINE #win.flip()NEWLINE outcome_onset = globalClock.getTime()NEWLINENEWLINE while timer.getTime() < outcome_dur:NEWLINE outcome_cardStim.draw()NEWLINE pictureStim.draw()NEWLINE nameStim.draw()NEWLINE #win.flip()NEWLINENEWLINE if trial['Feedback'] == '3' and resp_val == 2:NEWLINE outcome_txt = int(random.randint(1,4))NEWLINE outcome_moneyTxt= 'h'NEWLINE outcome_color='green'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif trial['Feedback'] == '3' and resp_val == 3:NEWLINE outcome_txt = int(random.randint(6,9))NEWLINE outcome_moneyTxt= 'h'NEWLINE outcome_color='green'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif trial['Feedback'] == '2' and resp_val == 2:NEWLINE outcome_txt = int(5)NEWLINE outcome_moneyTxt= 'n'NEWLINE outcome_color='white'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif trial['Feedback'] == '2' and resp_val == 3:NEWLINE outcome_txt = int(5)NEWLINE outcome_moneyTxt= 'n'NEWLINE outcome_color='white'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif trial['Feedback'] == '1' and resp_val == 2:NEWLINE outcome_txt = int(random.randint(6,9))NEWLINE outcome_moneyTxt= 'i'NEWLINE outcome_color='red'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif trial['Feedback'] == '1' and resp_val == 3:NEWLINE outcome_txt = int (random.randint(1,4))NEWLINE outcome_moneyTxt= 'i'NEWLINE outcome_color='red'NEWLINE trials.addData('outcome_val', int(outcome_txt))NEWLINE elif resp_val == 0:NEWLINE outcome_txt='#'NEWLINE outcome_moneyTxt = ''NEWLINE outcome_color='white'NEWLINE trials.addData('outcome_val', 999)NEWLINENEWLINENEWLINE #print outcome_txtNEWLINE outcome_text.setText(outcome_txt)NEWLINE outcome_money.setText(outcome_moneyTxt)NEWLINE outcome_money.setColor(outcome_color)NEWLINE outcome_text.draw()NEWLINE outcome_money.draw()NEWLINE win.flip()NEWLINE core.wait(outcome_dur)NEWLINE #trials.addData('outcome_val', outcome_txt)NEWLINE trials.addData('outcome_onset', outcome_onset)NEWLINENEWLINE outcome_offset = globalClock.getTime()NEWLINE trials.addData('outcome_offset', outcome_offset)NEWLINENEWLINE duration = outcome_offset - trial_onsetNEWLINE trials.addData('trialDuration', duration)NEWLINE event.clearEvents()NEWLINE print "got to check 3"NEWLINENEWLINE os.chdir(subjdir)NEWLINE trials.saveAsWideText(fileName)NEWLINE os.chdir(expdir)NEWLINE if globalClock.getTime() < 850:NEWLINE endTime = (850 - globalClock.getTime())NEWLINE else:NEWLINE endTime = 10NEWLINE core.wait(endTime)NEWLINE print globalClock.getTime()NEWLINE #trials.saveAsText(fileName=log_file.format(subj_id),delim = ',',dataOut='all_raw')NEWLINEdo_run(trial_data,1)NEWLINENEWLINE#final ITINEWLINEfixation.draw()NEWLINEwin.flip()NEWLINEcore.wait(12)NEWLINENEWLINE# ExitNEWLINEexit_screen.draw()NEWLINEwin.flip()NEWLINEevent.waitKeys()NEWLINE
from django.conf.urls import urlNEWLINENEWLINEfrom .views import ImageDetail, ImageListNEWLINENEWLINENEWLINEurlpatterns = [NEWLINE url(r'^(?P<pk>\d+)/$', ImageDetail.as_view(), name='image-detail'),NEWLINE url(r'^(?P<gallery_ct>[a-z]+)/(?P<gallery_id>\d+)/$', ImageList.as_view(), name='image-list'),NEWLINE]NEWLINE
# Copyright The IETF Trust 2018, All Rights ReservedNEWLINE# -*- coding: utf-8 -*-NEWLINEfrom __future__ import unicode_literals, print_function, divisionNEWLINENEWLINEimport datetimeNEWLINEimport i18naddressNEWLINEimport lxmlNEWLINEimport osNEWLINEimport reNEWLINE#import sysNEWLINEimport sixNEWLINEimport unicodedataNEWLINEimport xml2rfcNEWLINENEWLINEfrom io import openNEWLINEfrom lxml.html import html_parserNEWLINEfrom lxml.html.builder import ElementMakerNEWLINENEWLINEif six.PY2:NEWLINE from urllib import urlopenNEWLINEelif six.PY3:NEWLINE from urllib.request import urlopenNEWLINENEWLINEtry:NEWLINE import debugNEWLINE debug.debug = TrueNEWLINEexcept ImportError:NEWLINE passNEWLINENEWLINEfrom xml2rfc import log, stringsNEWLINEfrom xml2rfc.writers.base import default_options, BaseV3WriterNEWLINEfrom xml2rfc.uniscripts import is_scriptNEWLINEfrom xml2rfc.util.date import extract_date, format_date, format_date_iso, get_expiry_dateNEWLINEfrom xml2rfc.util.name import ( full_author_name_expansion, short_author_role,NEWLINE ref_author_name_first, ref_author_name_last, NEWLINE short_author_name_set, full_author_name_set,NEWLINE short_org_name_set, full_org_name, )NEWLINEfrom xml2rfc.util.postal import ( get_normalized_address_info, address_hcard_properties,NEWLINE enhance_address_format, address_field_mapping, )NEWLINEfrom xml2rfc.util.unicode import expand_unicode_elementNEWLINEfrom xml2rfc.utils import namespaces, is_htmlblock, find_duplicate_html_ids, build_dataurlNEWLINENEWLINE#from xml2rfc import utilsNEWLINENEWLINE# ------------------------------------------------------------------------------NEWLINENEWLINEseen = set()NEWLINENEWLINEdef wrap(h, tag, **kwargs):NEWLINE w = build(tag, **kwargs)NEWLINE w.append(h)NEWLINE return wNEWLINENEWLINEdef slugify(s):NEWLINE s = s.strip().lower()NEWLINE s = re.sub(r'[^\w\s/|-]', '', s)NEWLINE s = re.sub(r'[-_\s/|]+', '-', s)NEWLINE s = s.strip('-')NEWLINE return sNEWLINENEWLINEdef maybefloat(f):NEWLINE try:NEWLINE return float(f)NEWLINE except (ValueError, TypeError):NEWLINE return NoneNEWLINENEWLINEdef wrap_ascii(tag, conj, name, ascii, role='', classes=None):NEWLINE role = ('','') if role in ['',None] else (', ', role)NEWLINE if ascii:NEWLINE e = build(tag,NEWLINE build.span(conj, name, classes='non-ascii'),NEWLINE ' (',NEWLINE build.span(ascii, classes='ascii'),NEWLINE ')',NEWLINE *role,NEWLINE classes=classesNEWLINE )NEWLINE else:NEWLINE e = build(tag, conj, name, *role, classes=classes)NEWLINE return eNEWLINENEWLINE#def wrap_ascii_div(NEWLINENEWLINENEWLINEclass ClassElementMaker(ElementMaker):NEWLINENEWLINE def __call__(self, tag, *children, **attrib):NEWLINE classes = attrib.pop('classes', None)NEWLINE attrib = dict( (k,v) for k,v in attrib.items() if v != None)NEWLINE elem = super(ClassElementMaker, self).__call__(tag, *children, **attrib)NEWLINE if classes:NEWLINE elem.set('class', classes)NEWLINE if is_htmlblock(elem) and (elem.tail is None or elem.tail.strip() == ''):NEWLINE elem.tail = '\n'NEWLINE return elemNEWLINEbuild = ClassElementMaker(makeelement=html_parser.makeelement)NEWLINENEWLINEclass ExtendingElementMaker(ClassElementMaker):NEWLINENEWLINE def __call__(self, tag, parent, precursor, *children, **attrib):NEWLINE elem = super(ExtendingElementMaker, self).__call__(tag, *children, **attrib)NEWLINE is_block = is_htmlblock(elem)NEWLINE #NEWLINE child = elemNEWLINE if precursor != None:NEWLINE pn = precursor.get('pn')NEWLINE sn = precursor.get('slugifiedName')NEWLINE an = precursor.get('anchor')NEWLINE if pn != None:NEWLINE elem.set('id', pn)NEWLINE if an != None and is_block:NEWLINE child = wrap(elem, 'div', id=an)NEWLINE elif sn != None:NEWLINE elem.set('id', sn)NEWLINE elif an != None:NEWLINE elem.set('id', an)NEWLINE if not elem.text or elem.text.strip() == '':NEWLINE elem.text = precursor.textNEWLINE elem.tail = precursor.tailNEWLINE if parent != None:NEWLINE parent.append(child)NEWLINE if is_block and (elem.tail is None or elem.tail.strip() == ''):NEWLINE elem.tail = '\n'NEWLINE if is_block and child != elem and (child.tail is None or child.tail.strip() == ''):NEWLINE child.tail = '\n'NEWLINE return elemNEWLINEadd = ExtendingElementMaker(makeelement=html_parser.makeelement)NEWLINENEWLINENEWLINEpilcrow = '\u00b6'NEWLINEmdash = '\u2014'NEWLINENEWLINE# ------------------------------------------------------------------------------NEWLINE# Address formatting functions, based on i18naddress functions, but rewritten toNEWLINE# produce html entities, rather than text lines.NEWLINENEWLINEdef _format_address_line(line_format, address, rules):NEWLINE def _get_field(name):NEWLINE field = []NEWLINE values = address.get(name, '')NEWLINE if isinstance(values, list):NEWLINE values = [ v for v in values if v ]NEWLINE if values:NEWLINE if isinstance(values, list):NEWLINE for value in values[:-1]:NEWLINE field.append(build.div(value, classes=address_hcard_properties[name]))NEWLINE field.append(build.span(values[-1], classes=address_hcard_properties[name]))NEWLINE else:NEWLINE span = NoneNEWLINE if name == 'name':NEWLINE role = address.get('role', '')NEWLINE if role:NEWLINE span = build.span(values,NEWLINE ' (',NEWLINE build.span(role, classes='role'),NEWLINE ')',NEWLINE classes=address_hcard_properties[name])NEWLINE if span == None:NEWLINE span = build.span(values, classes=address_hcard_properties[name])NEWLINE field.append(span)NEWLINE return fieldNEWLINENEWLINE replacements = {NEWLINE '%%%s' % code: _get_field(field_name)NEWLINE for code, field_name in address_field_mapping.items()}NEWLINENEWLINE field_entries = re.split('(%.)', line_format)NEWLINE fields = [ f for n in field_entries for f in replacements.get(n, n) ]NEWLINE return fieldsNEWLINENEWLINEdef format_address(address, latin=False):NEWLINE rules = i18naddress.get_validation_rules(address)NEWLINE address_format = (NEWLINE rules.address_latin_format if latin else rules.address_format)NEWLINE address_format = enhance_address_format(address, address_format)NEWLINE address_line_formats = address_format.split('%n')NEWLINE address_lines = [NEWLINE build.div(*_format_address_line(lf, address, rules), dir='auto')NEWLINE for lf in address_line_formats]NEWLINE address_lines = filter(lambda n: n!=None and ''.join(list(n.itertext())), address_lines)NEWLINE return address_linesNEWLINENEWLINEdef get_bidi_alignment(address):NEWLINE # We don't attempt to control the bidi layout in detail, but leave that toNEWLINE #the html layout engine; but want to know whether we have Right-to-left contentNEWLINE #in order to set the overall alignment of the address block.NEWLINE for field in address:NEWLINE line = address[field]NEWLINE if line:NEWLINE for ch in line:NEWLINE if isinstance(ch, six.text_type):NEWLINE dir = unicodedata.bidirectional(ch)NEWLINE if dir in ['R', 'AL']:NEWLINE return 'right'NEWLINE return 'left'NEWLINE NEWLINE# ------------------------------------------------------------------------------NEWLINENEWLINEclass HtmlWriter(BaseV3Writer):NEWLINENEWLINE def __init__(self, xmlrfc, quiet=None, options=default_options, date=datetime.date.today()):NEWLINE super(HtmlWriter, self).__init__(xmlrfc, quiet=quiet, options=options, date=date)NEWLINE self.anchor_tags = self.get_tags_with_anchor()NEWLINE self.duplicate_html_ids = set()NEWLINENEWLINE def get_tags_with_anchor(self):NEWLINE anchor_nodes = self.schema.xpath("//x:define/x:element//x:attribute[@name='anchor']", namespaces=namespaces)NEWLINE element_nodes = set()NEWLINE for a in anchor_nodes:NEWLINE for e in a.iterancestors():NEWLINE if e.tag.endswith('element'):NEWLINE element_nodes.add(e.get('name'))NEWLINE breakNEWLINE return element_nodesNEWLINENEWLINE def html_tree(self):NEWLINE if not self.root.get('prepTime'):NEWLINE prep = xml2rfc.PrepToolWriter(self.xmlrfc, options=self.options, date=self.options.date, liberal=True, keep_pis=[xml2rfc.V3_PI_TARGET])NEWLINE tree = prep.prep()NEWLINE self.tree = treeNEWLINE self.root = self.tree.getroot()NEWLINE html_tree = self.render(None, self.root)NEWLINE html_tree = self.post_process(html_tree)NEWLINE return html_treeNEWLINENEWLINE def html(self, html_tree=None):NEWLINE if html_tree is None:NEWLINE html_tree = self.html_tree()NEWLINE # 6.1. DOCTYPENEWLINE # NEWLINE # The DOCTYPE of the document is "html", which declares that theNEWLINE # document is compliant with HTML5. The document will start withNEWLINE # exactly this string:NEWLINE # NEWLINE # <!DOCTYPE html>NEWLINE html = lxml.etree.tostring(html_tree, method='html', encoding='unicode', pretty_print=True, doctype="<!DOCTYPE html>")NEWLINE html = re.sub(r'[\x00-\x09\x0B-\x1F]+', ' ', html)NEWLINE return htmlNEWLINENEWLINE def write(self, filename):NEWLINE self.filename = filenameNEWLINENEWLINE """Write the document to a file """NEWLINE html_tree = self.html_tree()NEWLINENEWLINE # Check for duplicate IDsNEWLINE dups = set(find_duplicate_html_ids(html_tree)) - self.duplicate_html_idsNEWLINE for attr, id, e in dups:NEWLINE self.warn(self.root[-1], 'Duplicate %s="%s" found in generated HTML.' % (attr, id, ))NEWLINENEWLINE if self.errors:NEWLINE log.write("Not creating output file due to errors (see above)")NEWLINE returnNEWLINENEWLINE # Use lxml's built-in serializationNEWLINE with open(filename, 'w', encoding='utf-8') as file:NEWLINE text = self.html(html_tree)NEWLINE file.write(text)NEWLINENEWLINE if not self.options.quiet:NEWLINE log.write('Created file', filename)NEWLINENEWLINENEWLINE def render(self, h, x):NEWLINE res = NoneNEWLINE if x.tag in (lxml.etree.PI, lxml.etree.Comment):NEWLINE tail = x.tail if x.tail and x.tail.strip() else ''NEWLINE if len(h):NEWLINE last = h[-1]NEWLINE last.tail = (last.tail or '') + tailNEWLINE else:NEWLINE h.text = (h.text or '') + tailNEWLINE else:NEWLINE func_name = "render_%s" % (x.tag.lower(),)NEWLINE func = getattr(self, func_name, None)NEWLINE if func == None:NEWLINE func = self.default_rendererNEWLINE if x.tag in self.__class__.deprecated_element_tags:NEWLINE self.warn(x, "Was asked to render a deprecated element: <%s>", (x.tag, ))NEWLINE elif not x.tag in seen:NEWLINE self.warn(x, "No renderer for <%s> found" % (x.tag, ))NEWLINE seen.add(x.tag)NEWLINE res = func(h, x)NEWLINE return resNEWLINENEWLINENEWLINE def default_renderer(self, h, x):NEWLINE hh = add(x.tag, h, x)NEWLINE for c in x.getchildren():NEWLINE self.render(hh, c)NEWLINE return hhNEWLINENEWLINE def skip_renderer(self, h, x):NEWLINE part = self.partNEWLINE for c in x.getchildren():NEWLINE self.part = partNEWLINE self.render(h, c)NEWLINENEWLINE def address_line_renderer(self, h, x, classes=None):NEWLINE if x.text:NEWLINE div = build.div(build.span(x.text.strip(), classes=classes))NEWLINE h.append(div)NEWLINE else:NEWLINE div = NoneNEWLINE return divNEWLINENEWLINE def inline_text_renderer(self, h, x):NEWLINE h.text = x.textNEWLINE for c in x.getchildren():NEWLINE self.render(h, c)NEWLINE h.tail = x.tailNEWLINENEWLINE def null_renderer(self, h, x):NEWLINE return NoneNEWLINENEWLINE def maybe_add_pilcrow(self, e):NEWLINE if len(e.xpath('.//*[@class="pilcrow"]')) == 0:NEWLINE id = e.get('id')NEWLINE if id:NEWLINE add.a(e, None, pilcrow, classes='pilcrow', href='#%s'%id)NEWLINE else:NEWLINE self.warn(e, 'Tried to add a pilcrow to <%s>, but found no "id" attribute' % e.tag)NEWLINENEWLINE # --- element rendering functions ------------------------------------------NEWLINENEWLINE def render_rfc(self, h, x):NEWLINE self.part = x.tagNEWLINE # 6.2. Root ElementNEWLINE # NEWLINE # The root element of the document is <html>. This element includes aNEWLINE # "lang" attribute, whose value is a language tag, as discussed inNEWLINE # [RFC5646], that describes the natural language of the document. TheNEWLINE # language tag to be included is "en". The class of the <html> elementNEWLINE # will be copied verbatim from the XML <rfc> element's <front>NEWLINE # element's <seriesInfo> element's "name" attributes (separated byNEWLINE # spaces; see Section 2.47.3 of [RFC7991]), allowing CSS to style RFCsNEWLINE # and Internet-Drafts differently from one another (if needed):NEWLINE # NEWLINE # <html lang="en" class="RFC">NEWLINENEWLINE classes = ' '.join( i.get('name') for i in x.xpath('./front/seriesInfo') )NEWLINE #NEWLINE html = h if h != None else build.html(classes=classes, lang='en')NEWLINE self.html_root = htmlNEWLINENEWLINE # 6.3. <head> ElementNEWLINE # NEWLINE # The root <html> will contain a <head> element that contains theNEWLINE # following elements, as needed.NEWLINENEWLINE head = add.head(html, None)NEWLINENEWLINE # 6.3.1. Charset DeclarationNEWLINE # NEWLINE # In order to be correctly processed by browsers that load the HTMLNEWLINE # using a mechanism that does not provide a valid content-type orNEWLINE # charset (such as from a local file system using a "file:" URL), theNEWLINE # HTML <head> element contains a <meta> element, whose "charset"NEWLINE # attribute value is "utf-8":NEWLINE # NEWLINE # <meta charset="utf-8">NEWLINENEWLINE add.meta(head, None, charset='utf-8')NEWLINE add.meta(head, None, name="scripts", content=x.get('scripts'))NEWLINENEWLINE # 6.3.2. Document TitleNEWLINE # NEWLINE # The contents of the <title> element from the XML source will beNEWLINE # placed inside an HTML <title> element in the header.NEWLINENEWLINE title = x.find('./front/title')NEWLINE text = title.textNEWLINE if self.options.rfc:NEWLINE text = ("RFC %s: " % self.root.get('number')) + textNEWLINE add.title(head, None, text)NEWLINENEWLINE # 6.3.3. Document MetadataNEWLINE # NEWLINE # The following <meta> elements will be included:NEWLINE # NEWLINE # o author - one each for the each of the "fullname"s andNEWLINE # "asciiFullname"s of all of the <author>s from the <front> of theNEWLINE # XML sourceNEWLINE for a in x.xpath('./front/author'):NEWLINE if not a.get('role') == 'contributor':NEWLINE name = full_author_name_expansion(a) or full_org_name(a)NEWLINE add.meta(head, None, name='author', content=name )NEWLINENEWLINE # o description - the <abstract> from the XML sourceNEWLINENEWLINE abstract = x.find('./front/abstract')NEWLINE if abstract != None:NEWLINE abstract_text = ' '.join(abstract.itertext())NEWLINE add.meta(head, None, name='description', content=abstract_text)NEWLINENEWLINE # o generator - the name and version number of the software used toNEWLINE # create the HTMLNEWLINENEWLINE generator = "%s %s" % (xml2rfc.NAME, xml2rfc.__version__)NEWLINE add.meta(head, None, name='generator', content=generator)NEWLINE NEWLINE # o keywords - comma-separated <keyword>s from the XML sourceNEWLINENEWLINE for keyword in x.xpath('./front/keyword'):NEWLINE add.meta(head, None, name='keyword', content=keyword.text)NEWLINENEWLINE # For example:NEWLINE # NEWLINE # <meta name="author" content="Joe Hildebrand">NEWLINE # <meta name="author" content="JOE HILDEBRAND">NEWLINE # <meta name="author" content="Heather Flanagan">NEWLINE # <meta name="description" content="This document defines...">NEWLINE # <meta name="generator" content="xmljade v0.2.4">NEWLINE # <meta name="keywords" content="html,css,rfc">NEWLINE # NEWLINE # Note: the HTML <meta> tag does not contain a closing slash.NEWLINE # NEWLINE # 6.3.4. Link to XML SourceNEWLINE # NEWLINE # The <head> element contains a <link> tag, with "rel" attribute ofNEWLINE # "alternate", "type" attribute of "application/rfc+xml", and "href"NEWLINE # attribute pointing to the prepared XML source that was used toNEWLINE # generate this document.NEWLINE # NEWLINE # <link rel="alternate" type="application/rfc+xml" href="source.xml">NEWLINENEWLINE add.link(head, None, rel='alternate', type='application/rfc+xml', href=self.xmlrfc.source)NEWLINENEWLINE # 6.3.5. Link to LicenseNEWLINE # NEWLINE # The <head> element contains a <link> tag, with "rel" attribute ofNEWLINE # "license" and "href" attribute pointing to the an appropriateNEWLINE # copyright license for the document.NEWLINE # NEWLINE # <link rel="license"NEWLINE # href="https://trustee.ietf.org/trust-legal-provisions.html">NEWLINENEWLINE add.link(head, None, rel='license', href="#copyright")NEWLINENEWLINE # 6.3.6. StyleNEWLINE # NEWLINE # The <head> element contains an embedded CSS in a <style> element.NEWLINE # The styles in the style sheet are to be set consistently betweenNEWLINE # documents by the RFC Editor, according to the best practices of theNEWLINE # day.NEWLINE # NEWLINE # To ensure consistent formatting, individual style attributes shouldNEWLINE # not be used in the main portion of the document.NEWLINE # NEWLINE # Different readers of a specification will desire different formattingNEWLINE # when reading the HTML versions of RFCs. To facilitate this, theNEWLINE # <head> element also includes a <link> to a style sheet in the sameNEWLINE # directory as the HTML file, named "rfc-local.css". Any formatting inNEWLINE # the linked style sheet will override the formatting in the includedNEWLINE # style sheet. For example:NEWLINE # NEWLINE # <style>NEWLINE # body {}NEWLINE # ...NEWLINE # </style>NEWLINE # <link rel="stylesheet" type="text/css" href="rfc-local.css">NEWLINENEWLINE cssin = self.options.css or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'xml2rfc.css')NEWLINE with open(cssin, encoding='utf-8') as f:NEWLINE css = f.read()NEWLINENEWLINE if self.options.external_css:NEWLINE cssout = os.path.join(os.path.dirname(self.filename), 'xml2rfc.css')NEWLINE with open(cssout, 'w', encoding='utf-8') as f:NEWLINE f.write(css)NEWLINE add.link(head, None, rel="stylesheet", href="xml2rfc.css", type="text/css")NEWLINE elif self.options.no_css:NEWLINE passNEWLINE else:NEWLINE add.style(head, None, css, type="text/css")NEWLINE add.link(head, None, rel="stylesheet", href="rfc-local.css", type="text/css")NEWLINENEWLINE # 6.3.7. LinksNEWLINE # NEWLINE # Each <link> element from the XML source is copied into the HTMLNEWLINE # header. Note: the HTML <link> element does not include a closingNEWLINE # slash.NEWLINENEWLINE for link in x.xpath('./link'):NEWLINE head.append(link)NEWLINENEWLINE body = add.body(html, None)NEWLINENEWLINE # 6.4. Page Headers and FootersNEWLINE # NEWLINE # In order to simplify printing by HTML renderers that implementNEWLINE # [W3C.WD-css3-page-20130314], a hidden HTML <table> tag of classNEWLINE # "ears" is added at the beginning of the HTML <body> tag, containingNEWLINE # HTML <thead> and <tfoot> tags, each of which contains an HTML <tr>NEWLINE # tag, which contains three HTML <td> tags with class "left", "center",NEWLINE # and "right", respectively.NEWLINE # NEWLINE # The <thead> corresponds to the top of the page, the <tfoot> to theNEWLINE # bottom. The string "[Page]" can be used as a placeholder for theNEWLINE # page number. In practice, this must always be in the <tfoot>'s rightNEWLINE # <td>, and no control of the formatting of the page number is implied.NEWLINE #NEWLINE # <table class="ears">NEWLINE # <thead>NEWLINE # <tr>NEWLINE # <td class="left">Internet-Draft</td>NEWLINE # <td class="center">HTML RFC</td>NEWLINE # <td class="right">March 2016</td>NEWLINE # </tr>NEWLINE # </thead>NEWLINE # <tfoot>NEWLINE # <tr>NEWLINE # <td class="left">Hildebrand</td>NEWLINE # <td class="center">Expires September 2, 2016</td>NEWLINE # <td class="right">[Page]</td>NEWLINE # </tr>NEWLINE # </tfoot>NEWLINE # </table>NEWLINENEWLINE body.append(NEWLINE build.table(NEWLINE build.thead(NEWLINE build.tr(NEWLINE build.td(self.page_top_left(), classes='left'),NEWLINE build.td(self.page_top_center(), classes='center'),NEWLINE build.td(self.page_top_right(), classes='right'),NEWLINE ),NEWLINE ),NEWLINE build.tfoot(NEWLINE build.tr(NEWLINE build.td(self.page_bottom_left(), classes='left'),NEWLINE build.td(self.page_bottom_center(), classes='center'),NEWLINE build.td("[Page]", classes='right'),NEWLINE ),NEWLINE ),NEWLINE classes='ears',NEWLINE )NEWLINE )NEWLINENEWLINE for c in [ e for e in [ x.find('front'), x.find('middle'), x.find('back') ] if e != None]:NEWLINE self.part = c.tagNEWLINE self.render(body, c)NEWLINENEWLINE jsin = self.options.css or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'xml2rfc.js')NEWLINE with open(jsin, encoding='utf-8') as f:NEWLINE js = f.read()NEWLINE add.script(body, None, js)NEWLINENEWLINE return htmlNEWLINENEWLINE # 9.1. <abstract>NEWLINE # NEWLINE # The abstract is rendered in a similar fashion to a <section> withNEWLINE # anchor="abstract" and <name>Abstract</name>, but without a sectionNEWLINE # number.NEWLINE # NEWLINE # <section id="abstract">NEWLINE # <h2><a href="#abstract" class="selfRef">Abstract</a></h2>NEWLINE # <p id="s-abstract-1">This document defines...NEWLINE # <a href="#s-abstract-1" class="pilcrow">&para;</a>NEWLINE # </p>NEWLINE # </section>NEWLINE # NEWLINENEWLINE def render_abstract(self, h, x):NEWLINE if self.part == 'front':NEWLINE section = add.section(h, x)NEWLINE section.append( build.h2( build.a('Abstract', classes='selfRef', href="#abstract"), id="abstract"))NEWLINE for c in x.getchildren():NEWLINE self.render(section, c)NEWLINE return sectionNEWLINE else:NEWLINE return NoneNEWLINENEWLINE # 9.2. <address>NEWLINE # NEWLINE # This element is used in the Authors' Addresses section. It isNEWLINE # rendered as an HTML <address> tag of class "vcard". If none of theNEWLINE # descendant XML elements has an "ascii" attribute, the <address> HTMLNEWLINE # tag includes the HTML rendering of each of the descendant XMLNEWLINE # elements. Otherwise, the <address> HTML tag includes an HTML <div>NEWLINE # tag of class "ascii" (containing the HTML rendering of the ASCIINEWLINE # variants of each of the descendant XML elements), an HTML <div> tagNEWLINE # of class "alternative-contact", (containing the text "AlternateNEWLINE # contact information:"), and an HTML <div> tag of class "non-ascii"NEWLINE # (containing the HTML rendering of the non-ASCII variants of each ofNEWLINE # the descendant XML elements).NEWLINE # NEWLINE # Note: the following example shows some ASCII equivalents that are theNEWLINE # same as their nominal equivalents for clarity; normally, the ASCIINEWLINE # equivalents would not be included for these cases.NEWLINE # NEWLINE # <address class="vcard">NEWLINE # <div class="ascii">NEWLINE # <div class="nameRole"><span class="fn">Joe Hildebrand</span>NEWLINE # (<span class="role">editor</span>)</div>NEWLINE # <div class="org">Cisco Systems, Inc.</div>NEWLINE # </div>NEWLINE # <div class="alternative-contact">NEWLINE # Alternate contact information:NEWLINE # </div>NEWLINE # <div class="non-ascii">NEWLINE # <div class="nameRole"><span class="fn">Joe Hildebrand</span>NEWLINE # (<span class="role">editor</span>)</div>NEWLINE # <div class="org">Cisco Systems, Inc.</div>NEWLINE # </div>NEWLINE # </address>NEWLINENEWLINE ## The above text is reasonable for author name and org, but nonsense forNEWLINE ## the <address> element. The following text will be used:NEWLINE ##NEWLINE ## The <address> element will be rendered as a sequence of <div> elements,NEWLINE ## each corresponding to a child element of <address>. Element classesNEWLINE ## will be taken from hcard, as specified on http://microformats.org/wiki/hcardNEWLINE ## NEWLINE ## <address class="vcard">NEWLINE ##NEWLINE ## <!-- ... name, role, and organization elements ... -->NEWLINE ##NEWLINE ## <div class="adr">NEWLINE ## <div class="street-address">1 Main Street</div>NEWLINE ## <div class="street-address">Suite 1</div>NEWLINE ## <div class="city-region-code">NEWLINE ## <span class="city">Denver</span>,&nbsp;NEWLINE ## <span class="region">CO</span>&nbsp;NEWLINE ## <span class="postal-code">80202</span>NEWLINE ## </div>NEWLINE ## <div class="country-name">USA</div>NEWLINE ## </div>NEWLINE ## <div class="tel">NEWLINE ## <span>Phone:</span>NEWLINE ## <a class="tel" href="tel:+1-720-555-1212">+1-720-555-1212</a>NEWLINE ## </div>NEWLINE ## <div class="fax">NEWLINE ## <span>Fax:</span>NEWLINE ## <span class="tel">+1-303-555-1212</span>NEWLINE ## </div>NEWLINE ## <div class="email">NEWLINE ## <span>Email:</span>NEWLINE ## <a class="email" href="mailto:author@example.com">author@example.com</a>NEWLINE ## </div>NEWLINE ## </address>NEWLINE render_address = skip_rendererNEWLINENEWLINE # 9.3. <annotation>NEWLINE # NEWLINE # This element is rendered as the text ", " (a comma and a space)NEWLINE # followed by a <span> of class "annotation" at the end of aNEWLINE # <reference> element, the <span> containing appropriately transformedNEWLINE # elements from the children of the <annotation> tag.NEWLINE # NEWLINE # <span class="annotation">Some <em>thing</em>.</span>NEWLINE def render_annotation(self, h, x):NEWLINE span = add.span(h, x, classes='annotation')NEWLINE for c in x.getchildren():NEWLINE self.render(span, c)NEWLINE return spanNEWLINENEWLINE # 9.4. <area>NEWLINE # NEWLINE # Not currently rendered to HTML.NEWLINE # NEWLINENEWLINE def render_artset(self, h, x):NEWLINE preflist = ['svg', 'binary-art', 'ascii-art', ]NEWLINE for t in preflist:NEWLINE for a in x.xpath('./artwork[@type="%s"]' % t):NEWLINE artwork = self.render(h, a)NEWLINE return artworkNEWLINE else:NEWLINE artwork = self.render(h, x[0])NEWLINE return artworkNEWLINENEWLINE # 9.5. <artwork>NEWLINE # NEWLINE # Artwork can consist of either inline text or SVG. If the artwork isNEWLINE # not inside a <figure> element, a pilcrow (Section 5.2) is included.NEWLINE # Inside a <figure> element, the figure title serves the purpose of theNEWLINE # pilcrow. If the "align" attribute has the value "right", the CSSNEWLINE # class "alignRight" will be added. If the "align" attribute has theNEWLINE # value "center", the CSS class "alignCenter" will be added.NEWLINE def render_artwork(self, h, x):NEWLINE type = x.get('type')NEWLINE align = x.get('align', 'left')NEWLINENEWLINE # 9.5.1. Text ArtworkNEWLINE # NEWLINE # Text artwork is rendered inside an HTML <pre> element, which isNEWLINE # contained by a <div> element for consistency with SVG artwork. NoteNEWLINE # that CDATA blocks are not a part of HTML, so angle brackets andNEWLINE # ampersands (i.e., <, >, and &) must be escaped as &lt;, &gt;, andNEWLINE # &amp;, respectively.NEWLINE # NEWLINE # The <div> element will have CSS classes of "artwork", "art-text", andNEWLINE # "art-" prepended to the value of the <artwork> element's "type"NEWLINE # attribute, if it exists.NEWLINE # NEWLINE # <div class="artwork art-text art-ascii-art" id="s-1-2">NEWLINE # <pre>NEWLINE # ______________NEWLINE # &lt; hello, world &gt;NEWLINE # --------------NEWLINE # \ ^__^NEWLINE # \ (oo)\_______NEWLINE # (__)\ )\/\NEWLINE # ||----w |NEWLINE # || ||NEWLINE # </pre>NEWLINE # <a class="pilcrow" href="#s-1-2">&para;</a>NEWLINE # </div>NEWLINE if type not in ['svg', 'binary-art', ]:NEWLINE if not x.text or not x.text.strip():NEWLINE self.err(x, 'Expected ascii-art artwork for <artwork type="%s">, but found %s...' % (x.get('type',''), lxml.etree.tostring(x)[:128]))NEWLINE return NoneNEWLINE else:NEWLINE pre = build.pre(x.text.expandtabs())NEWLINE classes = 'artwork art-text align%s' % align.capitalize()NEWLINE if type and type != 'text':NEWLINE classes += ' art-%s' % typeNEWLINE div = add.div(h, x, pre, classes=classes)NEWLINE div.text = NoneNEWLINE if x.getparent().tag != 'figure':NEWLINE self.maybe_add_pilcrow(div)NEWLINE return divNEWLINE NEWLINE # 9.5.2. SVG ArtworkNEWLINE # NEWLINE # SVG artwork will be included inline. The SVG is wrapped in a <div>NEWLINE # element with CSS classes "artwork" and "art-svg".NEWLINE # NEWLINE # If the SVG "artwork" element is a child of <figure> and the artworkNEWLINE # is specified as align="right", an empty HTML <span> element is addedNEWLINE # directly after the <svg> element, in order to get right alignment toNEWLINE # work correctly in HTML rendering engines that do not support theNEWLINE # flex-box model.NEWLINE # NEWLINE # Note: the "alt" attribute of <artwork> is not currently used for SVG;NEWLINE # instead, the <title> and <desc> tags are used in the SVG.NEWLINE # NEWLINE # <div class="artwork art-svg" id="s-2-17">NEWLINE # <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">NEWLINE # <desc>Alt text here</desc>NEWLINE # <circleNEWLINE # cx="50" cy="50" r="40"NEWLINE # stroke="green" stroke-width="4" fill="yellow" />NEWLINE # </svg>NEWLINE # <a href="#s-2-17" class="pilcrow">&para;</a>NEWLINE # </div>NEWLINE elif type == 'svg':NEWLINE classes = 'artwork art-svg align%s' % align.capitalize()NEWLINE div = add.div(h, x, classes=classes)NEWLINE div.text = NoneNEWLINE src = x.get('src')NEWLINE if src:NEWLINE svgfile = x.get('originalSrc') or x.get('src')[:37]+' ...'NEWLINE if not src.startswith('data:'):NEWLINE self.err(x, "Internal error: Got an <artwork> src: attribute that did not start with 'data:' after prepping")NEWLINE try:NEWLINE f = urlopen(src)NEWLINE data = f.read()NEWLINE svg = lxml.etree.fromstring(data)NEWLINE except IOError as e:NEWLINE self.err(x, str(e))NEWLINE svg = NoneNEWLINE else:NEWLINE svg = x.find('svg:svg', namespaces=namespaces)NEWLINE svgfile = "inline:%s ..." % lxml.etree.tostring(svg)[:31]NEWLINE if svg == None:NEWLINE self.err(x, 'Expected <svg> content inside <artwork type="svg">, but did not find it:\n %s ...' % (lxml.etree.tostring(x)[:256], ))NEWLINE return NoneNEWLINE # For w3.org validator compatibilityNEWLINE if svg.get('attribute', None):NEWLINE del svg.attrib['version']NEWLINE #NEWLINE # Deal with possible svg scaling issues.NEWLINE vbox = svg.get('viewBox')NEWLINE svgw = maybefloat(svg.get('width'))NEWLINE svgh = maybefloat(svg.get('height'))NEWLINE try:NEWLINE if vbox:NEWLINE xo,yo,w,h = re.split(',? +', vbox.strip('()'))NEWLINE # rewrite viewbox in the simplest syntax, in case needed for pdf libNEWLINE svg.set('viewBox', '%s %s %s %s' % (xo,yo,w,h))NEWLINE if not (svgw and svgh):NEWLINE svgw = float(w)-float(xo)NEWLINE svgh = float(h)-float(yo)NEWLINE else:NEWLINE if svgw and svgh:NEWLINE svg.set('viewBox', '0 0 %s %s' % (svgw, svgh))NEWLINE else:NEWLINE self.err(x, "Cannot place SVG properly when neither viewBox nor width and height is available") NEWLINE return NoneNEWLINE except ValueError as e:NEWLINE self.err(x, "Error when calculating SVG size: %s" % e)NEWLINE imgw = 660 if self.options.image_svg else 724NEWLINE if imgw < svgw:NEWLINE svg.set('width', str(svgw/svgw*imgw))NEWLINE svg.set('height', str(svgh/svgw*imgw))NEWLINE #NEWLINE if self.options.image_svg:NEWLINE data = build_dataurl('image/svg+xml', lxml.etree.tostring(svg))NEWLINE add.img(div, None, src=data, alt=x.get('alt'))NEWLINE else:NEWLINE div.append(svg)NEWLINE if x.getparent().tag != 'figure':NEWLINE self.maybe_add_pilcrow(div)NEWLINE else:NEWLINE if x.get('align') == 'right':NEWLINE add.span(div, None)NEWLINE #NEWLINE dups = set(find_duplicate_html_ids(self.html_root))NEWLINE new = dups - self.duplicate_html_idsNEWLINE for attr, id, e in new:NEWLINE self.warn(x, 'Duplicate attribute %s="%s" found after including svg from %s. This can cause problems with some browsers.' % (attr, id, svgfile))NEWLINE self.duplicate_html_ids = self.duplicate_html_ids | dupsNEWLINENEWLINE # 9.5.3. Other ArtworkNEWLINE # NEWLINE # Other artwork will have a "src" attribute that uses the "data" URINEWLINE # scheme defined in [RFC2397]. Such artwork is rendered in an HTMLNEWLINE # <img> element. Note: the HTML <img> element does not have a closingNEWLINE # slash.NEWLINE # NEWLINE # Note: such images are not yet allowed in RFCs even though the formatNEWLINE # supports them. A limited set of "data:" mediatypes for artwork mayNEWLINE # be allowed in the future.NEWLINE # NEWLINE # <div class="artwork art-logo" id="s-2-58">NEWLINE # <img alt="IETF logo"NEWLINE # src="data:image/gif;charset=utf-8;base64,...">NEWLINE # <a class="pilcrow" href="#s-2-58">&para;</a>NEWLINE # </div>NEWLINE elif type == 'binary-art':NEWLINE div = add.div(h, x, classes='artwork art-svg')NEWLINE data = x.get('src')NEWLINE if data:NEWLINE del div.attrib['src']NEWLINE add.img(div, None, src=data)NEWLINE else:NEWLINE self.err(x, 'Expected <img> data given by src="" for <artwork type="binary-art">, but did not find it: %s ...' % (lxml.etree.tostring(x)[:128], ))NEWLINE if x.getparent().tag != 'figure':NEWLINE self.maybe_add_pilcrow(div)NEWLINENEWLINE # 9.6. <aside>NEWLINE # NEWLINE # This element is rendered as an HTML <aside> element, with all childNEWLINE # content appropriately transformed.NEWLINE # NEWLINE # <aside id="s-2.1-2">NEWLINE # <p id="s-2.1-2.1">NEWLINE # A little more than kin, and less than kind.NEWLINE # <a class="pilcrow" href="#s-2.1-2.1">&para;</a>NEWLINE # </p>NEWLINE # </aside>NEWLINE render_aside = default_rendererNEWLINE NEWLINENEWLINE # NEWLINE # 9.7. <author>NEWLINE # NEWLINE # The <author> element is used in several places in the output.NEWLINE # Different rendering is used for each.NEWLINE def render_author(self, h, x):NEWLINE if len(x)==0 and len(x.attrib)==0:NEWLINE return NoneNEWLINENEWLINE # 9.7.1. Authors in Document InformationNEWLINE # NEWLINE # As seen in the Document Information at the beginning of the HTML,NEWLINE # each document author is rendered as an HTML <div> tag of classNEWLINE # "author".NEWLINE # NEWLINE # Inside the <div class="author"> HTML tag, the author's initials andNEWLINE # surname (or the fullname, if it exists and the others do not) will beNEWLINE # rendered in an HTML <div> tag of class "author-name". If theNEWLINE # <author> contains "asciiInitials" and "asciiSurname" attributes, orNEWLINE # contains as "asciiFullname" attribute, the author's name is renderedNEWLINE # twice, with the first being the non-ASCII version, wrapped in an HTMLNEWLINE # <span> tag of class "non-ascii", followed by the ASCII versionNEWLINE # wrapped in an HTML <span> tag of class "ascii", wrapped inNEWLINE # parentheses. If the <author> has a "role" attribute of "editor", theNEWLINE # <div class="author-name"> will also contain the text ", " (comma,NEWLINE # space), followed by an HTML <span> tag of class "editor", whichNEWLINE # contains the text "Ed.".NEWLINE # NEWLINE # If the <author> element contains an <organization> element, it isNEWLINE # also rendered inside the <div class="author"> HTML tag.NEWLINE # NEWLINE # <div class="author">NEWLINE # <div class="author-name">NEWLINE # H. Flanagan,NEWLINE # <span class="editor">Ed.</span></div>NEWLINE # <div class="org">Test Org</div>NEWLINE # </div>NEWLINE # <div class="author">NEWLINE # <div class="author-name">NEWLINE # <span class="non-ascii">Hildebrand</span>NEWLINE # (<span class="ascii">HILDEBRAND</span>)NEWLINE # </div>NEWLINE # <div class="org">NEWLINE # <span class="non-ascii">Test Org</span>NEWLINE # (<span class="ascii">TEST ORG</span>)NEWLINE # </div>NEWLINE # </div>NEWLINE if self.part == 'front':NEWLINE name, ascii = short_author_name_set(x)NEWLINE role = short_author_role(x)NEWLINE div = add.div(h, x, classes='author')NEWLINE if role:NEWLINE role = build.span(role, classes=x.get('role'))NEWLINE if name:NEWLINE div.append(wrap_ascii('div', '', name, ascii, role, classes='author-name'))NEWLINE o = x.find('organization')NEWLINE if o != None and o.get('showOnFrontPage') == 'true':NEWLINE org, ascii = short_org_name_set(x)NEWLINE if org:NEWLINE div.append(wrap_ascii('div', '', org, ascii, None, classes='org'))NEWLINE return divNEWLINENEWLINE # 9.7.2. Authors of This DocumentNEWLINE # NEWLINE # As seen in the Authors' Addresses section, at the end of the HTML,NEWLINE # each document author is rendered into an HTML <address> element withNEWLINE # the CSS class "vcard".NEWLINE # NEWLINE # The HTML <address> element will contain an HTML <div> with CSS classNEWLINE # "nameRole". That div will contain an HTML <span> element with CSSNEWLINE # class "fn" containing the value of the "fullname" attribute of theNEWLINE # <author> XML element and an HTML <span> element with CSS class "role"NEWLINE # containing the value of the "role" attribute of the <author> XMLNEWLINE # element (if there is a role). Parentheses will surround the <spanNEWLINE # class="role">, if it exists.NEWLINE # NEWLINE # <address class="vcard">NEWLINE # <div class="nameRole">NEWLINE # <span class="fn">Joe Hildebrand</span>NEWLINE # (<span class="role">editor</span>)NEWLINE # </div>NEWLINE # ...NEWLINE # NEWLINE # After the name, the <organization> and <address> child elements ofNEWLINE # the author are rendered inside the HTML <address> tag.NEWLINE # NEWLINE # When the <author> element, or any of its descendant elements, has anyNEWLINE # attribute that starts with "ascii", all of the author information isNEWLINE # displayed twice. The first version is wrapped in an HTML <div> tagNEWLINE # with class "ascii"; this version prefers the ASCII version ofNEWLINE # information, such as "asciiFullname", but falls back on the non-ASCIINEWLINE # version if the ASCII version doesn't exist. The second version isNEWLINE # wrapped in an HTML <div> tag with class "non-ascii"; this versionNEWLINE # prefers the non-ASCII version of information, such as "fullname", butNEWLINE # falls back on the ASCII version if the non-ASCII version does notNEWLINE # exist. Between these two HTML <div>s, a third <div> is inserted,NEWLINE # with class "alternative-contact", containing the text "AlternateNEWLINE # contact information:".NEWLINE # NEWLINE # <address class="vcard">NEWLINE # <div class="ascii">NEWLINE # <div class="nameRole">NEWLINE # <span class="fn">The ASCII name</span>NEWLINE # </div>NEWLINE # </div>NEWLINE # <div class="alternative-contact">NEWLINE # Alternate contact information:NEWLINE # </div>NEWLINE # <div class="non-ascii">NEWLINE # <div class="nameRole">NEWLINE # <span class="fn">The non-ASCII name</span>NEWLINE # (<span class="role">editor</span>)NEWLINE # </div>NEWLINE # </div>NEWLINE # </address>NEWLINE elif self.part == 'back':NEWLINE # ascii will be set only if name has codepoints not in the Latin script blocksNEWLINE name, ascii = full_author_name_set(x)NEWLINE #NEWLINE addr = add.address(h, x, classes='vcard')NEWLINE #NEWLINE address = x.find('./address')NEWLINE postal = x.find('./address/postal')NEWLINE if address is None:NEWLINE address = lxml.etree.Element('address')NEWLINE x.append(address)NEWLINE if postal is None:NEWLINE # We render author name as part of postal, so make sure it's thereNEWLINE address.insert(0, lxml.etree.Element('postal'))NEWLINE if ascii:NEWLINE ascii_div = add.div(addr, None, classes='ascii')NEWLINE for c in x.getchildren():NEWLINE self.render(ascii_div, c)NEWLINE add.div(addr, None, 'Additional contact information:', classes='alternative-contact')NEWLINE nonasc_div = add.div(addr, None, classes='non-ascii')NEWLINE for c in x.getchildren():NEWLINE self.render(nonasc_div, c)NEWLINE else:NEWLINE for c in x.getchildren():NEWLINE self.render(addr, c)NEWLINE return addrNEWLINENEWLINE # 9.7.3. Authors of ReferencesNEWLINE # NEWLINE # In the output generated from a reference element, author tags areNEWLINE # rendered inside an HTML <span> element with CSS class "refAuthor".NEWLINE # See Section 4.8.6.2 of [RFC7322] for guidance on how author names areNEWLINE # to appear.NEWLINE # NEWLINE # <span class="refAuthor">Flanagan, H.</span> andNEWLINE # <span class="refAuthor">N. Brownlee</span>NEWLINE elif self.part == 'references':NEWLINE prev = x.getprevious()NEWLINE next = x.getnext()NEWLINE role = short_author_role(x)NEWLINE if prev == None or prev.tag != 'author':NEWLINE # single autor or the first author in a listNEWLINE name, ascii = ref_author_name_first(x)NEWLINE span = wrap_ascii('span', '', name, ascii, role, classes='refAuthor')NEWLINE elif prev != None and prev.tag == 'author' and next != None and next.tag == 'author':NEWLINE # not first and not last author in a listNEWLINE name, ascii = ref_author_name_first(x)NEWLINE span = wrap_ascii('span', ', ', name, ascii, role, classes='refAuthor')NEWLINE elif prev != None and prev.tag == 'author' and prev.getprevious() != None and prev.getprevious().tag == 'author':NEWLINE # last author in a list of authorsNEWLINE name, ascii = ref_author_name_last(x)NEWLINE span = wrap_ascii('span', ', and ', name, ascii, role, classes='refAuthor')NEWLINE elif prev != None and prev.tag == 'author':NEWLINE # second author of twoNEWLINE name, ascii = ref_author_name_last(x)NEWLINE span = wrap_ascii('span', ' and ', name, ascii, role, classes='refAuthor')NEWLINE else:NEWLINE self.err(x, "Internal error, unexpected state when rendering authors.")NEWLINE h.append(span)NEWLINE return spanNEWLINENEWLINE else:NEWLINE self.err(x, "Did not expect to be asked to render <%s> while in <%s>" % (x.tag, x.getparent().tag))NEWLINENEWLINE # 9.8. <back>NEWLINE # NEWLINE # If there is exactly one <references> child, render that child in aNEWLINE # similar way to a <section>. If there are more than one <references>NEWLINE # children, render as a <section> whose name is "References",NEWLINE # containing a <section> for each <references> child.NEWLINE # NEWLINE # After any <references> sections, render each <section> child ofNEWLINE # <back> as an appendix.NEWLINE # NEWLINE # <section id="n-references">NEWLINE # <h2 id="s-2">NEWLINE # <a class="selfRef" href="#s-2">2.</a>NEWLINE # <a class="selfRef" href="#n-references">References</a>NEWLINE # </h2>NEWLINE # <section id="n-normative">NEWLINE # <h3 id="s-2.1">NEWLINE # <a class="selfRef" href="#s-2.1">2.1.</a>NEWLINE # <a class="selfRef" href="#n-normative">Normative</a>NEWLINE # </h3>NEWLINE # <dl class="reference"></dl>NEWLINE # </section>NEWLINE # <section id="n-informational">NEWLINE # <h3 id="s-2.2">NEWLINE # <a class="selfRef" href="#s-2.2">2.2.</a>NEWLINE # <a class="selfRef" href="#n-informational">Informational</a>NEWLINE # </h3>NEWLINE # <dl class="reference"></dl>NEWLINE # </section>NEWLINE # </section>NEWLINE # <section id="n-unimportant">NEWLINE # <h2 id="s-A">NEWLINE # <a class="selfRef" href="#s-A">Appendix A.</a>NEWLINE # <a class="selfRef" href="#n-unimportant">Unimportant</a>NEWLINE # </h2>NEWLINE # </section>NEWLINE render_back = skip_rendererNEWLINENEWLINE # 9.9. <bcp14>NEWLINE # NEWLINE # This element marks up words like MUST and SHOULD [BCP14] with an HTMLNEWLINE # <span> element with the CSS class "bcp14".NEWLINE # NEWLINE # You <span class="bcp14">MUST</span> be joking.NEWLINE def render_bcp14(self, h, x):NEWLINE return add.span(h, x, classes='bcp14')NEWLINENEWLINE # 9.10. <blockquote>NEWLINE # NEWLINE # This element renders in a way similar to the HTML <blockquote>NEWLINE # element. If there is a "cite" attribute, it is copied to the HTMLNEWLINE # "cite" attribute. If there is a "quoteFrom" attribute, it is placedNEWLINE # inside a <cite> element at the end of the quote, with an <a> elementNEWLINE # surrounding it (if there is a "cite" attribute), linking to the citedNEWLINE # URL.NEWLINE # NEWLINE # If the <blockquote> does not contain another element that gets aNEWLINE # pilcrow (Section 5.2), a pilcrow is added.NEWLINE # NEWLINE # Note that the "&mdash;" at the beginning of the <cite> element shouldNEWLINE # be a proper emdash, which is difficult to show in the display of theNEWLINE # current format.NEWLINE # NEWLINE # <blockquote id="s-1.2-1"NEWLINE # cite="http://...">NEWLINE # <p id="s-1.2-2">Four score and seven years ago our fathersNEWLINE # brought forth on this continent, a new nation, conceivedNEWLINE # in Liberty, and dedicated to the proposition that all menNEWLINE # are created equal.NEWLINE # <a href="#s-1.2-2" class="pilcrow">&para;</a>NEWLINE # </p>NEWLINE # <cite>&mdash; <a href="http://...">Abraham Lincoln</a></cite>NEWLINE # </blockquote>NEWLINE def render_blockquote(self, h, x):NEWLINE frm = x.get('quotedFrom')NEWLINE cite = x.get('cite')NEWLINE quote = add.blockquote(h, x)NEWLINE if cite:NEWLINE quote.set('cite', cite)NEWLINE for c in x.getchildren():NEWLINE self.render(quote, c)NEWLINE self.maybe_add_pilcrow(quote)NEWLINE if frm:NEWLINE if cite:NEWLINE frm = build.a(frm, href=cite)NEWLINE add.cite(quote, None, mdash, ' ', frm)NEWLINE return quoteNEWLINENEWLINE # 9.11. <boilerplate>NEWLINE # NEWLINE # The Status of This Memo and the Copyright statement, togetherNEWLINE # commonly referred to as the document boilerplate, appear after theNEWLINE # Abstract. The children of the input <boilerplate> element areNEWLINE # treated in a similar fashion to unnumbered sections.NEWLINE # NEWLINE # <section id="status-of-this-memo">NEWLINE # <h2 id="s-boilerplate-1">NEWLINE # <a href="#status-of-this-memo" class="selfRef">NEWLINE # Status of this Memo</a>NEWLINE # </h2>NEWLINE # <p id="s-boilerplate-1-1">This Internet-Draft is submitted in fullNEWLINE # conformance with the provisions of BCP 78 and BCP 79.NEWLINE # <a href="#s-boilerplate-1-1" class="pilcrow">&para;</a>NEWLINE # </p>NEWLINE # ...NEWLINE render_boilerplate = skip_rendererNEWLINENEWLINE # 9.12. <br>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart. Note: inNEWLINE # HTML, <br> does not have a closing slash.NEWLINE ## Removed from schemaNEWLINE def render_br(self, h, x):NEWLINE return add.br(h, x)NEWLINENEWLINE # NEWLINE # 9.13. <city>NEWLINE # NEWLINE # This element is rendered as a <span> element with CSS classNEWLINE # "locality".NEWLINE # NEWLINE # <span class="locality">Guilford</span>NEWLINE def render_city(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='locality')NEWLINENEWLINE def render_cityarea(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='locality')NEWLINENEWLINE # NEWLINE # 9.14. <code>NEWLINE # NEWLINE # This element is rendered as a <span> element with CSS class "postal-NEWLINE # code".NEWLINE # NEWLINE # <span class="postal-code">GU16 7HF<span>NEWLINE def render_code(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='postal-code')NEWLINENEWLINE def render_sortingcode(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='postal-code')NEWLINENEWLINE # 9.15. <country>NEWLINE # NEWLINE # This element is rendered as a <div> element with CSS class "country-NEWLINE # name".NEWLINE # NEWLINE # <div class="country-name">England</div>NEWLINE def render_country(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='country-name')NEWLINENEWLINE # 9.16. <cref>NEWLINE # NEWLINE # This element is rendered as a <span> element with CSS class "cref".NEWLINE # Any anchor is copied to the "id" attribute. If there is a sourceNEWLINE # given, it is contained inside the "cref" <span> element with anotherNEWLINE # <span> element of class "crefSource".NEWLINE # NEWLINE # <span class="cref" id="crefAnchor">Just a brief commentNEWLINE # about something that we need to remember later.NEWLINE # <span class="crefSource">--life</span></span>NEWLINE def render_cref(self, h, x):NEWLINE span = add.span(h, x, classes='cref')NEWLINE disp = x.get('display') == 'true'NEWLINE if disp:NEWLINE for c in x.getchildren():NEWLINE self.render(span, c)NEWLINE source = x.get('source')NEWLINE if source:NEWLINE add.span(span, None, source, classes='crefSource')NEWLINE return spanNEWLINENEWLINE # 9.17. <date>NEWLINE # NEWLINE # This element is rendered as the HTML <time> element. If the "year",NEWLINE # "month", or "day" attribute is included on the XML element, anNEWLINE # appropriate "datetime" element will be generated in HTML.NEWLINE # NEWLINE # If this date is a child of the document's <front> element, it getsNEWLINE # the CSS class "published".NEWLINE # NEWLINE # If this date is inside a <reference> element, it gets the CSS classNEWLINE # "refDate".NEWLINE # NEWLINE # <time datetime="2014-10" class="published">October 2014</time>NEWLINE def render_date(self, h, x):NEWLINE parts = extract_date(x, self.options.date)NEWLINE text = format_date(*parts, legacy=self.options.legacy_date_format)NEWLINE datetime = format_date_iso(*parts)NEWLINE time = add.time(h, x, text, datetime=datetime)NEWLINE if x.getparent() == self.root.find('front'):NEWLINE time.set('class', 'published')NEWLINE return timeNEWLINENEWLINE # 9.18. <dd>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE def render_dd(self, h, x):NEWLINE indent = x.getparent().get('indent')NEWLINE style = 'margin-left: %.1fem' % (int(indent)*0.5) if indent else NoneNEWLINE dd = add.dd(h, x, style=style)NEWLINE for c in x.getchildren():NEWLINE self.render(dd, c)NEWLINE return ddNEWLINENEWLINE # 9.19. <displayreference>NEWLINE # NEWLINE # This element does not affect the HTML output, but it is used in theNEWLINE # generation of the <reference>, <referencegroup>, <relref>, and <xref>NEWLINE # elements.NEWLINE render_displayreference = null_rendererNEWLINENEWLINE # 9.20. <dl>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE # NEWLINE # If the hanging attribute is "false", add the "dlParallel" class, elseNEWLINE # add the "dlHanging" class.NEWLINE # NEWLINE # If the spacing attribute is "compact", add the "dlCompact" class.NEWLINE def render_dl(self, h, x):NEWLINE newline = x.get('newline')NEWLINE spacing = x.get('spacing')NEWLINE classes = []NEWLINE if newline == 'true':NEWLINE classes.append('dlNewline')NEWLINE elif newline == 'false':NEWLINE classes.append('dlParallel')NEWLINE if spacing == 'compact':NEWLINE classes.append('dlCompact')NEWLINE classes = ' '.join(classes)NEWLINE dl = add.dl(h, x, classes=classes)NEWLINE for c in x.getchildren():NEWLINE self.render(dl, c)NEWLINE return dlNEWLINENEWLINE # 9.21. <dt>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_dt = default_rendererNEWLINENEWLINE # NEWLINE # 9.22. <em>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_em = default_rendererNEWLINENEWLINE # 9.23. <email>NEWLINE # NEWLINE # This element is rendered as an HTML <div> containing the stringNEWLINE # "Email:" and an HTML <a> element with the "href" attribute set to theNEWLINE # equivalent "mailto:" URI, a CSS class of "email", and the contentsNEWLINE # set to the email address. If this is the version of the address withNEWLINE # ASCII, the "ascii" attribute is preferred to the element text.NEWLINE # NEWLINE # <div>NEWLINE # <span>Email:</span>NEWLINE # <a class="email" href="mailto:joe@example.com">joe@example.com</a>NEWLINE # </div>NEWLINE def render_email(self, h, x):NEWLINE value = x.text.strip()NEWLINE cls = 'email'NEWLINE div = add.div(h, None,NEWLINE build.span("Email:"), '\n',NEWLINE build.a(value, href='mailto:%s'%value, classes=cls),NEWLINE classes=cls,NEWLINE )NEWLINE return divNEWLINENEWLINE # NEWLINE # 9.24. <eref>NEWLINE # NEWLINE # This element is rendered as an HTML <a> element, with the "href"NEWLINE # attribute set to the value of the "target" attribute and the CSSNEWLINE # class of "eref".NEWLINE # NEWLINE # <a href="https://..." class="eref">the text</a>NEWLINE def render_eref(self, h, x):NEWLINE target = x.get('target')NEWLINE if x.text:NEWLINE hh = add.a(h, x, href=target) NEWLINE else:NEWLINE hh = add.span(h, x, build.a(target, href=target))NEWLINE return hhNEWLINENEWLINE # 9.25. <figure>NEWLINE # NEWLINE # This element renders as the HTML <figure> element, containing theNEWLINE # artwork or sourcecode indicated and an HTML <figcaption> element.NEWLINE # The <figcaption> element will contain an <a> element around theNEWLINE # figure number. It will also contain another <a> element with CSSNEWLINE # class "selfRef" around the figure name, if a name was given.NEWLINE # NEWLINE # <figure id="f-1">NEWLINE # ...NEWLINE # <figcaption>NEWLINE # <a href="#f-1">Figure 1.</a>NEWLINE # <a href="#n-it-figures" id="n-it-figures" class="selfRef">NEWLINE # It figuresNEWLINE # </a>NEWLINE # </figcaption>NEWLINE # </figure>NEWLINE def render_figure(self, h, x):NEWLINE name = x.find('name')NEWLINE if name != None and name.text:NEWLINE add.span(h, None, id=name.get('slugifiedName'))NEWLINE figure = add.figure(h, x)NEWLINE for c in x.iterchildren('artset', 'artwork', 'sourcecode'):NEWLINE self.render(figure, c)NEWLINE pn = x.get('pn')NEWLINE caption = add.figcaption(figure, None)NEWLINE a = add.a(caption, None, pn.replace('-',' ',1).title(), href='#%s'%pn)NEWLINE if name != None and name.text:NEWLINE a.tail = ':\n'NEWLINE a = add.a(caption, None, href='#%s'%name.get('slugifiedName'), classes='selfRef')NEWLINE self.inline_text_renderer(a, name)NEWLINE return figureNEWLINENEWLINE # 9.26. <front>NEWLINE # NEWLINE # See "Document Information" (Section 6.5) for information on thisNEWLINE # element.NEWLINE def render_front(self, h, x):NEWLINE if self.part == 'front':NEWLINE # 6.5. Document InformationNEWLINE # NEWLINE # Information about the document as a whole will appear as the firstNEWLINE # child of the HTML <body> element, embedded in an HTML <dl> elementNEWLINE # with id="identifiers". The defined terms in the definition list areNEWLINE # "Workgroup:", "Series:", "Status:", "Published:", and "Author:" orNEWLINE # "Authors:" (as appropriate). For example:NEWLINE # NEWLINE # <dl id="identifiers">NEWLINE # <dt>Workgroup:</dt>NEWLINE # <dd class="workgroup">rfc-interest</dd>NEWLINE # <dt>Series:</dt>NEWLINE # <dd class="series">Internet-Draft</dd>NEWLINE # <dt>Status:</dt>NEWLINE # <dd class="status">Informational</dd>NEWLINE # <dt>Published:</dt>NEWLINE # <dd><time datetime="2014-10-25"NEWLINE # class="published">2014-10-25</time></dd>NEWLINE # <dt>Authors:</dt>NEWLINE # <dd class="authors">NEWLINE # <div class="author">NEWLINE # <span class="initial">J.</span>NEWLINE # <span class="surname">Hildebrand</span>NEWLINE # (<span class="organization">Cisco Systems, Inc.</span>)NEWLINE # <span class="editor">Ed.</span>NEWLINE # </div>NEWLINE # <div class="author">NEWLINE # <span class="initial">H.</span>NEWLINE # <span class="surname">Flanagan</span>NEWLINE # (<span class="organization">RFC Editor</span>)NEWLINE # </div>NEWLINE # </dd>NEWLINE # </dl>NEWLINE # NEWLINENEWLINE # Now, a text format RFC has the following information, optionals inNEWLINE # parentheses:NEWLINE # NEWLINE # If RFC:NEWLINE # * <Stream Name>NEWLINE # * Request for Comments: <Number>NEWLINE # * (STD|BCP|FYI: <Number>)NEWLINE # * (Obsoletes: <Number>[, <Number>]*)NEWLINE # * (Updates: <Number>[, <Number>]*)NEWLINE # * Category: <Category Name>NEWLINE # * ISSN: 2070-1721NEWLINE # else:NEWLINE # * <Workgroup name> or "Network Working Group"NEWLINE # * Internet-DraftNEWLINE # * (STD|BCP|FYI: <Number> (if approved))NEWLINE # * (Obsoletes: <Number>[, <Number>]*)NEWLINE # * (Updates: <Number>[, <Number>]*)NEWLINE # * Intended Status: <Cagegory Name>NEWLINE # * Expires: <Date>NEWLINENEWLINE def entry(dl, name, value):NEWLINE if value != None:NEWLINE cls = slugify(name)NEWLINE dl.append( build.dt('%s:'%name, classes='label-%s'%cls))NEWLINE dl.append( build.dd(value, classes=cls))NEWLINE #NEWLINE dl = build.dl(id='identifiers')NEWLINE h.append( build.div(dl, classes='document-information' ))NEWLINE if self.options.rfc:NEWLINE # StreamNEWLINE stream = self.root.get('submissionType')NEWLINE entry(dl, 'Stream', strings.stream_name[stream])NEWLINE # Series infoNEWLINE for series in x.xpath('./seriesInfo'):NEWLINE self.render_seriesinfo(dl, series)NEWLINE for section in ['obsoletes', 'updates']:NEWLINE items = self.root.get(section)NEWLINE if items:NEWLINE alist = []NEWLINE for num in items.split(','):NEWLINE num = num.strip()NEWLINE a = build.a(num, href=os.path.join(self.options.rfc_base_url, 'rfc%s.txt'%num), classes='eref')NEWLINE a.tail = ' 'NEWLINE alist.append(a)NEWLINE entry(dl, section.title(), *alist)NEWLINENEWLINE category = self.root.get('category', '')NEWLINE if category:NEWLINE entry(dl, 'Category', strings.category_name[category])NEWLINE # Publication dateNEWLINE entry(dl, 'Published', self.render_date(None, x.find('date')))NEWLINE # ISSNNEWLINE entry(dl, 'ISSN', '2070-1721')NEWLINENEWLINE else:NEWLINE # WorkgroupNEWLINE for wg in x.xpath('./workgroup'):NEWLINE entry(dl, 'Workgroup', wg.text)NEWLINE # Internet-DraftNEWLINE for series in x.xpath('./seriesInfo'):NEWLINE entry(dl, series.get('name'), series.get('value'))NEWLINE # Obsoletes and UpdatesNEWLINE for section in ['obsoletes', 'updates']:NEWLINE items = self.root.get(section)NEWLINE if items:NEWLINE for num in items.split(','):NEWLINE num = num.strip()NEWLINE a = build.a(num, href=os.path.join(self.options.rfc_base_url, 'rfc%s.txt'%num), classes='eref')NEWLINE a.tail = ' 'NEWLINE entry(dl, section.title(), a)NEWLINE a.tail += '(if approved)'NEWLINE # Publication dateNEWLINE entry(dl, 'Published', self.render_date(None, x.find('date')))NEWLINE # Intended categoryNEWLINE category = self.root.get('category', '')NEWLINE if category:NEWLINE entry(dl, 'Intended Status', strings.category_name[category])NEWLINE # Expiry dateNEWLINE if self.root.get('ipr') != 'none':NEWLINE exp = get_expiry_date(self.root, self.date)NEWLINE expdate = build.date(year=str(exp.year), month=str(exp.month))NEWLINE if exp.day:NEWLINE expdate.set('day', str(exp.day))NEWLINE entry(dl, 'Expires', self.render_date(None, expdate))NEWLINENEWLINE authors = x.xpath('./author')NEWLINE dl.append( build.dt('Authors:' if len(authors)>1 else 'Author:', classes='label-authors' ))NEWLINE dd = add.dd(dl, None, classes='authors')NEWLINE for a in authors:NEWLINE self.render(dd, a)NEWLINENEWLINE for c in x.iterchildren('title', 'abstract', 'note', 'boilerplate'):NEWLINE self.render(h, c)NEWLINENEWLINE elif self.part == 'references':NEWLINE self.default_renderer(h, x)NEWLINE else:NEWLINE self.err(x, "Did not expect to be asked to render <%s> while in <%s> (self.part: %s)" % (x.tag, x.getparent().tag, self.part))NEWLINE NEWLINENEWLINE # 9.27. <iref>NEWLINE # NEWLINE # This element is rendered as an empty <> tag of class "iref", with anNEWLINE # "id" attribute consisting of the <iref> element's "irefid" attribute:NEWLINE # NEWLINE # <span class="iref" id="s-Paragraphs-first-1"/>NEWLINE def render_iref(self, h, x):NEWLINE span = add.span(None, x, classes='iref', id=x.get('pn'))NEWLINE if h.tag in ['table', ]:NEWLINE h.addprevious(span)NEWLINE else:NEWLINE h.append(span)NEWLINE return spanNEWLINENEWLINE # 9.28. <keyword>NEWLINE # NEWLINE # Each <keyword> element renders its text into the <meta> keywords inNEWLINE # the document's header, separated by commas.NEWLINE # NEWLINE # <meta name="keywords" content="html,css,rfc">NEWLINE # NEWLINE # 9.29. <li>NEWLINE # NEWLINE # This element is rendered as its HTML counterpart. However, if thereNEWLINE # is no contained element that has a pilcrow (Section 5.2) attached, aNEWLINE # pilcrow is added.NEWLINE # NEWLINE # <li id="s-2-7">Item <a href="#s-2-7" class="pilcrow">&para;</a></li>NEWLINE def render_li_ul(self, h, x):NEWLINE li = add.li(h, x, classes=h.get('class'))NEWLINE for c in x.getchildren():NEWLINE self.render(li, c)NEWLINE self.maybe_add_pilcrow(li)NEWLINE return liNEWLINENEWLINE def render_li(self, h, x):NEWLINE if h.tag == 'ul':NEWLINE li = self.render_li_ul(h, x)NEWLINE elif h.tag == 'dl':NEWLINE li = self.render_li_dl(h, x)NEWLINE elif h.tag == 'ol':NEWLINE li = self.render_li_ol(h, x)NEWLINE else:NEWLINE self.err(x, "Did not expect to be asked to render <%s> while in <%s>" % (x.tag, h.tag))NEWLINE li = NoneNEWLINE return liNEWLINENEWLINE # 9.30. <link>NEWLINE # NEWLINE # This element is rendered as its HTML counterpart, in the HTML header.NEWLINE def render_link(self, h, x):NEWLINE link = add.link(h, x, rel=x.get('rel'), href=x.get('href'))NEWLINE return linkNEWLINE NEWLINE # 9.31. <middle>NEWLINE # NEWLINE # This element does not add any direct output to HTML.NEWLINE render_middle = skip_rendererNEWLINENEWLINE ## Potential extension: <math>NEWLINE ##NEWLINE ## Same content as for instance <name>, but may contain unicodeNEWLINE ## characters of categories L*, P*, Sm, Sk or Zs. For categories L*, the scriptNEWLINE ## must be either Common, Greek, or Hebrew.NEWLINE ##NEWLINE ## def render_math(self, s, x):NEWLINE ## for t in x.itertext():NEWLINE ## for c in t:NEWLINE ## cat = unicode.category(c)NEWLINE ## if cat.beginswith('L'):NEWLINE ## scr = get_script(c)NEWLINE ## if not scr in ['Common', 'Greek', 'Hebrew', ]:NEWLINE ## self.err(x, ...)NEWLINE ## div = add.div(h, x, classes="inline-math")NEWLINE ## for c in x.getchildren():NEWLINE ## self.render(div, c)NEWLINE ##NEWLINENEWLINE # 9.32. <name>NEWLINE # NEWLINE # This element is never rendered directly; it is only rendered whenNEWLINE # considering a parent element, such as <figure>, <references>,NEWLINE # <section>, or <table>.NEWLINE def render_name(self, s, x):NEWLINE p = x.getparent()NEWLINE if p.tag in [ 'note', 'section', 'references' ]:NEWLINE pn = p.get('pn')NEWLINE prefix, number = pn.split('-', 1)NEWLINE number += '.'NEWLINE if re.search(r'^[a-z]', number):NEWLINE num = number.split('.', 1)[1]NEWLINE else:NEWLINE num = numberNEWLINE level = min([6, len(num.split('.')) ])NEWLINE tag = 'h%d' % levelNEWLINE h = build(tag, id=x.get('slugifiedName'))NEWLINE s.append(h)NEWLINE #NEWLINE numbered = p.get('numbered') or ('true' if p.tag == 'references' else 'false')NEWLINE if numbered == 'true':NEWLINE if number.startswith('appendix'):NEWLINE number = number.replace('.', ' ', 1).title()NEWLINE elif re.search('^[a-z]', number):NEWLINE number = number.title()NEWLINE a_number = build.a(number, '\u00a0', href='#%s'%pn, classes='section-number selfRef')NEWLINE h.append( a_number)NEWLINE a_title = build.a(href='#%s'%x.get('slugifiedName'), classes='section-name selfRef')NEWLINE self.inline_text_renderer(a_title, x)NEWLINE h.append(a_title)NEWLINE return hNEWLINE elif p.tag in [ 'table', 'figure' ]:NEWLINE return NoneNEWLINE else:NEWLINE self.warn(x, "Did not expect to be asked to render <%s> while in <%s>" % (x.tag, x.getparent().tag))NEWLINE self.default_renderer(s, x)NEWLINENEWLINENEWLINE # 9.33. <note>NEWLINE # NEWLINE # This element is rendered like a <section> element, but without aNEWLINE # section number and with the CSS class of "note". If theNEWLINE # "removeInRFC" attribute is set to "yes", the generated <div> elementNEWLINE # will also include the CSS class "rfcEditorRemove".NEWLINE # NEWLINE # <section id="s-note-1" class="note rfcEditorRemove">NEWLINE # <h2>NEWLINE # <a href="#n-editorial-note" class="selfRef">Editorial Note</a>NEWLINE # </h2>NEWLINE # <p id="s-note-1-1">NEWLINE # Discussion of this draft takes place...NEWLINE # <a href="#s-note-1-1" class="pilcrow">&para;</a>NEWLINE # </p>NEWLINE # </section>NEWLINE def render_note(self, h, x):NEWLINE classes = 'note'NEWLINE if x.get('removeInRFC') == 'true':NEWLINE classes += ' rfcEditorRemove'NEWLINE section = add.section(h, x, classes=classes)NEWLINE for c in x.getchildren():NEWLINE self.render(section, c)NEWLINE return sectionNEWLINENEWLINE # 9.34. <ol>NEWLINE # NEWLINE # The output created from an <ol> element depends upon the "style"NEWLINE # attribute.NEWLINE # NEWLINE # If the "spacing" attribute has the value "compact", a CSS class ofNEWLINE # "olCompact" will be added.NEWLINE # NEWLINE # The group attribute is not copied; the input XML should have startNEWLINE # values added by a prep tool for all grouped <ol> elements.NEWLINE def render_ol(self, h, x):NEWLINE type = x.get('type')NEWLINE if len(type) > 1 and '%' in type:NEWLINE ol = add.dl(h, x, classes='olPercent')NEWLINE else:NEWLINE attrib = dict([ (k,v) for (k,v) in x.attrib.items() if k in ['start', 'type', ] ])NEWLINE ol = add.ol(h, x, classes=x.get('spacing'), **attrib)NEWLINE for c in x.getchildren():NEWLINE self.render(ol, c)NEWLINE return olNEWLINENEWLINE # 9.34.1. Percent StylesNEWLINE # NEWLINE # If the style attribute includes the character "%", the output is aNEWLINE # <dl> tag with the class "olPercent". Each contained <li> element isNEWLINE # emitted as a <dt>/<dd> pair, with the generated label in the <dt> andNEWLINE # the contents of the <li> in the <dd>.NEWLINE # NEWLINE # <dl class="olPercent">NEWLINE # <dt>Requirement xviii:</dt>NEWLINE # <dd>Wheels on a big rig</dd>NEWLINE # </dl>NEWLINE def render_li_dl(self, h, x):NEWLINE label = x.get('derivedCounter')NEWLINE dt = add.dt(h, None, label)NEWLINE dd = add.dd(h, x)NEWLINE for c in x.getchildren():NEWLINE self.render(dd, c)NEWLINE self.maybe_add_pilcrow(dd)NEWLINE return dt, ddNEWLINENEWLINE # 9.34.2. Standard StylesNEWLINE # NEWLINE # For all other styles, an <ol> tag is emitted, with any "style"NEWLINE # attribute turned into the equivalent HTML attribute.NEWLINE # NEWLINE # <ol class="compact" type="I" start="18">NEWLINE # <li>Wheels on a big rig</li>NEWLINE # </ol>NEWLINE def render_li_ol(self, h, x):NEWLINE li = add.li(h, x)NEWLINE for c in x.getchildren():NEWLINE self.render(li, c)NEWLINE self.maybe_add_pilcrow(li)NEWLINE return liNEWLINENEWLINE # 9.35. <organization>NEWLINE # NEWLINE # This element is rendered as an HTML <div> tag with CSS class "org".NEWLINE # NEWLINE # If the element contains the "ascii" attribute, the organization nameNEWLINE # is rendered twice: once with the non-ASCII version wrapped in an HTMLNEWLINE # <span> tag of class "non-ascii" and then as the ASCII version wrappedNEWLINE # in an HTML <span> tag of class "ascii" wrapped in parentheses.NEWLINE # NEWLINE # <div class="org">NEWLINE # <span class="non-ascii">Test Org</span>NEWLINE # (<span class="ascii">TEST ORG</span>)NEWLINE # </div>NEWLINE render_organization = null_renderer # handled in render_addressNEWLINENEWLINE # 9.36. <phone>NEWLINE # NEWLINE # This element is rendered as an HTML <div> tag containing the stringNEWLINE # "Phone:" (wrapped in a span), an HTML <a> tag with CSS class "tel"NEWLINE # containing the phone number (and an href with a corresponding "tel:"NEWLINE # URI), and an HTML <span> with CSS class "type" containing the stringNEWLINE # "VOICE".NEWLINE # NEWLINE # <div>NEWLINE # <span>Phone:</span>NEWLINE # <a class="tel" href="tel:+1-720-555-1212">+1-720-555-1212</a>NEWLINE # <span class="type">VOICE</span>NEWLINE # </div>NEWLINE def render_phone(self, h, x):NEWLINE # The content of <span class="type">VOICE</span> seems to violate theNEWLINE # vcard types (they identify things like 'Home', 'Work', etc) andNEWLINE # will be skipped. The NEWLINE if not x.text:NEWLINE return NoneNEWLINE value = x.text.strip()NEWLINE cls = 'tel'NEWLINE div = add.div(h, None,NEWLINE build.span("Phone:"), '\n',NEWLINE build.a(value, href='tel:%s'%value, classes=cls),NEWLINE classes=cls,NEWLINE )NEWLINE return divNEWLINENEWLINE # 9.37. <postal>NEWLINE # NEWLINE # This element renders as an HTML <div> with CSS class "adr", unless itNEWLINE # contains one or more <postalLine> child elements; in which case, itNEWLINE # renders as an HTML <pre> element with CSS class "label".NEWLINE # NEWLINE # When there is no <postalLine> child, the following child elements areNEWLINE # rendered into the HTML:NEWLINE # NEWLINE # o Each <street> is renderedNEWLINE # NEWLINE # o A <div> that includes:NEWLINE # NEWLINE # * The rendering of all <city> elementsNEWLINE # NEWLINE # * A comma and a space: ", "NEWLINE # NEWLINE # * The rendering of all <region> elementsNEWLINE # NEWLINE # * WhitespaceNEWLINE # NEWLINE # * The rendering of all <code> elementsNEWLINE # NEWLINE # o The rendering of all <country> elementsNEWLINE # NEWLINE # <div class="adr">NEWLINE # <div class="street-address">1 Main Street</div>NEWLINE # <div class="street-address">Suite 1</div>NEWLINE # <div>NEWLINE # <span class="city">Denver</span>,NEWLINE # <span class="region">CO</span>NEWLINE # <span class="postal-code">80212</span>NEWLINE # </div>NEWLINE # <div class="country-name">United States of America</div>NEWLINE # </div>NEWLINE ##NEWLINE ## Much of the description above is much too americentric, and alsoNEWLINE ## conflicts with hCard. Examples from hCard will be used instead,NEWLINE ## and addresses rendered in a format appropriate for their country.NEWLINE ## NEWLINE ## <span class="adr">NEWLINE ## <span class="street-address">12 rue Danton</span>NEWLINE ## <span class="postal-code">94270</span>NEWLINE ## <span class="locality">Le Kremlin-Bicetre</span>NEWLINE ## <span class="country-name">France</span>NEWLINE ## </span> NEWLINE def render_postal(self, h, x):NEWLINE latin = h.get('class') == 'ascii'NEWLINE adr = get_normalized_address_info(self, x, latin=latin)NEWLINE if adr:NEWLINE align = 'left' if latin else get_bidi_alignment(adr)NEWLINE for item in format_address(adr, latin=latin):NEWLINE item.set('class', align)NEWLINE h.append(item)NEWLINE else:NEWLINE # render elements in found orderNEWLINE for c in x.getchildren():NEWLINE self.render(h, c)NEWLINENEWLINE # 9.38. <postalLine>NEWLINE # NEWLINE # This element renders as the text contained by the element, followedNEWLINE # by a newline. However, the last <postalLine> in a given <postal>NEWLINE # element should not be followed by a newline. For example:NEWLINE # NEWLINE # <postal>NEWLINE # <postalLine>In care of:</postalLine>NEWLINE # <postalLine>Computer Sciences Division</postalLine>NEWLINE # </postal>NEWLINE # NEWLINE # Would be rendered as:NEWLINE # NEWLINE # <pre class="label">In care of:NEWLINE # Computer Sciences Division</pre>NEWLINE def render_postalline(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='extended-address')NEWLINENEWLINE # 9.39. <refcontent>NEWLINE # NEWLINE # This element renders as an HTML <span> with CSS class "refContent".NEWLINE # NEWLINE # <span class="refContent">Self-published pamphlet</span>NEWLINE def render_refcontent(self, h, x):NEWLINE span = add.span(h, x, classes='refContent')NEWLINE for c in x.getchildren():NEWLINE self.render(span, c)NEWLINE return spanNEWLINENEWLINENEWLINE # 9.40. <reference>NEWLINE # NEWLINE # If the parent of this element is not a <referencegroup>, this elementNEWLINE # will render as a <dt> <dd> pair with the defined term being theNEWLINE # reference "anchor" attribute surrounded by square brackets and theNEWLINE # definition including the correct set of bibliographic information asNEWLINE # specified by [RFC7322]. The <dt> element will have an "id" attributeNEWLINE # of the reference anchor.NEWLINE # NEWLINE # <dl class="reference">NEWLINE # <dt id="RFC5646">[RFC5646]</dt>NEWLINE # <dd>NEWLINE # <span class="refAuthor">Phillips, A.</span>NEWLINE # <span>and</span>NEWLINE # <span class="refAuthor">M. Davis</span>NEWLINE # <span class="refTitle">"Tags for Identifying Languages"</span>,NEWLINE # ...NEWLINE # </dd>NEWLINE # </dl>NEWLINE # NEWLINE # If the child of a <referencegroup>, this element renders as a <div>NEWLINE # of class "refInstance" whose "id" attribute is the value of theNEWLINE # <source> element's "anchor" attribute.NEWLINE # NEWLINE # <div class="refInstance" id="RFC5730">NEWLINE # ...NEWLINE # </div>NEWLINE def render_reference(self, h, x):NEWLINE p = x.getparent()NEWLINE if p.tag == 'referencegroup':NEWLINE div = add.div(h, x, classes='refInstance')NEWLINE outer = divNEWLINE inner = divNEWLINE elif p.tag != 'referencegroup':NEWLINE dt = add.dt(h, x, '[%s]'%x.get('derivedAnchor'))NEWLINE dd = add.dd(h, None)NEWLINE outer = dt, ddNEWLINE inner = ddNEWLINE else:NEWLINE self.err(x, "Did not expect to be asked to render <%s> while in <%s>" % (x.tag, x.getparent().tag))NEWLINE # Deal with parts in the correct orderNEWLINE for c in x.iterdescendants('author'):NEWLINE self.render(inner, c)NEWLINE for ctag in ('title', 'refcontent', 'stream', 'seriesInfo', 'date', ):NEWLINE for c in x.iterdescendants(ctag):NEWLINE if len(inner):NEWLINE inner[-1].tail = ', 'NEWLINE self.render(inner, c)NEWLINE if p.tag != 'referencegroup':NEWLINE target = x.get('target')NEWLINE if target:NEWLINE inner.append( build.span(', <', build.a(target, href=target), '>') )NEWLINE if len(inner):NEWLINE inner[-1].tail = '. 'NEWLINE for ctag in ('annotation', ):NEWLINE for c in x.iterdescendants(ctag):NEWLINE self.render(inner, c)NEWLINE #NEWLINE return outerNEWLINENEWLINE # 9.41. <referencegroup>NEWLINE # NEWLINE # A <referencegroup> is translated into a <dt> <dd> pair, with theNEWLINE # defined term being the referencegroup "anchor" attribute surroundedNEWLINE # by square brackets, and the definition containing the translatedNEWLINE # output of all of the child <reference> elements.NEWLINE # NEWLINE # <dt id="STD69">[STD69]</dt>NEWLINE # <dd>NEWLINE # <div class="refInstance" id="RFC5730">NEWLINE # <span class="refAuthor">Hollenbeck, S.</span>NEWLINE # ...NEWLINE # </div>NEWLINE # <div class="refInstance" id="RFC5731">NEWLINE # <span class="refAuthor">Hollenbeck, S.</span>NEWLINE # ...NEWLINE # </div>NEWLINE # ...NEWLINE # </dd>NEWLINE def render_referencegroup(self, h, x):NEWLINE dt = add.dt(h, x, '[%s]'%x.get('derivedAnchor'))NEWLINE dd = add.dd(h, None)NEWLINE for c in x.getchildren():NEWLINE self.render(dd, c)NEWLINE target = x.get('target')NEWLINE if target:NEWLINE dd.append( build.span('<', build.a(target, href=target), '>') )NEWLINE return dt, ddNEWLINENEWLINE # 9.42. <references>NEWLINE # NEWLINE # If there is at exactly one <references> element, a section is addedNEWLINE # to the document, continuing with the next section number after theNEWLINE # last top-level <section> in <middle>. The <name> element of theNEWLINE # <references> element is used as the section name.NEWLINE # NEWLINE # <section id="n-my-references">NEWLINE # <h2 id="s-3">NEWLINE # <a href="#s-3" class="selfRef">3.</a>NEWLINE # <a href="#n-my-references class="selfRef">My References</a>NEWLINE # </h2>NEWLINE # ...NEWLINE # </section>NEWLINE # NEWLINE # If there is more than one <references> element, an HTML <section>NEWLINE # element is created to contain a subsection for each of theNEWLINE # <references>. The section number will be the next section numberNEWLINE # after the last top-level <section> in <middle>. The name of thisNEWLINE # section will be "References", and its "id" attribute will beNEWLINE # "n-references".NEWLINE # NEWLINE # <section id="n-references">NEWLINE # <h2 id="s-3">NEWLINE # <a href="#s-3" class="selfRef">3.</a>NEWLINE # <a href="#n-references" class="selfRef">References</a>NEWLINE # </h2>NEWLINE # <section id="n-informative-references">NEWLINE # <h3 id="s-3.1">NEWLINE # <a href="#s-3.1" class="selfRef">3.1.</a>NEWLINE # <a href="#n-informative-references" class="selfRef">NEWLINE # Informative References</a></h3>NEWLINE # <dl class="reference">...NEWLINE # </dl>NEWLINE # </section>NEWLINE # ...NEWLINE # </section>NEWLINE def render_references(self, h, x):NEWLINE self.part = x.tagNEWLINE section = add.section(h, x)NEWLINE hh = sectionNEWLINE for c in x.getchildren():NEWLINE if c.tag in ['reference', 'referencegroup'] and hh.tag != 'dl':NEWLINE hh = add.dl(hh, None, classes='references')NEWLINE self.render(hh, c)NEWLINE return sectionNEWLINENEWLINE # NEWLINE # 9.43. <region>NEWLINE # NEWLINE # This element is rendered as a <span> tag with CSS class "region".NEWLINE # NEWLINE # <span class="region">Colorado</span>NEWLINE def render_region(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='region')NEWLINENEWLINE # NEWLINE # 9.44. <relref>NEWLINE # NEWLINE # This element is rendered as an HTML <a> tag with CSS class "relref"NEWLINE # and "href" attribute of the "derivedLink" attribute of the element.NEWLINE # Different values of the "displayFormat" attribute cause the textNEWLINE # inside that HTML <a> tag to change and cause extra text to beNEWLINE # generated. Some values of the "displayFormat" attribute also causeNEWLINE # another HTML <a> tag to be rendered with CSS class "xref" and anNEWLINE # "href" of "#" and the "target" attribute (modified by any applicableNEWLINE # <displayreference> XML element) and text inside of the "target"NEWLINE # attribute (modified by any applicable <displayreference> XMLNEWLINE # element). When used, this <a class='xref'> HTML tag is alwaysNEWLINE # surrounded by square brackets, for example, "[<a class='xref'NEWLINE # href='#foo'>foo</a>]".NEWLINENEWLINE ## Deprecated, removed by preptoolNEWLINENEWLINENEWLINE # 9.44.1. displayFormat='of'NEWLINE # NEWLINE # The output is an <a class='relref'> HTML tag, with contents ofNEWLINE # "Section " and the value of the "section" attribute. This isNEWLINE # followed by the word "of" (surrounded by whitespace). This isNEWLINE # followed by the <a class='xref'> HTML tag (surrounded by squareNEWLINE # brackets).NEWLINE # NEWLINE # For example, with an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="of"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"/>NEWLINE # for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a> of [<a class="xref" href="#RFC9999">RFC9999</a>]NEWLINE # for an overview.NEWLINE # NEWLINE # 9.44.2. displayFormat='comma'NEWLINE # NEWLINE # The output is an <a class='xref'> HTML tag (wrapped by squareNEWLINE # brackets), followed by a comma (","), followed by whitespace,NEWLINE # followed by an <a class='relref'> HTML tag, with contents ofNEWLINE # "Section " and the value of the "section" attribute.NEWLINE # NEWLINE # For example, with an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="comma"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"/>,NEWLINE # for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See [<a class="xref" href="#RFC9999">RFC9999</a>], <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">Section 2.3</a>,NEWLINE # for an overview.NEWLINE # NEWLINE # 9.44.3. displayFormat='parens'NEWLINE # NEWLINE # The output is an <a> element with "href" attribute whose value is theNEWLINE # value of the "target" attribute prepended by "#", and whose contentNEWLINE # is the value of the "target" attribute; the entire element is wrappedNEWLINE # in square brackets. This is followed by whitespace. This isNEWLINE # followed by an <a> element whose "href" attribute is the value of theNEWLINE # "derivedLink" attribute and whose content is the value of theNEWLINE # "derivedRemoteContent" attribute; the entire element is wrapped inNEWLINE # parentheses.NEWLINE # NEWLINE # For example, if Section 2.3 of RFC 9999 has the title "ProtocolNEWLINE # Overview", for an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="parens"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"NEWLINE # derivedRemoteContent="Section 2.3"/> for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See [<a class="relref" href="#RFC9999">RFC9999</a>]NEWLINE # (<a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a>) for an overview.NEWLINE # NEWLINE # 9.44.4. displayFormat='bare'NEWLINE # NEWLINE # The output is an <a> element whose "href" attribute is the value ofNEWLINE # the "derivedLink" attribute and whose content is the value of theNEWLINE # "derivedRemoteContent" attribute.NEWLINE # NEWLINE # For this input:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="bare"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"NEWLINE # derivedRemoteContent="Section 2.3"/> and ...NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a> and ...NEWLINENEWLINE # 9.45. <rfc>NEWLINE # NEWLINE # Various attributes of this element are represented in different partsNEWLINE # of the HTML document.NEWLINENEWLINE # 9.46. <section>NEWLINE # NEWLINE # This element is rendered as an HTML <section> element, containing anNEWLINE # appropriate level HTML heading element (<h2>-<h6>). That headingNEWLINE # element contains an <a> element around the part number (pn), ifNEWLINE # applicable (for instance, <abstract> does not get a section number).NEWLINE # Another <a> element is included with the section's name.NEWLINE # NEWLINE # <section id="intro">NEWLINE # <h2 id="s-1">NEWLINE # <a href="#s-1" class="selfRef">1.</a>NEWLINE # <a href="#intro" class="selfRef">Introduction</a>NEWLINE # </h2>NEWLINE # <p id="s-1-1">Paragraph <a href="#s-1-1" class="pilcrow">&para;</a>NEWLINE # </p>NEWLINE # </section>NEWLINE def render_section(self, h, x):NEWLINE section = add(x.tag, h, x)NEWLINE anchor = x.get('anchor')NEWLINE if anchor == 'toc':NEWLINE add.a(section, None, "\u25b2", href="#", onclick="scroll(0,0)", classes="toplink")NEWLINE for c in x.getchildren():NEWLINE self.render(section, c)NEWLINE return sectionNEWLINENEWLINENEWLINE # 9.47. <seriesInfo>NEWLINE # NEWLINE # This element is rendered in an HTML <span> element with CSS nameNEWLINE # "seriesInfo".NEWLINE # NEWLINE # <span class="seriesInfo">RFC 5646</span>NEWLINE ## This is different from what's shown in the sample documents, _and_NEWLINE ## different from what's shown in Section 6.5. Following the sample docNEWLINE ## here.NEWLINE def render_seriesinfo(self, h, x):NEWLINE def entry(dl, name, value):NEWLINE cls = slugify(name)NEWLINE dl.append( build.dt('%s:'%name, classes='label-%s'%cls))NEWLINE dl.append( build.dd(value, classes=cls))NEWLINE #NEWLINE name = x.get('name') NEWLINE value = x.get('value')NEWLINE if self.part == 'front':NEWLINE if name == 'RFC':NEWLINE value = build.a(value, href=os.path.join(self.options.rfc_base_url, 'rfc%s.txt'%value), classes='eref')NEWLINE elif name == 'DOI':NEWLINE value = build.a(value, href=os.path.join(self.options.doi_base_url, value), classes='eref')NEWLINE elif name == 'Internet-Draft':NEWLINE value = build.a(value, href=os.path.join(self.options.id_base_url, value), classes='eref')NEWLINE entry(h, name, value)NEWLINE return hNEWLINE elif self.part == 'references':NEWLINE span = add.span(h, x, name, ' ', value, classes='seriesInfo')NEWLINE return spanNEWLINE else:NEWLINE self.err(x, "Did not expect to be asked to render <%s> while in <%s>" % (x.tag, x.getparent().tag))NEWLINENEWLINENEWLINE # 9.48. <sourcecode>NEWLINE # NEWLINE # This element is rendered in an HTML <pre> element with a CSS class ofNEWLINE # "sourcecode". Note that CDATA blocks do not work consistently inNEWLINE # HTML, so all <, >, and & must be escaped as &lt;, &gt;, and &amp;,NEWLINE # respectively. If the input XML has a "type" attribute, another CSSNEWLINE # class of "lang-" and the type is added.NEWLINE # NEWLINE # If the sourcecode is not inside a <figure> element, a pilcrowNEWLINE # (Section 5.2) is included. Inside a <figure> element, the figureNEWLINE # title serves the purpose of the pilcrow.NEWLINE # NEWLINE # <pre class="sourcecode lang-c">NEWLINE # #include &lt;stdio.h&gt;NEWLINE # NEWLINE # int main(void)NEWLINE # {NEWLINE # printf(&quot;hello, world\n&quot;);NEWLINE # return 0;NEWLINE # }NEWLINE # </pre>NEWLINE def render_sourcecode(self, h, x):NEWLINE file = x.get('name')NEWLINE type = x.get('type')NEWLINE mark = x.get('markers') == 'true'NEWLINE classes = 'sourcecode'NEWLINE if type:NEWLINE classes += ' lang-%s' % typeNEWLINE div = add.div(h, x)NEWLINE div.text = NoneNEWLINE pre = add.pre(div, None, x.text, classes=classes)NEWLINE if mark:NEWLINE text = pre.textNEWLINE text = (' file "%s"\n%s' % (file, text)) if text else '\n%s' % textNEWLINE text = "<CODE BEGINS>%s\n<CODE ENDS>" % textNEWLINE pre.text = textNEWLINE self.maybe_add_pilcrow(div)NEWLINE return divNEWLINENEWLINENEWLINE def render_stream(self, h, x):NEWLINE return add.span(h, x, classes="stream")NEWLINENEWLINE # 9.49. <street>NEWLINE # NEWLINE # This element renders as an HTML <div> element with CSS class "street-NEWLINE # address".NEWLINE # NEWLINE # <div class="street-address">1899 Wynkoop St, Suite 600</div>NEWLINE def render_street(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='street-address')NEWLINENEWLINE def render_extaddr(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='extended-address')NEWLINENEWLINE def render_pobox(self, h, x):NEWLINE return self.address_line_renderer(h, x, classes='post-office-box')NEWLINENEWLINENEWLINE # 9.50. <strong>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_strong = default_rendererNEWLINENEWLINE # 9.51. <sub>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_sub = default_rendererNEWLINENEWLINE # 9.52. <sup>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_sup = default_rendererNEWLINENEWLINE # 9.53. <t>NEWLINE # NEWLINE # This element is rendered as an HTML <p> element. A pilcrowNEWLINE # (Section 5.2) is included.NEWLINE # NEWLINE # <p id="s-1-1">A paragraph.NEWLINE # <a href="#s-1-1" class="pilcrow">&para;</a></p>NEWLINE def render_t(self, h, x):NEWLINE p = add.p(h, x)NEWLINE for c in x.getchildren():NEWLINE self.render(p, c)NEWLINE add.a(p, None, pilcrow, classes='pilcrow', href='#%s'%x.get('pn'))NEWLINE return pNEWLINENEWLINE # NEWLINE # 9.54. <table>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE def render_table(self, h, x):NEWLINE name = x.find('name')NEWLINE if name != None and name.text:NEWLINE add.span(h, None, id=name.get('slugifiedName'))NEWLINE align = x.get('align')NEWLINE table = add.table(h, x, classes=align)NEWLINE caption = add.caption(table, None)NEWLINE pn = x.get('pn')NEWLINE a = add.a(caption, None, pn.replace('-',' ',1).title(), href='#%s'%pn)NEWLINE if name != None:NEWLINE a.tail = ':\n'NEWLINE a = add.a(caption, None, href='#%s'%name.get('slugifiedName'), classes='selfRef')NEWLINE self.inline_text_renderer(a, name)NEWLINE for c in x.getchildren():NEWLINE self.render(table, c)NEWLINE return tableNEWLINENEWLINE # 9.55. <tbody>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_tbody = default_rendererNEWLINENEWLINE # 9.56. <td>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE def render_td(self, h, x):NEWLINE classes = "text-%s" % x.get('align')NEWLINE hh = add(x.tag, h, x, classes=classes)NEWLINE hh.set('rowspan', x.get('rowspan', '1'))NEWLINE hh.set('colspan', x.get('colspan', '1'))NEWLINE for c in x.getchildren():NEWLINE self.render(hh, c)NEWLINENEWLINE # 9.57. <tfoot>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_tfoot = default_rendererNEWLINENEWLINE # 9.58. <th>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE def render_th(self, h, x):NEWLINE classes = "text-%s" % x.get('align')NEWLINE hh = add(x.tag, h, x, classes=classes)NEWLINE hh.set('rowspan', x.get('rowspan', '1'))NEWLINE hh.set('colspan', x.get('colspan', '1'))NEWLINE for c in x.getchildren():NEWLINE self.render(hh, c)NEWLINENEWLINE # 9.59. <thead>NEWLINE #NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_thead = default_rendererNEWLINE NEWLINE # 9.60. <title>NEWLINE # NEWLINE # The title of the document appears in a <title> element in the <head>NEWLINE # element, as described in Section 6.3.2.NEWLINE # NEWLINE # The title also appears in an <h1> element and follows directly afterNEWLINE # the Document Information. The <h1> element has an "id" attributeNEWLINE # with value "title".NEWLINE # NEWLINE # <h1 id="title">HyperText Markup Language Request ForNEWLINE # Comments Format</h1>NEWLINE # NEWLINE # Inside a reference, the title is rendered as an HTML <span> tag withNEWLINE # CSS class "refTitle". The text is surrounded by quotes inside theNEWLINE # <span>.NEWLINE # NEWLINE # <span class="refTitle">"Tags for Identifying Languages"</span>NEWLINE def render_title(self, h, x):NEWLINE pp = x.getparent().getparent()NEWLINE title = x.textNEWLINE if pp.get("quoteTitle") == 'true':NEWLINE title = '"%s"' % titleNEWLINE ascii = x.get('ascii')NEWLINE if ascii and not is_script(title, 'Latin'):NEWLINE if pp.get("quoteTitle") == 'true':NEWLINE ascii = '"%s"' % asciiNEWLINE #NEWLINE if self.part == 'references':NEWLINE if title:NEWLINE span = wrap_ascii('span', '', title, ascii, '', classes='refTitle')NEWLINE h.append(span)NEWLINE return spanNEWLINE else:NEWLINE h1 = build.h1(title, id='title')NEWLINE h.append(h1)NEWLINE return h1NEWLINENEWLINE # 9.61. <tr>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart.NEWLINE render_tr = default_rendererNEWLINENEWLINE # 9.62. <tt>NEWLINE # NEWLINE # This element is rendered as an HTML <code> element.NEWLINE def render_tt(self, h, x):NEWLINE hh = add.code(h, x)NEWLINE for c in x.getchildren():NEWLINE self.render(hh, c)NEWLINENEWLINE # 9.63. <ul>NEWLINE # NEWLINE # This element is directly rendered as its HTML counterpart. If theNEWLINE # "spacing" attribute has the value "compact", a CSS class ofNEWLINE # "ulCompact" will be added. If the "empty" attribute has the valueNEWLINE # "true", a CSS class of "ulEmpty" will be added.NEWLINE def render_ul(self, h, x):NEWLINE ul = build.ul()NEWLINE p = x.getparent()NEWLINE panchor = p.get('anchor')NEWLINE classes = h.get('class', '')NEWLINE if panchor in ['toc', ]:NEWLINE hh = wrap(ul, 'nav', **{'class': panchor})NEWLINE classes += ' '+panchor if classes else panchorNEWLINE else:NEWLINE hh = ulNEWLINE h.append(hh)NEWLINE if x.get('empty')=='true':NEWLINE if not 'ulEmpty' in classes:NEWLINE if classes:NEWLINE classes += ' 'NEWLINE classes += 'ulEmpty' NEWLINE if classes:NEWLINE ul.set('class', classes)NEWLINE for c in x.getchildren():NEWLINE self.render(ul, c)NEWLINE return ulNEWLINENEWLINE # RFC 7997NEWLINE # 3.4. Body of the DocumentNEWLINE # NEWLINE # When the mention of non-ASCII characters is required for correctNEWLINE # protocol operation and understanding, the characters' UnicodeNEWLINE # character name or code point MUST be included in the text.NEWLINE # NEWLINE # o Non-ASCII characters will require identifying the Unicode codeNEWLINE # point.NEWLINE # NEWLINE # o Use of the actual UTF-8 character (e.g., Δ) is encouraged soNEWLINE # that a reader can more easily see what the character is, if theirNEWLINE # device can render the text.NEWLINE # NEWLINE # o The use of the Unicode character names like "INCREMENT" inNEWLINE # addition to the use of Unicode code points is also encouraged.NEWLINE # When used, Unicode character names should be in all capitalNEWLINE # letters.NEWLINE # NEWLINE # Examples:NEWLINE # NEWLINE # OLD [RFC7564]:NEWLINE # NEWLINE # However, the problem is made more serious by introducing the fullNEWLINE # range of Unicode code points into protocol strings. For example,NEWLINE # the characters U+13DA U+13A2 U+13B5 U+13AC U+13A2 U+13AC U+13D2 fromNEWLINE # the Cherokee block look similar to the ASCII characters "STPETER" asNEWLINE # they might appear when presented using a "creative" font family.NEWLINE # NEWLINE # NEW/ALLOWED:NEWLINE # NEWLINE # However, the problem is made more serious by introducing the fullNEWLINE # range of Unicode code points into protocol strings. For example,NEWLINE # the characters U+13DA U+13A2 U+13B5 U+13AC U+13A2 U+13AC U+13D2NEWLINE # (ᏚᎢᎵᎬᎢᎬᏒ) from the Cherokee block look similar to the ASCIINEWLINE # characters "STPETER" as they might appear when presented using aNEWLINE # "creative" font family.NEWLINE # NEWLINE # ALSO ACCEPTABLE:NEWLINE # NEWLINE # However, the problem is made more serious by introducing the fullNEWLINE # range of Unicode code points into protocol strings. For example,NEWLINE # the characters "ᏚᎢᎵᎬᎢᎬᏒ" (U+13DA U+13A2 U+13B5 U+13AC U+13A2NEWLINE # U+13AC U+13D2) from the Cherokee block look similar to the ASCIINEWLINE # characters "STPETER" as they might appear when presented using aNEWLINE # "creative" font family.NEWLINE # NEWLINE # Example of proper identification of Unicode characters in an RFC:NEWLINE # NEWLINE # Flanagan Expires October 27, 2016 [Page 6]NEWLINE # NEWLINE # NEWLINE # Internet-Draft non-ASCII in RFCs April 2016NEWLINE # NEWLINE # NEWLINE # Acceptable:NEWLINE # NEWLINE # o Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the U+2206 character.NEWLINE # NEWLINE # Preferred:NEWLINE # NEWLINE # 1. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the U+2206 character ("Δ").NEWLINE # NEWLINE # 2. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the U+2206 character (INCREMENT).NEWLINE # NEWLINE # 3. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the U+2206 character ("Δ", INCREMENT).NEWLINE # NEWLINE # 4. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the U+2206 character (INCREMENT, "Δ").NEWLINE # NEWLINE # 5. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the "Delta" character "Δ" (U+2206).NEWLINE # NEWLINE # 6. Temperature changes in the Temperature Control Protocol areNEWLINE # indicated by the character "Δ" (INCREMENT, U+2206).NEWLINE def render_u(self, h, x):NEWLINE try:NEWLINE text = expand_unicode_element(x)NEWLINE except (RuntimeError, ValueError) as e:NEWLINE self.err(x, e)NEWLINE text = ''NEWLINE anchor = x.get('anchor')NEWLINE xref = self.root.find('.//xref[@target="%s"]'%anchor) if anchor else NoneNEWLINE if xref != None:NEWLINE # render only literal hereNEWLINE text = x.textNEWLINE span = add.span(h, None, text, classes="unicode", id=anchor)NEWLINE span.tail = x.tailNEWLINE return spanNEWLINE NEWLINE # 9.64. <uri>NEWLINE # NEWLINE # This element is rendered as an HTML <div> containing the stringNEWLINE # "URI:" and an HTML <a> element with the "href" attribute set to theNEWLINE # linked URI, CSS class of "url" (note that the value is "url", notNEWLINE # "uri" as one might expect), and the contents set to the linked URI.NEWLINE # NEWLINE # <div>URI:NEWLINE # <a href="http://www.example.com"NEWLINE # class="url">http://www.example.com</a>NEWLINE # </div>NEWLINE def render_uri(self, h, x):NEWLINE if not x.text:NEWLINE return NoneNEWLINE value = x.text.strip()NEWLINE cls = 'url'NEWLINE div = add.div(h, None,NEWLINE build.span("URI:"), '\n',NEWLINE build.a(value, href=value, classes=cls),NEWLINE classes=cls,NEWLINE )NEWLINE return divNEWLINENEWLINE # 9.65. <workgroup>NEWLINE # NEWLINE # This element does not add any direct output to HTML.NEWLINE render_workgroup = null_renderer # handled in render_rfc, when rendering the page top for draftsNEWLINENEWLINE # 9.66. <xref>NEWLINE # NEWLINE # This element is rendered as an HTML <a> element containing anNEWLINE # appropriate local link as the "href" attribute. The value of theNEWLINE # "href" attribute is taken from the "target" attribute, prepended byNEWLINE # "#". The <a> element generated will have class "xref". The contentsNEWLINE # of the <a> element are the value of the "derivedContent" attribute.NEWLINE # If the "format" attribute has the value "default", and the "target"NEWLINE # attribute points to a <reference> or <referencegroup> element, thenNEWLINE # the generated <a> element is surrounded by square brackets in theNEWLINE # output.NEWLINE # NEWLINE # <a class="xref" href="#target">Table 2</a>NEWLINE # NEWLINE # orNEWLINE # NEWLINE # [<a class="xref" href="#RFC1234">RFC1234</a>]NEWLINE # NEWLINE def render_xref(self, h, x):NEWLINE # possible attributes:NEWLINE target = x.get('target')NEWLINE #pageno = x.get('pageno')NEWLINE #format = x.get('format')NEWLINE section = x.get('section')NEWLINE relative= x.get('relative')NEWLINE #sformat = x.get('sectionFormat')NEWLINE reftext = x.get('derivedContent', '')NEWLINE in_name = len(list(x.iterancestors('name'))) > 0NEWLINE if reftext is None:NEWLINE self.die(x, "Found an <%s> without derivedContent: %s" % (x.tag, lxml.etree.tostring(x),))NEWLINE if not (section or relative):NEWLINE # plain xrefNEWLINE if in_name:NEWLINE hh = build.em(reftext, classes="xref")NEWLINE else:NEWLINE if reftext:NEWLINE a = build.a(reftext, href='#%s'%target, classes='xref')NEWLINE if target in self.refname_mapping:NEWLINE if x.text and x.text.strip() and x.text.strip() != reftext:NEWLINE aa = build.a(x.text, href='#%s'%target, classes='xref')NEWLINE hh = build.span(aa, ' [', a, ']')NEWLINE else:NEWLINE hh = build.span('[', a, ']')NEWLINE else:NEWLINE if x.text and x.text.strip() and x.text.strip() != reftext:NEWLINE aa = build.a(x.text, href='#%s'%target, classes='xref')NEWLINE hh = build.span(aa, ' (', a, ')')NEWLINE else:NEWLINE hh = aNEWLINE else:NEWLINE a = build.a(x.text or '', href='#%s'%target, classes='xref')NEWLINE hh = aNEWLINE hh.tail = x.tailNEWLINE h.append(hh)NEWLINE return hhNEWLINE else:NEWLINE label = 'Section' if section[0].isdigit() else 'Appendix'NEWLINE link = x.get('derivedLink')NEWLINE format = x.get('sectionFormat')NEWLINE # 9.44.1. displayFormat='of'NEWLINE # NEWLINE # The output is an <a class='relref'> HTML tag, with contents ofNEWLINE # "Section " and the value of the "section" attribute. This isNEWLINE # followed by the word "of" (surrounded by whitespace). This isNEWLINE # followed by the <a class='xref'> HTML tag (surrounded by squareNEWLINE # brackets).NEWLINE # NEWLINE # For example, with an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="of"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"/>NEWLINE # for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a> of [<a class="xref" href="#RFC9999">RFC9999</a>]NEWLINE # for an overview.NEWLINE if format == 'of':NEWLINE span = add.span(h, None,NEWLINE build.a('%s %s'%(label, section), href=link, classes='relref'),NEWLINE ' of [',NEWLINE build.a(reftext, href='#%s'%target, classes='xref'),NEWLINE ']',NEWLINE )NEWLINE return spanNEWLINENEWLINE # 9.44.2. displayFormat='comma'NEWLINE # NEWLINE # The output is an <a class='xref'> HTML tag (wrapped by squareNEWLINE # brackets), followed by a comma (","), followed by whitespace,NEWLINE # followed by an <a class='relref'> HTML tag, with contents ofNEWLINE # "Section " and the value of the "section" attribute.NEWLINE # NEWLINE # For example, with an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="comma"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"/>,NEWLINE # for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See [<a class="xref" href="#RFC9999">RFC9999</a>], <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">Section 2.3</a>,NEWLINE # for an overview.NEWLINE elif format == 'comma':NEWLINE span = add.span(h, None,NEWLINE '[',NEWLINE build.a(reftext, href='#%s'%target, classes='xref'),NEWLINE '], ',NEWLINE build.a('%s %s'%(label, section), href=link, classes='relref'),NEWLINE )NEWLINE return spanNEWLINENEWLINENEWLINE # 9.44.3. displayFormat='parens'NEWLINE # NEWLINE # The output is an <a> element with "href" attribute whose value is theNEWLINE # value of the "target" attribute prepended by "#", and whose contentNEWLINE # is the value of the "target" attribute; the entire element is wrappedNEWLINE # in square brackets. This is followed by whitespace. This isNEWLINE # followed by an <a> element whose "href" attribute is the value of theNEWLINE # "derivedLink" attribute and whose content is the value of theNEWLINE # "derivedRemoteContent" attribute; the entire element is wrapped inNEWLINE # parentheses.NEWLINE # NEWLINE # For example, if Section 2.3 of RFC 9999 has the title "ProtocolNEWLINE # Overview", for an input of:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="parens"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"NEWLINE # derivedRemoteContent="Section 2.3"/> for an overview.NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See [<a class="relref" href="#RFC9999">RFC9999</a>]NEWLINE # (<a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a>) for an overview.NEWLINE elif format == 'parens':NEWLINE span = add.span(h, None,NEWLINE '[',NEWLINE build.a(reftext, href='#%s'%target, classes='xref'),NEWLINE '] (',NEWLINE build.a('%s %s'%(label, section), href=link, classes='relref'),NEWLINE ')',NEWLINE )NEWLINE return spanNEWLINENEWLINE # NEWLINE # 9.44.4. displayFormat='bare'NEWLINE # NEWLINE # The output is an <a> element whose "href" attribute is the value ofNEWLINE # the "derivedLink" attribute and whose content is the value of theNEWLINE # "derivedRemoteContent" attribute.NEWLINE # NEWLINE # For this input:NEWLINE # NEWLINE # See <relref section="2.3" target="RFC9999" displayFormat="bare"NEWLINE # derivedLink="http://www.rfc-editor.org/info/rfc9999#s-2.3"NEWLINE # derivedRemoteContent="Section 2.3"/> and ...NEWLINE # NEWLINE # The HTML generated will be:NEWLINE # NEWLINE # See <a class="relref"NEWLINE # href="http://www.rfc-editor.org/info/rfc9999#s-2.3">SectionNEWLINE # 2.3</a> and ...NEWLINE elif format == 'bare':NEWLINE span = add.span(h, None,NEWLINE build.a('%s %s'%(label, section), href=link, classes='relref'),NEWLINE )NEWLINE return spanNEWLINE else:NEWLINE self.err(x, 'Unexpected value combination: section: %s relative: %s format: %s' %(section, relative, format))NEWLINENEWLINENEWLINE # --------------------------------------------------------------------------NEWLINE # Post processingNEWLINE def post_process(self, h):NEWLINE for x in h.iter():NEWLINE if x.text and x.text.strip() and '\u2028' in x.text:NEWLINE parts = x.text.split('\u2028')NEWLINE x.text = parts[0]NEWLINE for t in parts[1:]:NEWLINE br = build.br()NEWLINE br.tail = tNEWLINE x.append( br )NEWLINE if x.tail and x.tail.strip() and '\u2028' in x.tail:NEWLINE p = x.getparent()NEWLINE i = p.index(x)+1NEWLINE parts = x.tail.split('\u2028')NEWLINE x.tail = parts[0]NEWLINE for t in parts[1:]:NEWLINE br = build.br()NEWLINE br.tail = tNEWLINE p.insert(br, i)NEWLINE i += 1NEWLINE return hNEWLINENEWLINE # --- class variables ------------------------------------------------------NEWLINENEWLINE element_tags = [NEWLINE 'abstract',NEWLINE 'address',NEWLINE 'annotation',NEWLINE 'artset',NEWLINE 'artwork',NEWLINE 'aside',NEWLINE 'author',NEWLINE 'back',NEWLINE 'bcp14',NEWLINE 'blockquote',NEWLINE 'boilerplate',NEWLINE 'br',NEWLINE 'city',NEWLINE 'code',NEWLINE 'country',NEWLINE 'cref',NEWLINE 'date',NEWLINE 'dd',NEWLINE 'displayreference',NEWLINE 'dl',NEWLINE 'dt',NEWLINE 'em',NEWLINE 'email',NEWLINE 'eref',NEWLINE 'figure',NEWLINE 'front',NEWLINE 'iref',NEWLINE 'li',NEWLINE 'link',NEWLINE 'middle',NEWLINE 'name',NEWLINE 'note',NEWLINE 'ol',NEWLINE 'organization',NEWLINE 'phone',NEWLINE 'postal',NEWLINE 'postalLine',NEWLINE 'refcontent',NEWLINE 'reference',NEWLINE 'referencegroup',NEWLINE 'references',NEWLINE 'region',NEWLINE 'relref',NEWLINE 'rfc',NEWLINE 'section',NEWLINE 'seriesInfo',NEWLINE 'sourcecode',NEWLINE 'street',NEWLINE 'strong',NEWLINE 'sub',NEWLINE 'sup',NEWLINE 't',NEWLINE 'table',NEWLINE 'tbody',NEWLINE 'td',NEWLINE 'tfoot',NEWLINE 'th',NEWLINE 'thead',NEWLINE 'title',NEWLINE 'tr',NEWLINE 'tt',NEWLINE 'ul',NEWLINE 'uri',NEWLINE 'xref',NEWLINE ]NEWLINE deprecated_element_tags = [NEWLINE 'list',NEWLINE 'spanx',NEWLINE 'vspace',NEWLINE 'c',NEWLINE 'texttable',NEWLINE 'ttcol',NEWLINE 'facsimile',NEWLINE 'format',NEWLINE 'preamble',NEWLINE 'postamble',NEWLINE ]NEWLINE unused_front_element_renderers = [NEWLINE 'area',NEWLINE 'keyword',NEWLINE 'workgroup',NEWLINE ]NEWLINE all_element_tags = element_tags + deprecated_element_tags + unused_front_element_renderersNEWLINE deprecated_attributes = [NEWLINE # element, attrbuteNEWLINE ('figure', 'align'),NEWLINE ('section', 'title'),NEWLINE ('note', 'title'),NEWLINE ('figure', 'title'),NEWLINE ('references', 'title'),NEWLINE ('texttable', 'title'),NEWLINE ('figure', 'src'),NEWLINE ('artwork', 'xml:space'),NEWLINE ('artwork', 'height'),NEWLINE ('artwork', 'width'),NEWLINE ('figure', 'height'),NEWLINE ('figure', 'width'),NEWLINE ('xref', 'pageno'),NEWLINE ]NEWLINE
from business_register.models import (NEWLINE company_models,NEWLINE fop_models,NEWLINE kved_models,NEWLINE pep_models,NEWLINE sanction_models,NEWLINE declaration_models,NEWLINE)NEWLINE
import torchNEWLINEimport torch.nn as nnNEWLINEfrom torch.distributions import NormalNEWLINENEWLINEfrom examples.nvae.common import DecoderResidualBlockNEWLINEfrom examples.nvae.common import ResidualBlockNEWLINEfrom examples.nvae.common import SwishNEWLINEfrom examples.nvae.losses import kl_2NEWLINEfrom examples import iter_pairsNEWLINENEWLINENEWLINEclass UpsampleBlock(nn.Module):NEWLINE def __init__(self, in_channel, out_channel):NEWLINE super().__init__()NEWLINENEWLINE self._seq = nn.Sequential(NEWLINE nn.ConvTranspose2d(NEWLINE in_channel,NEWLINE out_channel,NEWLINE kernel_size=3,NEWLINE stride=2,NEWLINE padding=1,NEWLINE output_padding=1NEWLINE ),NEWLINE # nn.UpsamplingBilinear2d(scale_factor=2),NEWLINE # nn.Conv2d(in_channel, out_channel, kernel_size=3, padding=1),NEWLINE nn.BatchNorm2d(out_channel), Swish(),NEWLINE )NEWLINENEWLINE def forward(self, x):NEWLINE return self._seq(x)NEWLINENEWLINENEWLINEclass DecoderBlock(nn.Module):NEWLINENEWLINE def __init__(self, channels):NEWLINE super().__init__()NEWLINE self.channels = channelsNEWLINE self.module_list = nn.ModuleList([NEWLINE UpsampleBlock(inp, out)NEWLINE for inp, out in iter_pairs(channels)NEWLINE ])NEWLINENEWLINE def forward(self, x):NEWLINE for module in self.module_list:NEWLINE x = module(x)NEWLINE return xNEWLINENEWLINENEWLINEclass Decoder(nn.Module):NEWLINENEWLINE def __init__(self, z_dim):NEWLINE super().__init__()NEWLINENEWLINE # Input channels = z_channels * 2 = x_channels + z_channelsNEWLINE # Output channels = z_channelsNEWLINE self.decoder_blocks = nn.ModuleList([NEWLINE DecoderBlock([z_dim * 2, z_dim // 2]), # 2x upsampleNEWLINE DecoderBlock([z_dim, z_dim // 4, z_dim // 8]), # 4x upsampleNEWLINE DecoderBlock([z_dim // 4, z_dim // 16, z_dim // 32]) # 4x uplsampeNEWLINE ])NEWLINE self.decoder_residual_blocks = nn.ModuleList([NEWLINE DecoderResidualBlock(z_dim // 2, n_group=4),NEWLINE DecoderResidualBlock(z_dim // 8, n_group=2),NEWLINE DecoderResidualBlock(z_dim // 32, n_group=1)NEWLINE ])NEWLINENEWLINE # p(z_l | z_(l-1))NEWLINE self.condition_z = nn.ModuleList([NEWLINE nn.Sequential(NEWLINE ResidualBlock(z_dim // 2),NEWLINE Swish(),NEWLINE nn.Conv2d(z_dim // 2, z_dim, kernel_size=1)NEWLINE ),NEWLINE nn.Sequential(NEWLINE ResidualBlock(z_dim // 8),NEWLINE Swish(),NEWLINE nn.Conv2d(z_dim // 8, z_dim // 4, kernel_size=1)NEWLINE )NEWLINE ])NEWLINENEWLINE # p(z_l | x, z_(l-1))NEWLINE self.condition_xz = nn.ModuleList([NEWLINE nn.Sequential(NEWLINE ResidualBlock(z_dim),NEWLINE nn.Conv2d(z_dim, z_dim // 2, kernel_size=1),NEWLINE Swish(),NEWLINE nn.Conv2d(z_dim // 2, z_dim, kernel_size=1)NEWLINE ),NEWLINE nn.Sequential(NEWLINE ResidualBlock(z_dim // 4),NEWLINE nn.Conv2d(z_dim // 4, z_dim // 8, kernel_size=1),NEWLINE Swish(),NEWLINE nn.Conv2d(z_dim // 8, z_dim // 4, kernel_size=1)NEWLINE )NEWLINE ])NEWLINENEWLINE self.recon = nn.Sequential(NEWLINE ResidualBlock(z_dim // 32),NEWLINE nn.Conv2d(z_dim // 32, 3, kernel_size=1),NEWLINE )NEWLINENEWLINE def forward(self, z, xs=None):NEWLINE """NEWLINE :param z: shape. = (B, z_dim, map_h, map_w)NEWLINE :return:NEWLINE """NEWLINENEWLINE B, D, map_h, map_w = z.shapeNEWLINENEWLINE # The init h (hidden state), can be replace with learned param, but it didn't work muchNEWLINE decoder_out = torch.zeros(B, D, map_h, map_w, device=z.device, dtype=z.dtype)NEWLINENEWLINE kl_losses = []NEWLINENEWLINE for i in range(len(self.decoder_residual_blocks)):NEWLINE z_sample = torch.cat([decoder_out, z], dim=1)NEWLINE decoder_out = self.decoder_residual_blocks[i](self.decoder_blocks[i](z_sample))NEWLINENEWLINE if i == len(self.decoder_residual_blocks) - 1:NEWLINE breakNEWLINENEWLINE mu, log_var = self.condition_z[i](decoder_out).chunk(2, dim=1)NEWLINENEWLINE if xs is not None:NEWLINE delta_mu, delta_log_var = self.condition_xz[i](torch.cat([xs[i], decoder_out], dim=1)).chunk(2, dim=1)NEWLINE kl_losses.append(kl_2(delta_mu, delta_log_var, mu, log_var))NEWLINE mu = mu + delta_muNEWLINE log_var = log_var + delta_log_varNEWLINENEWLINE z = Normal(mu, torch.exp(0.5 * log_var)).rsample()NEWLINE map_h *= 2**(len(self.decoder_blocks[i].channels) - 1)NEWLINE map_w *= 2**(len(self.decoder_blocks[i].channels) - 1)NEWLINENEWLINE x_hat = torch.sigmoid(self.recon(decoder_out))NEWLINENEWLINE return x_hat, kl_lossesNEWLINE
from rt_utils.rtstruct import RTStructNEWLINEimport pytestNEWLINEimport osNEWLINEfrom rt_utils import RTStructBuilderNEWLINENEWLINE@pytest.fixture()NEWLINEdef series_path() -> str:NEWLINE return get_and_test_series_path('mock_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef new_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('mock_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef oriented_series_path() -> RTStruct:NEWLINE return get_and_test_series_path('oriented_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef oriented_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('oriented_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef one_slice_series_path() -> RTStruct:NEWLINE return get_and_test_series_path('one_slice_data')NEWLINENEWLINE@pytest.fixture()NEWLINEdef one_slice_rtstruct() -> RTStruct:NEWLINE return get_rtstruct('one_slice_data')NEWLINENEWLINEdef get_rtstruct(dirname) -> RTStruct:NEWLINE path = get_and_test_series_path(dirname)NEWLINE rtstruct = RTStructBuilder.create_new(path)NEWLINE return rtstructNEWLINENEWLINEdef get_and_test_series_path(dirname) -> str:NEWLINE series_path = os.path.join(os.path.dirname(__file__), dirname)NEWLINE assert os.path.exists(series_path)NEWLINE return series_pathNEWLINE
# Generated by Django 2.2 on 2020-02-19 18:16NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('home', '0108_fullwidthpage_citations'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='custompage',NEWLINE name='page_ptr',NEWLINE field=models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='digestpageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='homepage',NEWLINE name='page_ptr',NEWLINE field=models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='pressreleasepageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE migrations.AlterField(NEWLINE model_name='recordpageauthors',NEWLINE name='author',NEWLINE field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='home.Author'),NEWLINE ),NEWLINE ]NEWLINE
# pylint: disable=no-value-for-parameterNEWLINENEWLINEimport dagster.check as checkNEWLINENEWLINEfrom dagster import (NEWLINE DependencyDefinition,NEWLINE InProcessExecutorConfig,NEWLINE InputDefinition,NEWLINE Int,NEWLINE List,NEWLINE ModeDefinition,NEWLINE MultiDependencyDefinition,NEWLINE Nothing,NEWLINE OutputDefinition,NEWLINE PipelineDefinition,NEWLINE ResourceDefinition,NEWLINE Output,NEWLINE Optional,NEWLINE RunConfig,NEWLINE SolidInvocation,NEWLINE String,NEWLINE execute_pipeline,NEWLINE execute_pipeline_iterator,NEWLINE lambda_solid,NEWLINE pipeline,NEWLINE solid,NEWLINE)NEWLINEfrom dagster.core.definitions import Solid, solids_in_topological_orderNEWLINEfrom dagster.core.definitions.dependency import DependencyStructureNEWLINEfrom dagster.core.definitions.container import _create_adjacency_listsNEWLINEfrom dagster.core.execution.api import step_output_event_filterNEWLINEfrom dagster.core.execution.config import ReexecutionConfigNEWLINEfrom dagster.core.execution.results import SolidExecutionResultNEWLINEfrom dagster.core.storage.intermediates_manager import StepOutputHandleNEWLINEfrom dagster.core.utility_solids import (NEWLINE define_stub_solid,NEWLINE create_root_solid,NEWLINE create_solid_with_deps,NEWLINE input_set,NEWLINE)NEWLINEfrom dagster.utils.test import execute_solid_within_pipelineNEWLINENEWLINE# protected membersNEWLINE# pylint: disable=W0212NEWLINENEWLINENEWLINEdef _default_passthrough_compute_fn(*args, **kwargs):NEWLINE check.invariant(not args, 'There should be no positional args')NEWLINE return list(kwargs.values())[0]NEWLINENEWLINENEWLINEdef create_dep_input_fn(name):NEWLINE return lambda context, arg_dict: {name: 'input_set'}NEWLINENEWLINENEWLINEdef make_compute_fn():NEWLINE def compute(context, inputs):NEWLINE passed_rows = []NEWLINE seen = set()NEWLINE for row in inputs.values():NEWLINE for item in row:NEWLINE key = list(item.keys())[0]NEWLINE if key not in seen:NEWLINE seen.add(key)NEWLINE passed_rows.append(item)NEWLINENEWLINE result = []NEWLINE result.extend(passed_rows)NEWLINE result.append({context.solid.name: 'compute_called'})NEWLINE return resultNEWLINENEWLINE return computeNEWLINENEWLINENEWLINEdef _do_construct(solids, dependencies):NEWLINE solids = {NEWLINE s.name: Solid(NEWLINE name=s.name, definition=s, resource_mapper_fn=SolidInvocation.default_resource_mapper_fnNEWLINE )NEWLINE for s in solidsNEWLINE }NEWLINE dependency_structure = DependencyStructure.from_definitions(solids, dependencies)NEWLINE return _create_adjacency_lists(list(solids.values()), dependency_structure)NEWLINENEWLINENEWLINEdef test_empty_adjaceny_lists():NEWLINE solids = [create_root_solid('a_node')]NEWLINE forward_edges, backwards_edges = _do_construct(solids, {})NEWLINE assert forward_edges == {'a_node': set()}NEWLINE assert backwards_edges == {'a_node': set()}NEWLINENEWLINENEWLINEdef test_single_dep_adjacency_lists():NEWLINE # A <-- BNEWLINE node_a = create_root_solid('A')NEWLINE node_b = create_solid_with_deps('B', node_a)NEWLINENEWLINE forward_edges, backwards_edges = _do_construct(NEWLINE [node_a, node_b], {'B': {'A': DependencyDefinition('A')}}NEWLINE )NEWLINENEWLINE assert forward_edges == {'A': {'B'}, 'B': set()}NEWLINE assert backwards_edges == {'B': {'A'}, 'A': set()}NEWLINENEWLINENEWLINEdef test_diamond_deps_adjaceny_lists():NEWLINE forward_edges, backwards_edges = _do_construct(create_diamond_solids(), diamond_deps())NEWLINENEWLINE assert forward_edges == {'A_source': {'A'}, 'A': {'B', 'C'}, 'B': {'D'}, 'C': {'D'}, 'D': set()}NEWLINE assert backwards_edges == {NEWLINE 'D': {'B', 'C'},NEWLINE 'B': {'A'},NEWLINE 'C': {'A'},NEWLINE 'A': {'A_source'},NEWLINE 'A_source': set(),NEWLINE }NEWLINENEWLINENEWLINEdef diamond_deps():NEWLINE return {NEWLINE 'A': {'A_input': DependencyDefinition('A_source')},NEWLINE 'B': {'A': DependencyDefinition('A')},NEWLINE 'C': {'A': DependencyDefinition('A')},NEWLINE 'D': {'B': DependencyDefinition('B'), 'C': DependencyDefinition('C')},NEWLINE }NEWLINENEWLINENEWLINEdef test_disconnected_graphs_adjaceny_lists():NEWLINE # A <-- BNEWLINE # C <-- DNEWLINE node_a = create_root_solid('A')NEWLINE node_b = create_solid_with_deps('B', node_a)NEWLINENEWLINE node_c = create_root_solid('C')NEWLINE node_d = create_solid_with_deps('D', node_c)NEWLINENEWLINE forward_edges, backwards_edges = _do_construct(NEWLINE [node_a, node_b, node_c, node_d],NEWLINE {'B': {'A': DependencyDefinition('A')}, 'D': {'C': DependencyDefinition('C')}},NEWLINE )NEWLINE assert forward_edges == {'A': {'B'}, 'B': set(), 'C': {'D'}, 'D': set()}NEWLINE assert backwards_edges == {'B': {'A'}, 'A': set(), 'D': {'C'}, 'C': set()}NEWLINENEWLINENEWLINEdef create_diamond_solids():NEWLINE a_source = define_stub_solid('A_source', [input_set('A_input')])NEWLINE node_a = create_root_solid('A')NEWLINE node_b = create_solid_with_deps('B', node_a)NEWLINE node_c = create_solid_with_deps('C', node_a)NEWLINE node_d = create_solid_with_deps('D', node_b, node_c)NEWLINE return [node_d, node_c, node_b, node_a, a_source]NEWLINENEWLINENEWLINEdef create_diamond_pipeline():NEWLINE return PipelineDefinition(NEWLINE name='diamond_pipeline', solid_defs=create_diamond_solids(), dependencies=diamond_deps()NEWLINE )NEWLINENEWLINENEWLINEdef test_diamond_toposort():NEWLINE assert [s.name for s in solids_in_topological_order(create_diamond_pipeline())] == [NEWLINE 'A_source',NEWLINE 'A',NEWLINE 'B',NEWLINE 'C',NEWLINE 'D',NEWLINE ]NEWLINENEWLINENEWLINEdef compute_called(name):NEWLINE return {name: 'compute_called'}NEWLINENEWLINENEWLINEdef assert_equivalent_results(left, right):NEWLINE check.inst_param(left, 'left', SolidExecutionResult)NEWLINE check.inst_param(right, 'right', SolidExecutionResult)NEWLINENEWLINE assert left.success == right.successNEWLINE assert left.name == right.nameNEWLINE assert left.solid.name == right.solid.nameNEWLINE assert left.output_value() == right.output_value()NEWLINENEWLINENEWLINEdef assert_all_results_equivalent(expected_results, result_results):NEWLINE check.list_param(expected_results, 'expected_results', of_type=SolidExecutionResult)NEWLINE check.list_param(result_results, 'result_results', of_type=SolidExecutionResult)NEWLINE assert len(expected_results) == len(result_results)NEWLINE for expected, result in zip(expected_results, result_results):NEWLINE assert_equivalent_results(expected, result)NEWLINENEWLINENEWLINEdef test_pipeline_execution_graph_diamond():NEWLINE pipe = PipelineDefinition(solid_defs=create_diamond_solids(), dependencies=diamond_deps())NEWLINE return _do_test(pipe)NEWLINENEWLINENEWLINEdef test_execute_solid_in_diamond():NEWLINE solid_result = execute_solid_within_pipeline(NEWLINE create_diamond_pipeline(), 'A', inputs={'A_input': [{'a key': 'a value'}]}NEWLINE )NEWLINENEWLINE assert solid_result.successNEWLINE assert solid_result.output_value() == [{'a key': 'a value'}, {'A': 'compute_called'}]NEWLINENEWLINENEWLINEdef test_execute_aliased_solid_in_diamond():NEWLINE a_source = define_stub_solid('A_source', [input_set('A_input')])NEWLINENEWLINE @pipelineNEWLINE def aliased_pipeline():NEWLINE create_root_solid('A').alias('aliased')(a_source())NEWLINENEWLINE solid_result = execute_solid_within_pipeline(NEWLINE aliased_pipeline, 'aliased', inputs={'A_input': [{'a key': 'a value'}]}NEWLINE )NEWLINENEWLINE assert solid_result.successNEWLINE assert solid_result.output_value() == [{'a key': 'a value'}, {'aliased': 'compute_called'}]NEWLINENEWLINENEWLINEdef test_create_pipeline_with_empty_solids_list():NEWLINE @pipelineNEWLINE def empty_pipe():NEWLINE passNEWLINENEWLINE assert execute_pipeline(empty_pipe).successNEWLINENEWLINENEWLINEdef test_singleton_pipeline():NEWLINE stub_solid = define_stub_solid('stub', [{'a key': 'a value'}])NEWLINENEWLINE @pipelineNEWLINE def single_solid_pipeline():NEWLINE stub_solid()NEWLINENEWLINE assert execute_pipeline(single_solid_pipeline).successNEWLINENEWLINENEWLINEdef test_two_root_solid_pipeline_with_empty_dependency_definition():NEWLINE stub_solid_a = define_stub_solid('stub_a', [{'a key': 'a value'}])NEWLINE stub_solid_b = define_stub_solid('stub_b', [{'a key': 'a value'}])NEWLINENEWLINE @pipelineNEWLINE def pipe():NEWLINE stub_solid_a()NEWLINE stub_solid_b()NEWLINENEWLINE assert execute_pipeline(pipe).successNEWLINENEWLINENEWLINEdef test_two_root_solid_pipeline_with_partial_dependency_definition():NEWLINE stub_solid_a = define_stub_solid('stub_a', [{'a key': 'a value'}])NEWLINE stub_solid_b = define_stub_solid('stub_b', [{'a key': 'a value'}])NEWLINENEWLINE single_dep_pipe = PipelineDefinition(NEWLINE solid_defs=[stub_solid_a, stub_solid_b], dependencies={'stub_a': {}}NEWLINE )NEWLINENEWLINE assert execute_pipeline(single_dep_pipe).successNEWLINENEWLINENEWLINEdef _do_test(pipe):NEWLINE result = execute_pipeline(pipe)NEWLINENEWLINE assert result.result_for_solid('A').output_value() == [NEWLINE input_set('A_input'),NEWLINE compute_called('A'),NEWLINE ]NEWLINENEWLINE assert result.result_for_solid('B').output_value() == [NEWLINE input_set('A_input'),NEWLINE compute_called('A'),NEWLINE compute_called('B'),NEWLINE ]NEWLINENEWLINE assert result.result_for_solid('C').output_value() == [NEWLINE input_set('A_input'),NEWLINE compute_called('A'),NEWLINE compute_called('C'),NEWLINE ]NEWLINENEWLINE assert result.result_for_solid('D').output_value() == [NEWLINE input_set('A_input'),NEWLINE compute_called('A'),NEWLINE compute_called('C'),NEWLINE compute_called('B'),NEWLINE compute_called('D'),NEWLINE ] or result.result_for_solid('D').output_value() == [NEWLINE input_set('A_input'),NEWLINE compute_called('A'),NEWLINE compute_called('B'),NEWLINE compute_called('C'),NEWLINE compute_called('D'),NEWLINE ]NEWLINENEWLINENEWLINEdef test_empty_pipeline_execution():NEWLINE result = execute_pipeline(PipelineDefinition(solid_defs=[]))NEWLINENEWLINE assert result.successNEWLINENEWLINENEWLINEdef test_pipeline_name_threaded_through_context():NEWLINE name = 'foobar'NEWLINENEWLINE @solid()NEWLINE def assert_name_solid(context):NEWLINE assert context.pipeline_def.name == nameNEWLINENEWLINE result = execute_pipeline(PipelineDefinition(name="foobar", solid_defs=[assert_name_solid]))NEWLINENEWLINE assert result.successNEWLINENEWLINE for step_event in step_output_event_filter(NEWLINE execute_pipeline_iterator(NEWLINE PipelineDefinition(name="foobar", solid_defs=[assert_name_solid]), {}NEWLINE )NEWLINE ):NEWLINE assert step_event.is_step_successNEWLINENEWLINENEWLINEdef test_pipeline_subset():NEWLINE @lambda_solidNEWLINE def return_one():NEWLINE return 1NEWLINENEWLINE @lambda_solidNEWLINE def add_one(num):NEWLINE return num + 1NEWLINENEWLINE pipeline_def = PipelineDefinition(NEWLINE solid_defs=[return_one, add_one],NEWLINE dependencies={'add_one': {'num': DependencyDefinition('return_one')}},NEWLINE )NEWLINENEWLINE pipeline_result = execute_pipeline(pipeline_def)NEWLINE assert pipeline_result.successNEWLINE assert pipeline_result.result_for_solid('add_one').output_value() == 2NEWLINENEWLINE env_config = {'solids': {'add_one': {'inputs': {'num': {'value': 3}}}}}NEWLINENEWLINE subset_result = execute_pipeline(NEWLINE pipeline_def.build_sub_pipeline(['add_one']), environment_dict=env_configNEWLINE )NEWLINENEWLINE assert subset_result.successNEWLINE assert len(subset_result.solid_result_list) == 1NEWLINE assert subset_result.result_for_solid('add_one').output_value() == 4NEWLINENEWLINE events = execute_pipeline_iterator(NEWLINE pipeline_def.build_sub_pipeline(['add_one']), environment_dict=env_configNEWLINE )NEWLINENEWLINE for step_event in step_output_event_filter(events):NEWLINE assert step_event.is_step_successNEWLINENEWLINENEWLINEdef test_pipeline_subset_with_multi_dependency():NEWLINE @lambda_solidNEWLINE def return_one():NEWLINE return 1NEWLINENEWLINE @lambda_solidNEWLINE def return_two():NEWLINE return 2NEWLINENEWLINE @lambda_solid(input_defs=[InputDefinition('dep', Nothing)])NEWLINE def noop():NEWLINE return 3NEWLINENEWLINE pipeline_def = PipelineDefinition(NEWLINE solid_defs=[return_one, return_two, noop],NEWLINE dependencies={NEWLINE 'noop': {NEWLINE 'dep': MultiDependencyDefinition(NEWLINE [DependencyDefinition('return_one'), DependencyDefinition('return_two')]NEWLINE )NEWLINE }NEWLINE },NEWLINE )NEWLINENEWLINE pipeline_result = execute_pipeline(pipeline_def)NEWLINE assert pipeline_result.successNEWLINE assert pipeline_result.result_for_solid('noop').output_value() == 3NEWLINENEWLINE subset_result = execute_pipeline(pipeline_def.build_sub_pipeline(['noop']))NEWLINENEWLINE assert subset_result.successNEWLINE assert len(subset_result.solid_result_list) == 1NEWLINE assert pipeline_result.result_for_solid('noop').output_value() == 3NEWLINENEWLINE events = execute_pipeline_iterator(pipeline_def.build_sub_pipeline(['noop']))NEWLINENEWLINE for step_event in step_output_event_filter(events):NEWLINE assert step_event.is_step_successNEWLINENEWLINE subset_result = execute_pipeline(NEWLINE pipeline_def.build_sub_pipeline(['return_one', 'return_two', 'noop'])NEWLINE )NEWLINENEWLINE assert subset_result.successNEWLINE assert len(subset_result.solid_result_list) == 3NEWLINE assert pipeline_result.result_for_solid('noop').output_value() == 3NEWLINENEWLINENEWLINEdef define_three_part_pipeline():NEWLINE @lambda_solid(input_defs=[InputDefinition('num', Int)], output_def=OutputDefinition(Int))NEWLINE def add_one(num):NEWLINE return num + 1NEWLINENEWLINE @lambda_solid(input_defs=[InputDefinition('num', Int)], output_def=OutputDefinition(Int))NEWLINE def add_two(num):NEWLINE return num + 2NEWLINENEWLINE @lambda_solid(input_defs=[InputDefinition('num', Int)], output_def=OutputDefinition(Int))NEWLINE def add_three(num):NEWLINE return num + 3NEWLINENEWLINE return PipelineDefinition(name='three_part_pipeline', solid_defs=[add_one, add_two, add_three])NEWLINENEWLINENEWLINEdef define_created_disjoint_three_part_pipeline():NEWLINE return define_three_part_pipeline().build_sub_pipeline(['add_one', 'add_three'])NEWLINENEWLINENEWLINEdef test_pipeline_disjoint_subset():NEWLINE disjoint_pipeline = define_three_part_pipeline().build_sub_pipeline(['add_one', 'add_three'])NEWLINE assert len(disjoint_pipeline.solids) == 2NEWLINENEWLINENEWLINEdef test_pipeline_execution_disjoint_subset():NEWLINE env_config = {NEWLINE 'solids': {NEWLINE 'add_one': {'inputs': {'num': {'value': 2}}},NEWLINE 'add_three': {'inputs': {'num': {'value': 5}}},NEWLINE },NEWLINE 'loggers': {'console': {'config': {'log_level': 'ERROR'}}},NEWLINE }NEWLINENEWLINE pipeline_def = define_created_disjoint_three_part_pipeline()NEWLINENEWLINE result = execute_pipeline(NEWLINE pipeline_def.build_sub_pipeline(['add_one', 'add_three']), environment_dict=env_configNEWLINE )NEWLINENEWLINE assert result.successNEWLINE assert len(result.solid_result_list) == 2NEWLINE assert result.result_for_solid('add_one').output_value() == 3NEWLINE assert result.result_for_solid('add_three').output_value() == 8NEWLINENEWLINENEWLINEdef test_pipeline_wrapping_types():NEWLINE @lambda_solid(NEWLINE input_defs=[InputDefinition('value', Optional[List[Optional[String]]])],NEWLINE output_def=OutputDefinition(Optional[List[Optional[String]]]),NEWLINE )NEWLINE def double_string_for_all(value):NEWLINE if not value:NEWLINE return valueNEWLINENEWLINE output = []NEWLINE for item in value:NEWLINE output.append(None if item is None else item + item)NEWLINE return outputNEWLINENEWLINE @pipelineNEWLINE def wrapping_test():NEWLINE double_string_for_all()NEWLINENEWLINE assert execute_pipeline(NEWLINE wrapping_test,NEWLINE environment_dict={'solids': {'double_string_for_all': {'inputs': {'value': None}}}},NEWLINE ).successNEWLINENEWLINE assert execute_pipeline(NEWLINE wrapping_test,NEWLINE environment_dict={'solids': {'double_string_for_all': {'inputs': {'value': []}}}},NEWLINE ).successNEWLINENEWLINE assert execute_pipeline(NEWLINE wrapping_test,NEWLINE environment_dict={NEWLINE 'solids': {'double_string_for_all': {'inputs': {'value': [{'value': 'foo'}]}}}NEWLINE },NEWLINE ).successNEWLINENEWLINE assert execute_pipeline(NEWLINE wrapping_test,NEWLINE environment_dict={NEWLINE 'solids': {'double_string_for_all': {'inputs': {'value': [{'value': 'bar'}, None]}}}NEWLINE },NEWLINE ).successNEWLINENEWLINENEWLINEdef test_pipeline_streaming_iterator():NEWLINE events = []NEWLINENEWLINE @lambda_solidNEWLINE def push_one():NEWLINE events.append(1)NEWLINE return 1NEWLINENEWLINE @lambda_solidNEWLINE def add_one(num):NEWLINE events.append(num + 1)NEWLINE return num + 1NEWLINENEWLINE @pipelineNEWLINE def test_streaming_iterator():NEWLINE add_one(push_one())NEWLINENEWLINE step_event_iterator = step_output_event_filter(NEWLINE execute_pipeline_iterator(test_streaming_iterator)NEWLINE )NEWLINENEWLINE push_one_step_event = next(step_event_iterator)NEWLINE assert push_one_step_event.is_successful_outputNEWLINE assert events == [1]NEWLINENEWLINE add_one_step_event = next(step_event_iterator)NEWLINE assert add_one_step_event.is_successful_outputNEWLINE assert events == [1, 2]NEWLINENEWLINENEWLINEdef test_pipeline_streaming_multiple_outputs():NEWLINE events = []NEWLINENEWLINE @solid(output_defs=[OutputDefinition(Int, 'one'), OutputDefinition(Int, 'two')])NEWLINE def push_one_two(_context):NEWLINE events.append(1)NEWLINE yield Output(1, 'one')NEWLINE events.append(2)NEWLINE yield Output(2, 'two')NEWLINENEWLINE @pipelineNEWLINE def test_streaming_iterator_multiple_outputs():NEWLINE push_one_two()NEWLINENEWLINE step_event_iterator = step_output_event_filter(NEWLINE execute_pipeline_iterator(test_streaming_iterator_multiple_outputs)NEWLINE )NEWLINENEWLINE one_output_step_event = next(step_event_iterator)NEWLINE assert one_output_step_event.is_successful_outputNEWLINE assert one_output_step_event.step_output_data.output_name == 'one'NEWLINE assert events == [1]NEWLINENEWLINE two_output_step_event = next(step_event_iterator)NEWLINE assert two_output_step_event.is_successful_outputNEWLINE assert two_output_step_event.step_output_data.output_name == 'two'NEWLINE assert events == [1, 2]NEWLINENEWLINENEWLINEdef test_pipeline_init_failure():NEWLINE stub_solid = define_stub_solid('stub', None)NEWLINE env_config = {}NEWLINENEWLINE def failing_resource_fn(*args, **kwargs):NEWLINE raise Exception()NEWLINENEWLINE @pipeline(NEWLINE mode_defs=[NEWLINE ModeDefinition(NEWLINE resource_defs={'failing': ResourceDefinition(resource_fn=failing_resource_fn)}NEWLINE )NEWLINE ]NEWLINE )NEWLINE def failing_init_pipeline():NEWLINE stub_solid()NEWLINENEWLINE result = execute_pipeline(NEWLINE failing_init_pipeline,NEWLINE environment_dict=env_config,NEWLINE run_config=RunConfig(executor_config=InProcessExecutorConfig(raise_on_error=False)),NEWLINE )NEWLINENEWLINE assert result.success is FalseNEWLINE assert len(result.event_list) == 1NEWLINE event = result.event_list[0]NEWLINE assert event.event_type_value == 'PIPELINE_INIT_FAILURE'NEWLINE assert event.pipeline_init_failure_dataNEWLINENEWLINENEWLINEdef test_reexecution():NEWLINE @lambda_solidNEWLINE def return_one():NEWLINE return 1NEWLINENEWLINE @lambda_solidNEWLINE def add_one(num):NEWLINE return num + 1NEWLINENEWLINE pipeline_def = PipelineDefinition(NEWLINE solid_defs=[return_one, add_one],NEWLINE dependencies={'add_one': {'num': DependencyDefinition('return_one')}},NEWLINE )NEWLINENEWLINE pipeline_result = execute_pipeline(NEWLINE pipeline_def, environment_dict={'storage': {'filesystem': {}}}NEWLINE )NEWLINE assert pipeline_result.successNEWLINE assert pipeline_result.result_for_solid('add_one').output_value() == 2NEWLINENEWLINE reexecution_run_config = RunConfig(NEWLINE reexecution_config=ReexecutionConfig(NEWLINE previous_run_id=pipeline_result.run_id,NEWLINE step_output_handles=[StepOutputHandle('return_one.compute')],NEWLINE )NEWLINE )NEWLINE reexecution_result = execute_pipeline(NEWLINE pipeline_def,NEWLINE environment_dict={'storage': {'filesystem': {}}},NEWLINE run_config=reexecution_run_config,NEWLINE )NEWLINENEWLINE assert reexecution_result.successNEWLINE assert len(reexecution_result.solid_result_list) == 2NEWLINE assert reexecution_result.result_for_solid('return_one').output_value() == 1NEWLINE assert reexecution_result.result_for_solid('add_one').output_value() == 2NEWLINE
"""NEWLINECreated on Apr 18, 2017NEWLINENEWLINE@author: Christopher BrunsNEWLINE"""NEWLINENEWLINEimport osNEWLINENEWLINEimport numpyNEWLINEfrom OpenGL import GLNEWLINEfrom OpenGL.GL.shaders import compileShader, compileProgramNEWLINEfrom OpenGL.arrays import vboNEWLINENEWLINEfrom openvr.glframework.glmatrix import identity, pack, rotate_y, scaleNEWLINEfrom openvr.glframework import shader_stringNEWLINENEWLINENEWLINEclass TriangleActor(object):NEWLINE def __init__(self):NEWLINE self.vao = NoneNEWLINE # hard-code shader parameter location indexNEWLINE self.mvp_location = 0NEWLINE self.program = NoneNEWLINE # Create triangle geometry: corner 2D location and colorsNEWLINE self.vertices = vbo.VBO(numpy.array([NEWLINE [-0.6, -0.4, 1.0, 0.0, 0.0], # x, y, r, g, bNEWLINE [0.6, -0.4, 0.0, 1.0, 0.0],NEWLINE [0.0, 0.6, 0.0, 0.0, 1.0],NEWLINE ], dtype='float32'))NEWLINENEWLINE def init_gl(self):NEWLINE # Create vertex array object, apparently required for modern OpenGLNEWLINE self.vao = GL.glGenVertexArrays(1)NEWLINE GL.glBindVertexArray(self.vao)NEWLINE self.vertices.bind()NEWLINE # hard-code shader parameter location indicesNEWLINE vpos_location = 0NEWLINE vcol_location = 1NEWLINE GL.glEnableVertexAttribArray(vpos_location)NEWLINE float_size = self.vertices.dtype.itemsize # 4 bytes per float32NEWLINE GL.glVertexAttribPointer(vpos_location, 2, GL.GL_FLOAT, False,NEWLINE float_size * 5, self.vertices + float_size * 0)NEWLINE GL.glEnableVertexAttribArray(vcol_location)NEWLINE GL.glVertexAttribPointer(vcol_location, 3, GL.GL_FLOAT, False,NEWLINE float_size * 5, self.vertices + float_size * 2)NEWLINE # Create GLSL shader programNEWLINE vertex_shader = compileShader(NEWLINE """#version 450 coreNEWLINE #line 50NEWLINE NEWLINE layout(location = %d) uniform mat4 MVP = mat4(1);NEWLINE NEWLINE layout(location = %d) in vec2 vPos;NEWLINE layout(location = %d) in vec3 vCol;NEWLINE NEWLINE out vec3 color;NEWLINE NEWLINE void main() NEWLINE {NEWLINE gl_Position = MVP * vec4(vPos, 0.0, 1.0);NEWLINE color = vCol;NEWLINE }NEWLINE """ % (self.mvp_location, vpos_location, vcol_location),NEWLINE GL.GL_VERTEX_SHADER)NEWLINE fragment_shader = compileShader(NEWLINE """#version 450 coreNEWLINE #line 68NEWLINE NEWLINE in vec3 color;NEWLINE out vec4 fragColor;NEWLINE NEWLINE void main() NEWLINE {NEWLINE fragColor = vec4(color, 1);NEWLINE }NEWLINE """,NEWLINE GL.GL_FRAGMENT_SHADER)NEWLINE self.program = compileProgram(vertex_shader, fragment_shader)NEWLINENEWLINE def display_gl(self, model_view, projection):NEWLINE GL.glBindVertexArray(self.vao)NEWLINE GL.glUseProgram(self.program)NEWLINE mvp = numpy.matrix(model_view) * projectionNEWLINE GL.glUniformMatrix4fv(self.mvp_location, 1, False, pack(mvp))NEWLINE GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)NEWLINENEWLINE def dispose_gl(self):NEWLINE if self.vao:NEWLINE GL.glDeleteVertexArrays(1, [self.vao, ])NEWLINE self.vertices.delete()NEWLINE GL.glDeleteProgram(self.program)NEWLINENEWLINENEWLINEclass ObjActor(object):NEWLINE def __init__(self, obj_stream):NEWLINE self.model_matrix = identity()NEWLINE self.vao = NoneNEWLINE self.shader = NoneNEWLINE self.vertexes = list()NEWLINE vertex_normals = list()NEWLINE self.normal_for_vertex = dict()NEWLINE self.faces = list()NEWLINE fh = obj_streamNEWLINE for line in fh:NEWLINE if line.startswith('#'):NEWLINE # e.g. "# Blender v2.65 (sub 0) OBJ File"NEWLINE continue # ignore commentsNEWLINE elif line.startswith('o '):NEWLINE # e.g. "o teapot.005"NEWLINE continue # ignore object namesNEWLINE elif line.startswith('v '):NEWLINE # e.g. "v -0.498530 0.712498 -0.039883"NEWLINE vec3 = [float(x) for x in line.split()[1:4]]NEWLINE self.vertexes.append(vec3)NEWLINE elif line.startswith('vn '):NEWLINE # e.g. "vn -0.901883 0.415418 0.118168"NEWLINE vec3 = [float(x) for x in line.split()[1:4]]NEWLINE vertex_normals.append(vec3)NEWLINE elif line.startswith('s '):NEWLINE continue # ignore whatever "s" isNEWLINE # print(line)NEWLINE elif line.startswith('f '):NEWLINE face = list()NEWLINE for c in line.split()[1:]:NEWLINE v, n = [int(x) for x in c.split('/')[0:3:2]]NEWLINE face.append(v - 1) # vertex indexNEWLINE self.normal_for_vertex[v - 1] = vertex_normals[n - 1]NEWLINE self.faces.append(face)NEWLINE # print(line)NEWLINE # print(face)NEWLINE else:NEWLINE print(line)NEWLINE breakNEWLINE self.vbo = list()NEWLINE ibo = list()NEWLINE for i in range(len(self.vertexes)):NEWLINE v = self.vertexes[i]NEWLINE n = self.normal_for_vertex[i]NEWLINE self.vbo.append(v)NEWLINE self.vbo.append(n)NEWLINE for f in self.faces:NEWLINE for v in f:NEWLINE ibo.append(v)NEWLINE # todo: only works for single triangle faces at the moment...NEWLINE self.element_count = len(ibo)NEWLINE self.vbo = numpy.array(self.vbo, 'float32')NEWLINE ibo = numpy.array(ibo, 'int16')NEWLINE self.vbo = vbo.VBO(self.vbo)NEWLINE self.ibo = vbo.VBO(ibo, target=GL.GL_ELEMENT_ARRAY_BUFFER)NEWLINENEWLINE def init_gl(self):NEWLINE self.vao = GL.glGenVertexArrays(1)NEWLINE GL.glBindVertexArray(self.vao)NEWLINE self.ibo.bind()NEWLINE self.vbo.bind()NEWLINE GL.glEnableVertexAttribArray(0) # vertex locationNEWLINE float_size = self.vbo.dtype.itemsize # 4 bytes per float32NEWLINE GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False,NEWLINE 6 * float_size, self.vbo + 0 * float_size)NEWLINE GL.glEnableVertexAttribArray(1) # vertex normalNEWLINE GL.glVertexAttribPointer(1, 3, GL.GL_FLOAT, False,NEWLINE 6 * float_size, self.vbo + 3 * float_size)NEWLINE vertex_shader = compileShader(NEWLINE shader_string("""NEWLINE layout(location = 0) in vec3 in_Position;NEWLINE layout(location = 1) in vec3 in_Normal;NEWLINENEWLINE layout(location = 0) uniform mat4 projection = mat4(1);NEWLINE layout(location = 1) uniform mat4 model_view = mat4(1);NEWLINENEWLINE out vec3 normal;NEWLINENEWLINE void main() NEWLINE {NEWLINE gl_Position = projection * model_view * vec4(in_Position, 1.0);NEWLINE mat4 normal_matrix = transpose(inverse(model_view));NEWLINE normal = normalize((normal_matrix * vec4(in_Normal, 0)).xyz);NEWLINE }NEWLINE """),NEWLINE GL.GL_VERTEX_SHADER)NEWLINE fragment_shader = compileShader(NEWLINE shader_string(""" in vec3 normal;NEWLINE out vec4 fragColor;NEWLINENEWLINE vec4 color_by_normal(in vec3 n) {NEWLINE return vec4(0.5 * (normalize(n) + vec3(1)), 1);NEWLINE }NEWLINENEWLINE void main() NEWLINE {NEWLINE fragColor = color_by_normal(normal);NEWLINE }NEWLINE """),NEWLINE GL.GL_FRAGMENT_SHADER)NEWLINE self.shader = compileProgram(vertex_shader, fragment_shader)NEWLINE GL.glEnable(GL.GL_DEPTH_TEST)NEWLINENEWLINE def display_gl(self, model_view, projection):NEWLINE GL.glBindVertexArray(self.vao)NEWLINE GL.glUseProgram(self.shader)NEWLINE m = self.model_matrix * model_viewNEWLINE GL.glUniformMatrix4fv(0, 1, False, pack(projection))NEWLINE GL.glUniformMatrix4fv(1, 1, False, pack(m))NEWLINE GL.glDrawElements(GL.GL_TRIANGLES, self.element_count, GL.GL_UNSIGNED_SHORT, None)NEWLINENEWLINE def dispose_gl(self):NEWLINE if self.vao:NEWLINE GL.glDeleteVertexArrays(1, [self.vao, ])NEWLINE self.ibo.delete()NEWLINE self.vbo.delete()NEWLINE GL.glDeleteProgram(self.shader)NEWLINE self.vao = NoneNEWLINENEWLINENEWLINEclass TeapotActor(ObjActor):NEWLINE def __init__(self):NEWLINE src_folder = os.path.dirname(os.path.abspath(__file__))NEWLINE obj_path = os.path.join(src_folder, 'wt_teapot.obj')NEWLINE with open(obj_path) as fh:NEWLINE super(TeapotActor, self).__init__(obj_stream=fh)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE from openvr.glframework.glfw_app import GlfwVrAppNEWLINE import glfwNEWLINE teapot = TeapotActor()NEWLINE s = 0.2 # size of teapot in metersNEWLINE with GlfwVrApp(actors=[teapot, ]) as app:NEWLINE while not glfw.window_should_close(app.window):NEWLINE # scale teapot to original Melitta model aspect ratioNEWLINE teapot.model_matrix = scale(s, s*4/3, s) * rotate_y(glfw.get_time())NEWLINE app.render_scene()NEWLINE
# Generated by Django 3.2 on 2021-06-24 12:18NEWLINENEWLINEfrom django.db import migrations, modelsNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('blog_email', '0001_initial'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.AlterField(NEWLINE model_name='email',NEWLINE name='id',NEWLINE field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),NEWLINE ),NEWLINE ]NEWLINE
import cv2NEWLINEimport osNEWLINEimport csvNEWLINEimport parzen.PARZEN as parzenNEWLINENEWLINENEWLINEdef extract_features(image_path, vector_size, label):NEWLINE img = cv2.imread(image_path)NEWLINE gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)NEWLINE small = cv2.resize(gray, (vector_size, vector_size))NEWLINENEWLINE small = small.flatten()NEWLINE features = (small).tolist()NEWLINE features[-1] = str(label)NEWLINENEWLINE return featuresNEWLINENEWLINENEWLINEdef write_csv(images_path='persian_number/'):NEWLINE files = [os.path.join(images_path, p) for p in sorted(os.listdir(images_path))]NEWLINE final_path = {}NEWLINE database = []NEWLINE for f in files:NEWLINE tmp_list = [os.path.join(f, p) for p in sorted(os.listdir(f))]NEWLINE # tmp_list[-1] = f[8:]NEWLINE final_path[f[15:]] = (tmp_list)NEWLINE # print(f[15:])NEWLINE with open('file.csv', "w") as csv_file:NEWLINE for key, value in final_path.items():NEWLINE writer = csv.writer(csv_file, delimiter=',')NEWLINE for path in value:NEWLINE writer.writerow(extract_features(path, 30, key))NEWLINENEWLINENEWLINEwrite_csv()NEWLINENEWLINE# dosent work for these featureNEWLINE# radius = [0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1, 2, 3, 4]NEWLINE#NEWLINE# my_parzen = parzen.ParzenClassifier(csv_file='file.csv', data=None, r=radius, weight=.90)NEWLINE# radius_accuracy_dict, best_radius = my_parzen.kfold_validation(10)NEWLINE#NEWLINE# test, predicted = my_parzen.test(best_radius)NEWLINE#NEWLINE# ac, cm, re = my_parzen.report(test, predicted)NEWLINE#NEWLINE# print(re, "\n")NEWLINE# print(cm, "\n")NEWLINE# print(ac, "\n")NEWLINE
#!/usr/bin/env python3NEWLINE# SPDX-License-Identifier: Apache-2.0NEWLINE# Copyright (C) 2010-2021 Intel CorporationNEWLINE"""NEWLINELMS DBus interface unit-testsNEWLINENEWLINECall every DBus method, should not throw exception.NEWLINETest also incorrect input.NEWLINENEWLINETODO: Alarm, check output.NEWLINE"""NEWLINEimport unittestNEWLINEimport dbusNEWLINENEWLINEDBUS_DEST = 'com.intel.amt.lms'NEWLINEDBUS_OBJ = '/com/intel/amt/lms'NEWLINEDBUS_IFACE = 'com.intel.amt.lms.'NEWLINENEWLINEclass ManageabilityTestCase(unittest.TestCase):NEWLINE """Manageability interface test"""NEWLINENEWLINE def setUp(self):NEWLINE bus = dbus.SystemBus()NEWLINE proxy = bus.get_object(DBUS_DEST, DBUS_OBJ)NEWLINE self.iface = dbus.Interface(proxy,NEWLINE dbus_interface=DBUS_IFACE + 'Manageability')NEWLINENEWLINE def tearDown(self):NEWLINE #os.close(self.fd)NEWLINE passNEWLINENEWLINE def test_GetTheFeatureState(self):NEWLINE '''GetTheFeatureState test method'''NEWLINE for i in [x for x in range(0, 21) if x not in (6, 8)]:NEWLINE with self.subTest(i=i):NEWLINE self.iface.GetTheFeatureState(i)NEWLINE for i in (22, 100000000):NEWLINE with self.subTest(i=i):NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.GetTheFeatureState(i)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINENEWLINE def test_GetCustomerType(self):NEWLINE '''GetCustomerType test method'''NEWLINE self.iface.GetCustomerType()NEWLINENEWLINE def test_GetMenageabiltyMode(self):NEWLINE '''GetMenageabiltyMode test method'''NEWLINE self.iface.GetMenageabiltyMode()NEWLINENEWLINE def test_GetFWInfo(self):NEWLINE '''GetFWInfo test method'''NEWLINE self.iface.GetFWInfo()NEWLINENEWLINE def test_GetPMCVersion(self):NEWLINE '''GetPMCVersion test method'''NEWLINE self.iface.GetPMCVersion()NEWLINENEWLINE def test_IsMeasuredBootState(self):NEWLINE '''IsMeasuredBootState test method'''NEWLINE try:NEWLINE self.iface.IsMeasuredBootState()NEWLINE except dbus.exceptions.DBusException as the_exp:NEWLINE self.assertEqual(the_exp.get_dbus_message(), 'Request is not supported by system')NEWLINENEWLINEclass PTHITestCase(unittest.TestCase):NEWLINE """PTHI interface test"""NEWLINENEWLINE def setUp(self):NEWLINE bus = dbus.SystemBus()NEWLINE proxy = bus.get_object(DBUS_DEST, DBUS_OBJ)NEWLINE self.iface = dbus.Interface(proxy,NEWLINE dbus_interface=DBUS_IFACE + 'PTHI')NEWLINENEWLINE def tearDown(self):NEWLINE #os.close(self.fd)NEWLINE passNEWLINENEWLINE def test_GetAMTVersion(self):NEWLINE '''GetAMTVersion test method'''NEWLINE self.iface.GetAMTVersion()NEWLINENEWLINE def test_GetLMSVersion(self):NEWLINE '''GetLMSVersion test method'''NEWLINE self.iface.GetLMSVersion()NEWLINENEWLINE def test_GetProvisioningState(self):NEWLINE '''GetProvisioningState test method'''NEWLINE self.iface.GetProvisioningState()NEWLINENEWLINE def test_GetNetworkConnectionStatus(self):NEWLINE '''GetNetworkConnectionStatus test method'''NEWLINE self.iface.GetNetworkConnectionStatus()NEWLINENEWLINE def test_GetUserInitiatedEnabled(self):NEWLINE '''GetUserInitiatedEnabled test method'''NEWLINE self.iface.GetUserInitiatedEnabled()NEWLINENEWLINE def test_GetPowerPolicy(self):NEWLINE '''GetPowerPolicy test method'''NEWLINE self.iface.GetPowerPolicy()NEWLINENEWLINE def test_GetLastResetReason(self):NEWLINE '''GetLastResetReason test method'''NEWLINE self.iface.GetLastResetReason()NEWLINENEWLINE def test_GetRedirectionStatus(self):NEWLINE '''GetRedirectionStatus test method'''NEWLINE self.iface.GetRedirectionStatus()NEWLINENEWLINE def test_GetSystemDefenseStatus(self):NEWLINE '''GetSystemDefenseStatus test method'''NEWLINE self.iface.GetSystemDefenseStatus()NEWLINENEWLINE def test_GetNetworkSettingsWired(self):NEWLINE '''GetNetworkSettings test method (wired)'''NEWLINE self.iface.GetNetworkSettings(0)NEWLINENEWLINE @unittest.skip("Requires wireless card")NEWLINE def test_GetNetworkSettingsWireless(self):NEWLINE '''GetNetworkSettings test method (wireless)'''NEWLINE self.iface.GetNetworkSettings(1)NEWLINENEWLINE def test_GetNetworkSettingsFail(self):NEWLINE '''GetNetworkSettings test method (wrong parameters)'''NEWLINE for i in (2, 100000000):NEWLINE with self.subTest(i=i):NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.GetNetworkSettings(i)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINENEWLINE def test_GetIPv6NetworkSettingsWired(self):NEWLINE '''GetIPv6NetworkSettings test method (wired)'''NEWLINE self.iface.GetIPv6NetworkSettings(0)NEWLINENEWLINE @unittest.skip("Requires wireless card")NEWLINE def test_GetIPv6NetworkSettingsWireless(self):NEWLINE '''GetIPv6NetworkSettings test method (wireless)'''NEWLINE self.iface.GetIPv6NetworkSettings(1)NEWLINENEWLINE def test_GetIPv6NetworkSettingsFail(self):NEWLINE '''GetIPv6NetworkSettings test method (wrong parameters)'''NEWLINE for i in (2, 100000000):NEWLINE with self.subTest(i=i):NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.GetIPv6NetworkSettings(i)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINENEWLINE def test_GetSystemUUID(self):NEWLINE '''GetSystemUUID test method'''NEWLINE self.iface.GetSystemUUID()NEWLINENEWLINE @unittest.skip("Requires provisioned FW")NEWLINE def test_UserInitiatedConnection(self):NEWLINE '''*UserInitiatedConnection test method'''NEWLINE self.iface.InitiateUserConnection()NEWLINE self.iface.CloseUserInitiatedConnection()NEWLINENEWLINE def test_GetKVMRedirectionState(self):NEWLINE '''GetKVMRedirectionState test method'''NEWLINE self.iface.GetKVMRedirectionState()NEWLINENEWLINE def test_Sprite(self):NEWLINE '''Sprite related test method'''NEWLINE #no PFU on LinuxNEWLINE #self.iface.SetSpriteLanguage(1)NEWLINE #lang = self.iface.GetSpriteLanguage()NEWLINE #self.assertEqual(lang, 1)NEWLINE self.iface.SetSpriteZoom(2)NEWLINE lang, zoom = self.iface.GetSpriteParameters()NEWLINE #self.assertEqual(lang, 1)NEWLINE self.assertEqual(zoom, 2)NEWLINENEWLINE def test_GetConfigurationInfo(self):NEWLINE '''GetConfigurationInfo test method'''NEWLINE self.iface.GetConfigurationInfo()NEWLINENEWLINE def test_TerminateRemedySessions(self):NEWLINE '''TerminateRemedySessions test method'''NEWLINE self.iface.TerminateRemedySessions()NEWLINENEWLINE def test_GetUserConsentState(self):NEWLINE '''GetUserConsentState test method'''NEWLINE self.iface.GetUserConsentState()NEWLINENEWLINE @unittest.skip("Requires wireless card")NEWLINE def test_GetWLANLinkInfo(self):NEWLINE '''GetWLANLinkInfo test method'''NEWLINE self.iface.GetWLANLinkInfo()NEWLINENEWLINE def test_SetLinkPreferenceToHost(self):NEWLINE '''SetLinkPreferenceToHost test method'''NEWLINE self.iface.SetLinkPreferenceToHost()NEWLINENEWLINE def test_userInitiatedPolicyRuleExists(self):NEWLINE '''userInitiatedPolicyRuleExists test method'''NEWLINE self.iface.userInitiatedPolicyRuleExists()NEWLINENEWLINE def test_userInitiatedPolicyRuleForLocalMpsExists(self):NEWLINE '''userInitiatedPolicyRuleForLocalMpsExists test method'''NEWLINE self.iface.userInitiatedPolicyRuleForLocalMpsExists()NEWLINENEWLINE def test_snmpEventSubscriberExists(self):NEWLINE '''snmpEventSubscriberExists test method'''NEWLINE self.iface.snmpEventSubscriberExists()NEWLINENEWLINE def test_CILAFilterCollectionSubscriptionExists(self):NEWLINE '''CILAFilterCollectionSubscriptionExists test method'''NEWLINE self.iface.CILAFilterCollectionSubscriptionExists()NEWLINENEWLINE @unittest.skip("Requires provisioned FW")NEWLINE def test_UpdateScreenSettings2(self):NEWLINE '''UpdateScreenSettings2 test method'''NEWLINE self.iface.UpdateScreenSettings2([(True, 1, 2, 3, 4, 5), (False, 98, 99, 100, 44, 55)], 2)NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.UpdateScreenSettings2([(True, 1, 2, 3, 4, 5)], 2)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.UpdateScreenSettings2([(True, 1, 2, 3, 4, 5), (False, 98, 99, 100, 44, 55)], 1)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINENEWLINE @unittest.skip("Requires specially configured FW")NEWLINE def test_GetRedirectionSessionLinkTechnology_SOL(self):NEWLINE '''GetRedirectionSessionLinkTechnology SOL test method'''NEWLINE self.iface.GetRedirectionSessionLinkTechnology(0)NEWLINENEWLINE @unittest.skip("Requires specially configured FW")NEWLINE def test_GetRedirectionSessionLinkTechnology_IDER(self):NEWLINE '''GetRedirectionSessionLinkTechnology IDER test method'''NEWLINE self.iface.GetRedirectionSessionLinkTechnology(1)NEWLINENEWLINE @unittest.skip("Requires specially configured FW")NEWLINE def test_GetRedirectionSessionLinkTechnology_KVM(self):NEWLINE '''GetRedirectionSessionLinkTechnology KVM test method'''NEWLINE self.iface.GetRedirectionSessionLinkTechnology(2)NEWLINENEWLINE def test_GetRedirectionSessionLinkTechnology_Argument(self):NEWLINE '''GetRedirectionSessionLinkTechnology out of range argument test method'''NEWLINE with self.assertRaises(dbus.exceptions.DBusException) as the_exp:NEWLINE self.iface.GetRedirectionSessionLinkTechnology(3)NEWLINE self.assertEqual(the_exp.exception.get_dbus_message(), 'Invalid argument')NEWLINENEWLINEclass AT_DeviceTestCase(unittest.TestCase):NEWLINE """AT_Device interface test"""NEWLINENEWLINE def setUp(self):NEWLINE bus = dbus.SystemBus()NEWLINE proxy = bus.get_object(DBUS_DEST, DBUS_OBJ)NEWLINE self.iface = dbus.Interface(proxy,NEWLINE dbus_interface=DBUS_IFACE + 'AT_Device')NEWLINENEWLINE def tearDown(self):NEWLINE passNEWLINENEWLINE def test_GetAuditLogs(self):NEWLINE '''GetAuditLogs test method'''NEWLINE self.iface.GetAuditLogs()NEWLINENEWLINEclass UNSAlertTestCase(unittest.TestCase):NEWLINE """UNSAlert interface test"""NEWLINENEWLINE def setUp(self):NEWLINE bus = dbus.SystemBus()NEWLINE proxy = bus.get_object(DBUS_DEST, DBUS_OBJ)NEWLINE self.iface = dbus.Interface(proxy,NEWLINE dbus_interface=DBUS_IFACE + 'UNSAlert')NEWLINENEWLINE def tearDown(self):NEWLINE passNEWLINENEWLINE def test_GetIMSSEventHistory(self):NEWLINE '''GetIMSSEventHistory test method'''NEWLINE self.iface.GetIMSSEventHistory()NEWLINENEWLINEif __name__ == '__main__':NEWLINE unittest.main()NEWLINE
"""Tests for TypeVar."""NEWLINENEWLINEfrom pytype import file_utilsNEWLINEfrom pytype.tests import test_baseNEWLINENEWLINENEWLINEclass TypeVarTest(test_base.TargetPython3BasicTest):NEWLINE """Tests for TypeVar."""NEWLINENEWLINE def test_id(self):NEWLINE ty = self.Infer("""NEWLINE import typingNEWLINE T = typing.TypeVar("T")NEWLINE def f(x: T) -> T:NEWLINE return __any_object__NEWLINE v = f(42)NEWLINE w = f("")NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import AnyNEWLINE typing = ... # type: moduleNEWLINE T = TypeVar("T")NEWLINE def f(x: T) -> T: ...NEWLINE v = ... # type: intNEWLINE w = ... # type: strNEWLINE """)NEWLINE self.assertTrue(ty.Lookup("f").signatures[0].template)NEWLINENEWLINE def test_extract_item(self):NEWLINE ty = self.Infer("""NEWLINE from typing import List, TypeVarNEWLINE S = TypeVar("S") # unusedNEWLINE T = TypeVar("T")NEWLINE def f(x: List[T]) -> T:NEWLINE return __any_object__NEWLINE v = f(["hello world"])NEWLINE w = f([True])NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE S = TypeVar("S")NEWLINE T = TypeVar("T")NEWLINE def f(x: typing.List[T]) -> T: ...NEWLINE v = ... # type: strNEWLINE w = ... # type: boolNEWLINE """)NEWLINE self.assertTrue(ty.Lookup("f").signatures[0].template)NEWLINENEWLINE def test_wrap_item(self):NEWLINE ty = self.Infer("""NEWLINE from typing import List, TypeVarNEWLINE T = TypeVar("T")NEWLINE def f(x: T) -> List[T]:NEWLINE return __any_object__NEWLINE v = f(True)NEWLINE w = f(3.14)NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE T = TypeVar("T")NEWLINE def f(x: T) -> typing.List[T]: ...NEWLINE v = ... # type: typing.List[bool]NEWLINE w = ... # type: typing.List[float]NEWLINE """)NEWLINENEWLINE def test_import_typevar_name_change(self):NEWLINE with file_utils.Tempdir() as d:NEWLINE d.create_file("a.pyi", """NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T")NEWLINE X = TypeVar("X")NEWLINE """)NEWLINE _, errors = self.InferWithErrors("""NEWLINE # This is illegal: A TypeVar("T") needs to be stored under the name "T".NEWLINE from a import T as T2 # invalid-typevar[e1]NEWLINE from a import XNEWLINE Y = X # invalid-typevar[e2]NEWLINE def f(x: T2) -> T2: ...NEWLINE """, pythonpath=[d.path])NEWLINE self.assertErrorRegexes(errors, {"e1": r"T.*T2", "e2": r"X.*Y"})NEWLINENEWLINE def test_multiple_substitution(self):NEWLINE ty = self.Infer("""NEWLINE from typing import Dict, Tuple, TypeVarNEWLINE K = TypeVar("K")NEWLINE V = TypeVar("V")NEWLINE def f(x: Dict[K, V]) -> Tuple[V, K]:NEWLINE return __any_object__NEWLINE v = f({})NEWLINE w = f({"test": 42})NEWLINE """, deep=False)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import Any, Dict, Tuple, TypeVarNEWLINE K = TypeVar("K")NEWLINE V = TypeVar("V")NEWLINE def f(x: Dict[K, V]) -> Tuple[V, K]: ...NEWLINE v = ... # type: Tuple[Any, Any]NEWLINE w = ... # type: Tuple[int, str]NEWLINE """)NEWLINENEWLINE def test_union(self):NEWLINE ty = self.Infer("""NEWLINE from typing import TypeVar, UnionNEWLINE S = TypeVar("S")NEWLINE T = TypeVar("T")NEWLINE def f(x: S, y: T) -> Union[S, T]:NEWLINE return __any_object__NEWLINE v = f("", 42)NEWLINE w = f(3.14, False)NEWLINE """, deep=False)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import TypeVar, UnionNEWLINE S = TypeVar("S")NEWLINE T = TypeVar("T")NEWLINE def f(x: S, y: T) -> Union[S, T]: ...NEWLINE v = ... # type: Union[str, int]NEWLINE w = ... # type: Union[float, bool]NEWLINE """)NEWLINENEWLINE def test_bad_substitution(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import List, TypeVarNEWLINE S = TypeVar("S")NEWLINE T = TypeVar("T")NEWLINE def f1(x: S) -> List[S]:NEWLINE return {x} # bad-return-type[e1]NEWLINE def f2(x: S) -> S:NEWLINE return 42 # no error because never calledNEWLINE def f3(x: S) -> S:NEWLINE return 42 # bad-return-type[e2] # bad-return-type[e3]NEWLINE def f4(x: S, y: T, z: T) -> List[S]:NEWLINE return [y] # bad-return-type[e4]NEWLINE f3("")NEWLINE f3(16) # okNEWLINE f3(False)NEWLINE f4(True, 3.14, 0)NEWLINE f4("hello", "world", "domination") # okNEWLINE """)NEWLINE self.assertErrorRegexes(errors, {NEWLINE "e1": r"List\[S\].*set", "e2": r"str.*int", "e3": r"bool.*int",NEWLINE "e4": r"List\[bool\].*List\[Union\[float, int\]\]"})NEWLINENEWLINE def test_use_constraints(self):NEWLINE ty, errors = self.InferWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE def f(x: T) -> T:NEWLINE return __any_object__NEWLINE v = f("") # wrong-arg-types[e]NEWLINE w = f(True) # okNEWLINE u = f(__any_object__) # okNEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import Any, TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE def f(x: T) -> T: ...NEWLINE v = ... # type: AnyNEWLINE w = ... # type: boolNEWLINE u = ... # type: int or floatNEWLINE """)NEWLINE self.assertErrorRegexes(errors, {"e": r"Union\[float, int\].*str"})NEWLINENEWLINE def test_type_parameter_type(self):NEWLINE ty = self.Infer("""NEWLINE from typing import Type, TypeVarNEWLINE T = TypeVar("T")NEWLINE def f(x: Type[T]) -> T:NEWLINE return __any_object__NEWLINE v = f(int)NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import Type, TypeVarNEWLINE T = TypeVar("T")NEWLINE def f(x: Type[T]) -> T: ...NEWLINE v = ... # type: intNEWLINE """)NEWLINENEWLINE def test_type_parameter_type_error(self):NEWLINE errors = self.CheckWithErrors("""NEWLINE from typing import Sequence, Type, TypeVarNEWLINE T = TypeVar('T')NEWLINE def f(x: int):NEWLINE passNEWLINE def g(x: Type[Sequence[T]]) -> T:NEWLINE print(f(x)) # wrong-arg-types[e]NEWLINE return x()[0]NEWLINE """)NEWLINE self.assertErrorRegexes(NEWLINE errors, {"e": r"Expected.*int.*Actual.*Type\[Sequence\]"})NEWLINENEWLINE def test_print_nested_type_parameter(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import List, TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE def f(x: List[T]): ...NEWLINE f([""]) # wrong-arg-types[e]NEWLINE """)NEWLINE self.assertErrorRegexes(errors, {NEWLINE "e": r"List\[Union\[float, int\]\].*List\[str\]"})NEWLINENEWLINE def test_constraint_subtyping(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE def f(x: T, y: T): ...NEWLINE f(True, False) # okNEWLINE f(True, 42) # wrong-arg-types[e]NEWLINE """)NEWLINE self.assertErrorRegexes(errors, {"e": r"Expected.*y: bool.*Actual.*y: int"})NEWLINENEWLINE def test_filter_value(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T", str, float)NEWLINE def f(x: T, y: T): ...NEWLINE x = ''NEWLINE x = 42.0NEWLINE f(x, '') # wrong-arg-types[e]NEWLINE f(x, 42.0) # okNEWLINE """)NEWLINE self.assertErrorRegexes(NEWLINE errors, {"e": r"Expected.*y: float.*Actual.*y: str"})NEWLINENEWLINE def test_filter_class(self):NEWLINE self.Check("""NEWLINE from typing import TypeVarNEWLINE class A(object): passNEWLINE class B(object): passNEWLINE T = TypeVar("T", A, B)NEWLINE def f(x: T, y: T): ...NEWLINE x = A()NEWLINE x.__class__ = BNEWLINE # Setting __class__ makes the type ambiguous to pytype.NEWLINE f(x, A())NEWLINE f(x, B())NEWLINE """)NEWLINENEWLINE def test_split(self):NEWLINE ty = self.Infer("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T", int, type(None))NEWLINE def f(x: T) -> T:NEWLINE return __any_object__NEWLINE if __random__:NEWLINE x = NoneNEWLINE else:NEWLINE x = 3NEWLINE v = id(x) if x else 42NEWLINE """, deep=False)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE import typesNEWLINE from typing import Optional, TypeVarNEWLINE v = ... # type: intNEWLINE x = ... # type: Optional[int]NEWLINE T = TypeVar("T", int, None)NEWLINE def f(x: T) -> T: ...NEWLINE """)NEWLINENEWLINE def test_enforce_non_constrained_typevar(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T")NEWLINE def f(x: T, y: T): ...NEWLINE f(42, True) # okNEWLINE f(42, "") # wrong-arg-types[e1]NEWLINE f(42, 16j) # okNEWLINE f(object(), 42) # okNEWLINE f(42, object()) # okNEWLINE f(42.0, "") # wrong-arg-types[e2]NEWLINE """)NEWLINE self.assertErrorRegexes(errors, {NEWLINE "e1": r"Expected.*y: int.*Actual.*y: str",NEWLINE "e2": r"Expected.*y: float.*Actual.*y: str"})NEWLINENEWLINE def test_useless_typevar(self):NEWLINE self.InferWithErrors("""NEWLINE from typing import Tuple, TypeVarNEWLINE T = TypeVar("T")NEWLINE S = TypeVar("S", int, float)NEWLINE def f1(x: T): ... # invalid-annotationNEWLINE def f2() -> T: ... # invalid-annotationNEWLINE def f3(x: Tuple[T]): ... # invalid-annotationNEWLINE def f4(x: Tuple[T, T]): ... # okNEWLINE def f5(x: S): ... # okNEWLINE def f6(x: "U"): ... # invalid-annotationNEWLINE def f7(x: T, y: "T"): ... # okNEWLINE def f8(x: "U") -> "U": ... # okNEWLINE U = TypeVar("U")NEWLINE """)NEWLINENEWLINE def test_use_bound(self):NEWLINE ty, errors = self.InferWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar("T", bound=float)NEWLINE def f(x: T) -> T:NEWLINE return xNEWLINE v1 = f(__any_object__) # okNEWLINE v2 = f(True) # okNEWLINE v3 = f(42) # okNEWLINE v4 = f(3.14) # okNEWLINE v5 = f("") # wrong-arg-types[e]NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import Any, TypeVarNEWLINE T = TypeVar("T", bound=float)NEWLINE def f(x: T) -> TNEWLINE v1 = ... # type: floatNEWLINE v2 = ... # type: boolNEWLINE v3 = ... # type: intNEWLINE v4 = ... # type: floatNEWLINE v5 = ... # type: AnyNEWLINE """)NEWLINE self.assertErrorRegexes(errors, {"e": r"x: float.*x: str"})NEWLINENEWLINE def test_bad_return(self):NEWLINE self.assertNoCrash(self.Check, """NEWLINE from typing import AnyStr, DictNEWLINENEWLINE class Foo(object):NEWLINE def f(self) -> AnyStr: return __any_object__NEWLINE def g(self) -> Dict[AnyStr, Dict[AnyStr, AnyStr]]:NEWLINE return {'foo': {'bar': self.f()}}NEWLINE """)NEWLINENEWLINE def test_optional_typevar(self):NEWLINE _, errors = self.InferWithErrors("""NEWLINE from typing import Optional, TypeVarNEWLINE T = TypeVar("T", bound=str)NEWLINE def f() -> Optional[T]:NEWLINE return 42 if __random__ else None # bad-return-type[e]NEWLINE """, deep=True)NEWLINE self.assertErrorRegexes(errors, {"e": r"Optional\[T\].*int"})NEWLINENEWLINE def test_unicode_literals(self):NEWLINE ty = self.Infer("""NEWLINE from __future__ import unicode_literalsNEWLINE import typingNEWLINE T = typing.TypeVar("T")NEWLINE def f(x: T) -> T:NEWLINE return __any_object__NEWLINE v = f(42)NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE import __future__NEWLINE from typing import AnyNEWLINE typing = ... # type: moduleNEWLINE unicode_literals = ... # type: __future__._FeatureNEWLINE T = TypeVar("T")NEWLINE def f(x: T) -> T: ...NEWLINE v = ... # type: intNEWLINE """)NEWLINENEWLINE def test_any_as_bound(self):NEWLINE self.Check("""NEWLINE from typing import Any, TypeVarNEWLINE T = TypeVar("T", bound=Any)NEWLINE def f(x: T) -> T:NEWLINE return xNEWLINE f(42)NEWLINE """)NEWLINENEWLINE def test_any_as_constraint(self):NEWLINE self.Check("""NEWLINE from typing import Any, TypeVarNEWLINE T = TypeVar("T", str, Any)NEWLINE def f(x: T) -> T:NEWLINE return xNEWLINE f(42)NEWLINE """)NEWLINENEWLINE def test_name_reuse(self):NEWLINE self.Check("""NEWLINE from typing import Generic, TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE class Foo(Generic[T]):NEWLINE def __init__(self, x: T):NEWLINE self.x = xNEWLINE def f(foo: Foo[T]) -> T:NEWLINE return foo.xNEWLINE """)NEWLINENEWLINE def test_property_type_param(self):NEWLINE # We should allow property signatures of the form f(self) -> X[T] withoutNEWLINE # needing to annotate 'self' if the class is generic and we use its typeNEWLINE # parameter in the property's signature.NEWLINE ty = self.Infer("""NEWLINE from typing import TypeVar, GenericNEWLINE T = TypeVar('T')NEWLINE class A(Generic[T]):NEWLINE def __init__(self, foo: T):NEWLINE self._foo = fooNEWLINE @propertyNEWLINE def foo(self) -> T:NEWLINE return self._fooNEWLINE @foo.setterNEWLINE def foo(self, foo: T) -> None:NEWLINE self._foo = fooNEWLINE """)NEWLINE # types inferred as Any due to b/123835298NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import TypeVar, Generic, AnyNEWLINE T = TypeVar('T')NEWLINE class A(Generic[T]):NEWLINE _foo: AnyNEWLINE foo: AnyNEWLINE def __init__(self, foo: T) -> NoneNEWLINE """)NEWLINENEWLINE def test_return_typevar(self):NEWLINE errors = self.CheckWithErrors("""NEWLINE from typing import TypeVarNEWLINE T = TypeVar('T')NEWLINE def f(x: T) -> T:NEWLINE return T # bad-return-type[e]NEWLINE """)NEWLINE self.assertErrorRegexes(errors, {"e": "Expected.*T.*Actual.*TypeVar"})NEWLINENEWLINE def test_typevar_in_union_alias(self):NEWLINE ty = self.Infer("""NEWLINE from typing import Dict, List, TypeVar, UnionNEWLINE T = TypeVar("T")NEWLINE U = TypeVar("U")NEWLINE Foo = Union[T, List[T], Dict[T, List[U]], complex]NEWLINE def f(x: Foo[int, str]): ...NEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import Dict, List, TypeVar, Union, AnyNEWLINE T = TypeVar("T")NEWLINE U = TypeVar("U")NEWLINE Foo: AnyNEWLINE def f(x: Union[Dict[int, List[str]], List[int], complex, int]) -> None: ...NEWLINE """)NEWLINENEWLINE def test_typevar_in_union_alias_error(self):NEWLINE err = self.CheckWithErrors("""NEWLINE from typing import Dict, List, TypeVar, UnionNEWLINE T = TypeVar("T")NEWLINE U = TypeVar("U")NEWLINE Foo = Union[T, List[T], Dict[T, List[U]], complex]NEWLINE def f(x: Foo[int]): ... # invalid-annotation[e]NEWLINE """)NEWLINE self.assertErrorRegexes(err, {"e": "Union.*2.*instantiated.*1"})NEWLINENEWLINE def test_use_unsupported_typevar(self):NEWLINE # Test that we don't crash when using this pattern (b/162274390)NEWLINE self.CheckWithErrors("""NEWLINE from typing import List, TypeVar, UnionNEWLINE T = TypeVar("T")NEWLINE Tree = Union[T, List['Tree']] # not-supported-yetNEWLINE def f(x: Tree[int]): ... # no error since Tree is set to AnyNEWLINE """)NEWLINENEWLINENEWLINEclass TypeVarTestPy3(test_base.TargetPython3FeatureTest):NEWLINE """Tests for TypeVar in Python 3."""NEWLINENEWLINE def test_use_constraints_from_pyi(self):NEWLINE with file_utils.Tempdir() as d:NEWLINE d.create_file("foo.pyi", """NEWLINE from typing import AnyStr, TypeVarNEWLINE T = TypeVar("T", int, float)NEWLINE def f(x: T) -> T: ...NEWLINE def g(x: AnyStr) -> AnyStr: ...NEWLINE """)NEWLINE _, errors = self.InferWithErrors("""NEWLINE import fooNEWLINE foo.f("") # wrong-arg-types[e1]NEWLINE foo.g(0) # wrong-arg-types[e2]NEWLINE """, pythonpath=[d.path])NEWLINE self.assertErrorRegexes(errors, {NEWLINE "e1": r"Union\[float, int\].*str",NEWLINE "e2": r"Union\[bytes, str\].*int"})NEWLINENEWLINE def test_subprocess(self):NEWLINE ty = self.Infer("""NEWLINE import subprocessNEWLINE from typing import ListNEWLINE def run(args: List[str]):NEWLINE result = subprocess.run(NEWLINE args,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=subprocess.PIPE,NEWLINE universal_newlines=True)NEWLINE if result.returncode:NEWLINE raise subprocess.CalledProcessError(NEWLINE result.returncode, args, result.stdout)NEWLINE return result.stdoutNEWLINE """)NEWLINE self.assertTypesMatchPytd(ty, """NEWLINE from typing import ListNEWLINE subprocess: moduleNEWLINE def run(args: List[str]) -> strNEWLINE """)NEWLINENEWLINE def test_abstract_classmethod(self):NEWLINE self.Check("""NEWLINE from abc import ABC, abstractmethodNEWLINE from typing import Type, TypeVarNEWLINENEWLINE T = TypeVar('T', bound='Foo')NEWLINENEWLINE class Foo(ABC):NEWLINE @classmethodNEWLINE @abstractmethodNEWLINE def f(cls: Type[T]) -> T:NEWLINE return cls()NEWLINE """)NEWLINENEWLINENEWLINEtest_base.main(globals(), __name__ == "__main__")NEWLINE
import cv2NEWLINEimport numpy as npNEWLINEimport osNEWLINEimport sysNEWLINEimport tensorflow as tfNEWLINENEWLINEfrom sklearn.model_selection import train_test_splitNEWLINENEWLINEEPOCHS = 10NEWLINEIMG_WIDTH = 30NEWLINEIMG_HEIGHT = 30NEWLINENUM_CATEGORIES = 43NEWLINETEST_SIZE = 0.4NEWLINENEWLINENEWLINEdef main():NEWLINENEWLINE # Check command-line argumentsNEWLINE if len(sys.argv) not in [2, 3]:NEWLINE sys.exit("Usage: python traffic.py data_directory [model.h5]")NEWLINENEWLINE # Get image arrays and labels for all image filesNEWLINE images, labels = load_data(sys.argv[1])NEWLINENEWLINE # Split data into training and testing setsNEWLINE labels = tf.keras.utils.to_categorical(labels)NEWLINE x_train, x_test, y_train, y_test = train_test_split(NEWLINE np.array(images), np.array(labels), test_size=TEST_SIZENEWLINE )NEWLINENEWLINE # Get a compiled neural networkNEWLINE model = get_model()NEWLINENEWLINE # Fit model on training dataNEWLINE model.fit(x_train, y_train, epochs=EPOCHS)NEWLINENEWLINE # Evaluate neural network performanceNEWLINE model.evaluate(x_test, y_test, verbose=2)NEWLINENEWLINE # Save model to fileNEWLINE if len(sys.argv) == 3:NEWLINE filename = sys.argv[2]NEWLINE model.save(filename)NEWLINE print(f"Model saved to {filename}.")NEWLINENEWLINENEWLINEdef load_data(data_dir):NEWLINE """NEWLINE Load image data from directory `data_dir`.NEWLINENEWLINE Assume `data_dir` has one directory named after each category, numberedNEWLINE 0 through NUM_CATEGORIES - 1. Inside each category directory will be someNEWLINE number of image files.NEWLINENEWLINE Return tuple `(images, labels)`. `images` should be a list of allNEWLINE of the images in the data directory, where each image is formatted as aNEWLINE numpy ndarray with dimensions IMG_WIDTH x IMG_HEIGHT x 3. `labels` shouldNEWLINE be a list of integer labels, representing the categories for each of theNEWLINE corresponding `images`.NEWLINE """NEWLINE images = []NEWLINE labels = []NEWLINE for x in range(NUM_CATEGORIES):NEWLINE for filename in os.listdir(os.path.join(data_dir, str(x))):NEWLINE NEWLINE img = cv2.imread(os.path.join(data_dir, str(x), filename))NEWLINE resize = cv2.resize(img, (IMG_WIDTH, IMG_HEIGHT))NEWLINE NEWLINE images.append(resize)NEWLINE labels.append(x)NEWLINENEWLINE return (images, labels)NEWLINE NEWLINEdef get_model():NEWLINE """NEWLINE Returns a compiled convolutional neural network model. Assume that theNEWLINE `input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.NEWLINE The output layer should have `NUM_CATEGORIES` units, one for each category.NEWLINE """NEWLINE NEWLINE model = tf.keras.models.Sequential([NEWLINENEWLINE tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 3)),NEWLINENEWLINE tf.keras.layers.MaxPooling2D(pool_size=(2,2)),NEWLINE NEWLINE tf.keras.layers.Flatten(),NEWLINENEWLINE tf.keras.layers.Dense(128, activation='relu'),NEWLINE tf.keras.layers.Dense(128, activation='relu'),NEWLINE tf.keras.layers.Dense(128, activation='relu'),NEWLINE tf.keras.layers.Dense(128, activation='relu'),NEWLINENEWLINE tf.keras.layers.Dropout(0.2),NEWLINE NEWLINE tf.keras.layers.Dense(NUM_CATEGORIES, activation='softmax')NEWLINE ])NEWLINENEWLINENEWLINE model.compile(NEWLINE optimizer='rmsprop',NEWLINE loss='sparse_categorical_crossentropy',NEWLINE metrics=['accuracy']NEWLINE )NEWLINENEWLINE return (model)NEWLINENEWLINEif __name__ == "__main__":NEWLINE main()NEWLINE
from .companies import CompanyView, CompaniesViewNEWLINEfrom .employees import (NEWLINE EmployeeView, EmployeesView, EmployeeProductsView,NEWLINE EmployeeProductDeleteViewNEWLINE)NEWLINEfrom .products import ProductView, ProductsViewNEWLINENEWLINENEWLINEHANDLERS = (NEWLINE CompanyView, CompaniesView,NEWLINE EmployeeView, EmployeesView, EmployeeProductsView,NEWLINE EmployeeProductDeleteView,NEWLINE ProductView, ProductsViewNEWLINE)NEWLINE
# -*- coding: utf8 -*-NEWLINE"""NEWLINE.. module:: lesscpy.plib.negated_expressionNEWLINE :synopsis: Node for unary negated expressions.NEWLINENEWLINE Copyright (c)NEWLINE See LICENSE for details.NEWLINE"""NEWLINENEWLINEfrom six import string_typesNEWLINENEWLINEfrom .node import NodeNEWLINENEWLINENEWLINEclass NegatedExpression(Node):NEWLINENEWLINE """Expressions preceded by unary negation."""NEWLINENEWLINE def parse(self, scope):NEWLINE val, = self.process(self.tokens, scope)NEWLINE if isinstance(val, string_types):NEWLINE return '-' + valNEWLINE return -valNEWLINE
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.comNEWLINE#NEWLINE# Part of "Nuitka", an optimizing Python compiler that is compatible andNEWLINE# integrates with CPython, but also works on its own.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINE""" Spawning processes.NEWLINENEWLINEThis is to replace the standard spawn implementation with one that tracks theNEWLINEprogress, and gives warnings about things taking very long.NEWLINE"""NEWLINENEWLINEimport osNEWLINEimport subprocessNEWLINEimport threadingNEWLINENEWLINEfrom nuitka.Tracing import my_print, scons_loggerNEWLINEfrom nuitka.utils.Timing import TimerReportNEWLINENEWLINEfrom .SconsCaching import extractClcacheLogFromOutputNEWLINEfrom .SconsUtils import decodeDataNEWLINENEWLINENEWLINE# Thread class to run a commandNEWLINEclass SubprocessThread(threading.Thread):NEWLINE def __init__(self, cmdline, env):NEWLINE threading.Thread.__init__(self)NEWLINENEWLINE self.cmdline = cmdlineNEWLINE self.env = envNEWLINENEWLINE self.data = NoneNEWLINE self.err = NoneNEWLINE self.exit_code = NoneNEWLINENEWLINE self.timer_report = TimerReport(NEWLINE message="Running %s took %%.2f seconds"NEWLINE % repr(self.cmdline).replace("%", "%%"),NEWLINE min_report_time=60,NEWLINE logger=scons_logger,NEWLINE )NEWLINENEWLINE def run(self):NEWLINE # execute the command, queue the resultNEWLINE with self.timer_report:NEWLINE proc = subprocess.Popen(NEWLINE self.cmdline,NEWLINE stdin=subprocess.PIPE,NEWLINE stdout=subprocess.PIPE,NEWLINE stderr=subprocess.PIPE,NEWLINE shell=False,NEWLINE env=self.env,NEWLINE )NEWLINENEWLINE self.data, self.err = proc.communicate()NEWLINE self.exit_code = proc.wait()NEWLINENEWLINE def getProcessResult(self):NEWLINE return self.data, self.err, self.exit_codeNEWLINENEWLINENEWLINEdef runProcessMonitored(cmdline, env):NEWLINE thread = SubprocessThread(cmdline, env)NEWLINE thread.start()NEWLINENEWLINE # Allow a minute before warning for long compile time.NEWLINE thread.join(60)NEWLINENEWLINE if thread.is_alive():NEWLINE scons_logger.info(NEWLINE "Slow C compilation detected, used %.0fs so far, this might indicate scalability problems."NEWLINE % thread.timer_report.getTimer().getDelta()NEWLINE )NEWLINENEWLINE thread.join()NEWLINENEWLINE return thread.getProcessResult()NEWLINENEWLINENEWLINE# To work around Windows not supporting command lines of greater than 10K byNEWLINE# default:NEWLINEdef getWindowsSpawnFunction(module_mode, source_files):NEWLINE def spawnWindowsCommand(NEWLINE sh, escape, cmd, args, envNEWLINE ): # pylint: disable=unused-argumentNEWLINENEWLINE # The "del" appears to not work reliably, but is used with large amounts ofNEWLINE # files to link. So, lets do this ourselves, plus it avoids a processNEWLINE # spawn.NEWLINE if cmd == "del":NEWLINE assert len(args) == 2NEWLINENEWLINE os.unlink(args[1])NEWLINE return 0NEWLINENEWLINE # For quoted arguments that end in a backslash, things don't work wellNEWLINE # this is a workaround for it.NEWLINE def removeTrailingSlashQuote(arg):NEWLINE if arg.endswith(r"\""):NEWLINE return arg[:-1] + '\\"'NEWLINE else:NEWLINE return argNEWLINENEWLINE newargs = " ".join(removeTrailingSlashQuote(arg) for arg in args[1:])NEWLINE cmdline = cmd + " " + newargsNEWLINENEWLINE data, err, rv = runProcessMonitored(cmdline, env)NEWLINENEWLINE if cmd == "rc":NEWLINE data = data[data.find(b"reserved.\r") + 13 :]NEWLINENEWLINE data = b"\n".join(NEWLINE lineNEWLINE for line in data.split(b"\n")NEWLINE if b"identifier truncated to" not in lineNEWLINE )NEWLINE elif cmd == "link":NEWLINE if module_mode:NEWLINE data = b"\r\n".join(NEWLINE lineNEWLINE for line in data.split(b"\r\n")NEWLINE if b" Creating library" not in lineNEWLINE # On localized compilers, the message to ignore is not as clear.NEWLINE if not (module_mode and b".exp" in line)NEWLINE )NEWLINE elif cmd == "cl" or os.path.basename(cmd).lower() == "clcache.exe":NEWLINE # Remove clcache debug output if present:NEWLINE data = extractClcacheLogFromOutput(data)NEWLINENEWLINE # Skip forced output from cl.exeNEWLINE data = data[data.find(b"\r\n") + 2 :]NEWLINENEWLINE source_basenames = [NEWLINE os.path.basename(source_file) for source_file in source_filesNEWLINE ]NEWLINENEWLINE def check(line):NEWLINE return line in (b"", b"Generating Code...") or line in source_basenamesNEWLINENEWLINE data = (NEWLINE b"\r\n".join(line for line in data.split(b"\r\n") if not check(line))NEWLINE + b"\r\n"NEWLINE )NEWLINENEWLINE if data.rstrip():NEWLINE if not decodeData:NEWLINE my_print(cmdline, style="yellow")NEWLINENEWLINE if str is not bytes:NEWLINE data = decodeData(data)NEWLINENEWLINE my_print(data, style="yellow", end="")NEWLINENEWLINE if err:NEWLINE if str is not bytes:NEWLINE err = decodeData(err)NEWLINENEWLINE my_print(err, style="yellow", end="")NEWLINENEWLINE return rvNEWLINENEWLINE return spawnWindowsCommandNEWLINENEWLINENEWLINEclass SpawnThread(threading.Thread):NEWLINE def __init__(self, spawn, *args):NEWLINE threading.Thread.__init__(self)NEWLINENEWLINE self.spawn = spawnNEWLINE self.args = argsNEWLINENEWLINE self.timer_report = TimerReport(NEWLINE message="Running %s took %%.2f seconds"NEWLINE % (repr(self.args).replace("%", "%%"),),NEWLINE min_report_time=60,NEWLINE logger=scons_logger,NEWLINE )NEWLINENEWLINE self.result = NoneNEWLINENEWLINE def run(self):NEWLINE # execute the command, queue the resultNEWLINE with self.timer_report:NEWLINE self.result = self.spawn(*self.args)NEWLINENEWLINE def getSpawnResult(self):NEWLINE return self.resultNEWLINENEWLINENEWLINEdef runSpawnMonitored(spawn, sh, escape, cmd, args, env):NEWLINE thread = SpawnThread(spawn, sh, escape, cmd, args, env)NEWLINE thread.start()NEWLINENEWLINE # Allow a minute before warning for long compile time.NEWLINE thread.join(60)NEWLINENEWLINE if thread.is_alive():NEWLINE scons_logger.info(NEWLINE "Slow C compilation detected, used %.0fs so far, this might indicate scalability problems."NEWLINE % thread.timer_report.getTimer().getDelta()NEWLINE )NEWLINENEWLINE thread.join()NEWLINENEWLINE return thread.getSpawnResult()NEWLINENEWLINENEWLINEdef getWrappedSpawnFunction(spawn):NEWLINE def spawnCommand(sh, escape, cmd, args, env):NEWLINE return runSpawnMonitored(spawn, sh, escape, cmd, args, env)NEWLINENEWLINE return spawnCommandNEWLINE
from __future__ import print_functionNEWLINEimport hashlibNEWLINEimport importlibNEWLINEimport jsonNEWLINEimport loggingNEWLINEimport osNEWLINEimport sysNEWLINEfrom itertools import chainNEWLINEfrom warnings import warn as _warnNEWLINEfrom hashlib import sha1NEWLINEfrom os.path import isfileNEWLINEfrom os.path import joinNEWLINEfrom re import compile as regex_compileNEWLINENEWLINEimport requestsNEWLINENEWLINEimport sixNEWLINENEWLINEfrom saml2 import mdNEWLINEfrom saml2 import samlNEWLINEfrom saml2 import samlpNEWLINEfrom saml2 import xmldsigNEWLINEfrom saml2 import xmlencNEWLINEfrom saml2 import SAMLErrorNEWLINEfrom saml2 import BINDING_HTTP_REDIRECTNEWLINEfrom saml2 import BINDING_HTTP_POSTNEWLINEfrom saml2 import BINDING_SOAPNEWLINEfrom saml2.httpbase import HTTPBaseNEWLINEfrom saml2.extension.idpdisc import BINDING_DISCONEWLINEfrom saml2.extension.idpdisc import DiscoveryResponseNEWLINEfrom saml2.md import NAMESPACE as NS_MDNEWLINEfrom saml2.md import EntitiesDescriptorNEWLINEfrom saml2.md import ArtifactResolutionServiceNEWLINEfrom saml2.md import NameIDMappingServiceNEWLINEfrom saml2.md import SingleSignOnServiceNEWLINEfrom saml2.mdie import to_dictNEWLINEfrom saml2.s_utils import UnsupportedBindingNEWLINEfrom saml2.s_utils import UnknownSystemEntityNEWLINEfrom saml2.sigver import split_lenNEWLINEfrom saml2.validate import valid_instanceNEWLINEfrom saml2.time_util import validNEWLINEfrom saml2.time_util import instantNEWLINEfrom saml2.time_util import add_durationNEWLINEfrom saml2.time_util import beforeNEWLINEfrom saml2.time_util import str_to_timeNEWLINEfrom saml2.validate import NotValidNEWLINEfrom saml2.sigver import security_contextNEWLINEfrom saml2.extension.mdattr import NAMESPACE as NS_MDATTRNEWLINEfrom saml2.extension.mdattr import EntityAttributesNEWLINEfrom saml2.extension.algsupport import NAMESPACE as NS_ALGSUPPORTNEWLINEfrom saml2.extension.algsupport import SigningMethod, DigestMethodNEWLINEfrom saml2.extension.mdui import NAMESPACE as NS_MDUINEWLINEfrom saml2.extension.mdui import UIInfoNEWLINEfrom saml2.extension.mdui import DisplayNameNEWLINEfrom saml2.extension.mdui import DescriptionNEWLINEfrom saml2.extension.mdui import InformationURLNEWLINEfrom saml2.extension.mdui import PrivacyStatementURLNEWLINEfrom saml2.extension.mdui import LogoNEWLINEfrom saml2.extension.mdrpi import NAMESPACE as NS_MDRPINEWLINEfrom saml2.extension.mdrpi import RegistrationInfoNEWLINEfrom saml2.extension.mdrpi import RegistrationPolicyNEWLINEfrom saml2.extension.shibmd import NAMESPACE as NS_SHIBMDNEWLINEfrom saml2.extension.shibmd import ScopeNEWLINENEWLINENEWLINElogger = logging.getLogger(__name__)NEWLINENEWLINEclassnames = {NEWLINE "mdattr_entityattributes": "{ns}&{tag}".format(NEWLINE ns=NS_MDATTR, tag=EntityAttributes.c_tagNEWLINE ),NEWLINE "algsupport_signing_method": "{ns}&{tag}".format(ns=NS_ALGSUPPORT, tag=SigningMethod.c_tag),NEWLINE "algsupport_digest_method": "{ns}&{tag}".format(ns=NS_ALGSUPPORT, tag=DigestMethod.c_tag),NEWLINE "mdui_uiinfo": "{ns}&{tag}".format(ns=NS_MDUI, tag=UIInfo.c_tag),NEWLINE "mdui_uiinfo_display_name": "{ns}&{tag}".format(ns=NS_MDUI, tag=DisplayName.c_tag),NEWLINE "mdui_uiinfo_description": "{ns}&{tag}".format(ns=NS_MDUI, tag=Description.c_tag),NEWLINE "mdui_uiinfo_information_url": "{ns}&{tag}".format(NEWLINE ns=NS_MDUI, tag=InformationURL.c_tagNEWLINE ),NEWLINE "mdui_uiinfo_privacy_statement_url": "{ns}&{tag}".format(NEWLINE ns=NS_MDUI, tag=PrivacyStatementURL.c_tagNEWLINE ),NEWLINE "mdui_uiinfo_logo": "{ns}&{tag}".format(ns=NS_MDUI, tag=Logo.c_tag),NEWLINE "service_artifact_resolution": "{ns}&{tag}".format(ns=NS_MD, tag=ArtifactResolutionService.c_tag),NEWLINE "service_single_sign_on": "{ns}&{tag}".format(ns=NS_MD, tag=SingleSignOnService.c_tag),NEWLINE "service_nameid_mapping": "{ns}&{tag}".format(ns=NS_MD, tag=NameIDMappingService.c_tag),NEWLINE "mdrpi_registration_info": "{ns}&{tag}".format(ns=NS_MDRPI, tag=RegistrationInfo.c_tag),NEWLINE "mdrpi_registration_policy": "{ns}&{tag}".format(ns=NS_MDRPI, tag=RegistrationPolicy.c_tag),NEWLINE "shibmd_scope": "{ns}&{tag}".format(ns=NS_SHIBMD, tag=Scope.c_tag)NEWLINE}NEWLINENEWLINEENTITY_CATEGORY = "http://macedir.org/entity-category"NEWLINEENTITY_CATEGORY_SUPPORT = "http://macedir.org/entity-category-support"NEWLINEASSURANCE_CERTIFICATION = "urn:oasis:names:tc:SAML:attribute:assurance-certification"NEWLINENEWLINESAML_METADATA_CONTENT_TYPE = "application/samlmetadata+xml"NEWLINEDEFAULT_FRESHNESS_PERIOD = "P0Y0M0DT12H0M0S"NEWLINENEWLINEREQ2SRV = {NEWLINE # IDPNEWLINE "authn_request": "single_sign_on_service",NEWLINE "name_id_mapping_request": "name_id_mapping_service",NEWLINE # AuthnAuthorityNEWLINE "authn_query": "authn_query_service",NEWLINE # AttributeAuthorityNEWLINE "attribute_query": "attribute_service",NEWLINE # PDPNEWLINE "authz_decision_query": "authz_service",NEWLINE # AuthnAuthority + IDP + PDP + AttributeAuthorityNEWLINE "assertion_id_request": "assertion_id_request_service",NEWLINE # IDP + SPNEWLINE "logout_request": "single_logout_service",NEWLINE "manage_name_id_request": "manage_name_id_service",NEWLINE "artifact_query": "artifact_resolution_service",NEWLINE # SPNEWLINE "assertion_response": "assertion_consumer_service",NEWLINE "attribute_response": "attribute_consuming_service",NEWLINE "discovery_service_request": "discovery_response"NEWLINE}NEWLINENEWLINENEWLINEclass ToOld(Exception):NEWLINE passNEWLINENEWLINENEWLINEclass TooOld(ToOld):NEWLINE passNEWLINENEWLINENEWLINEclass SourceNotFound(Exception):NEWLINE passNEWLINENEWLINENEWLINEdef load_extensions():NEWLINE from saml2 import extensionNEWLINE import pkgutilNEWLINENEWLINE package = extensionNEWLINE prefix = package.__name__ + "."NEWLINE ext_map = {}NEWLINE for importer, modname, ispkg in pkgutil.iter_modules(package.__path__,NEWLINE prefix):NEWLINE module = __import__(modname, fromlist="dummy")NEWLINE ext_map[module.NAMESPACE] = moduleNEWLINENEWLINE return ext_mapNEWLINENEWLINENEWLINEdef load_metadata_modules():NEWLINE mods = {NEWLINE saml.NAMESPACE: saml,NEWLINE md.NAMESPACE: md,NEWLINE xmldsig.NAMESPACE: xmldsig,NEWLINE xmlenc.NAMESPACE: xmlencNEWLINE }NEWLINENEWLINE mods.update(load_extensions())NEWLINE return modsNEWLINENEWLINENEWLINEdef metadata_modules():NEWLINE _res = [saml, md, xmldsig, xmlenc]NEWLINE _res.extend(list(load_extensions().values()))NEWLINE return _resNEWLINENEWLINENEWLINEdef response_locations(srvs):NEWLINE """NEWLINE Return the ResponseLocation attributes mapped to the services.NEWLINENEWLINE ArtifactResolutionService, SingleSignOnService and NameIDMappingService MUST omitNEWLINE the ResponseLocation attribute. This is enforced here, but metadata with suchNEWLINE service declarations and such attributes should not have been part of the metadataNEWLINE store in the first place.NEWLINE """NEWLINE values = (NEWLINE s["response_location"]NEWLINE for s in srvsNEWLINE if "response_location" in sNEWLINE if s["__class__"] not in [NEWLINE classnames["service_artifact_resolution"],NEWLINE classnames["service_single_sign_on"],NEWLINE classnames["service_nameid_mapping"],NEWLINE ]NEWLINE )NEWLINE return valuesNEWLINENEWLINENEWLINEdef locations(srvs):NEWLINE values = (NEWLINE s["location"]NEWLINE for s in srvsNEWLINE if "location" in sNEWLINE )NEWLINE return valuesNEWLINENEWLINENEWLINEdef destinations(srvs):NEWLINE warn_msg = (NEWLINE "`saml2.mdstore.destinations` function is deprecated; "NEWLINE "instead, use `saml2.mdstore.locations` or `saml2.mdstore.all_locations`."NEWLINE )NEWLINE logger.warning(warn_msg)NEWLINE _warn(warn_msg, DeprecationWarning)NEWLINE values = list(locations(srvs))NEWLINE return valuesNEWLINENEWLINENEWLINEdef all_locations(srvs):NEWLINE values = chain(NEWLINE response_locations(srvs),NEWLINE locations(srvs),NEWLINE )NEWLINE return valuesNEWLINENEWLINENEWLINEdef attribute_requirement(entity, index=None):NEWLINE res = {"required": [], "optional": []}NEWLINE for acs in entity["attribute_consuming_service"]:NEWLINE if index is not None and acs["index"] != index:NEWLINE continueNEWLINENEWLINE for attr in acs["requested_attribute"]:NEWLINE if "is_required" in attr and attr["is_required"] == "true":NEWLINE res["required"].append(attr)NEWLINE else:NEWLINE res["optional"].append(attr)NEWLINE return resNEWLINENEWLINENEWLINEdef name(ent, langpref="en"):NEWLINE try:NEWLINE org = ent["organization"]NEWLINE except KeyError:NEWLINE return NoneNEWLINENEWLINE for info in ["organization_display_name",NEWLINE "organization_name",NEWLINE "organization_url"]:NEWLINE try:NEWLINE for item in org[info]:NEWLINE if item["lang"] == langpref:NEWLINE return item["text"]NEWLINE except KeyError:NEWLINE passNEWLINE return NoneNEWLINENEWLINENEWLINEdef repack_cert(cert):NEWLINE part = cert.split("\n")NEWLINE if len(part) == 1:NEWLINE part = part[0].strip()NEWLINE return "\n".join(split_len(part, 64))NEWLINE else:NEWLINE return "\n".join([s.strip() for s in part])NEWLINENEWLINENEWLINEclass MetaData(object):NEWLINE def __init__(self, attrc, metadata='', node_name=None,NEWLINE check_validity=True, security=None, **kwargs):NEWLINE self.attrc = attrcNEWLINE self.metadata = metadataNEWLINE self.entity = NoneNEWLINE self.cert = NoneNEWLINE self.to_old = []NEWLINE self.node_name = node_nameNEWLINE self.check_validity = check_validityNEWLINE self.security = securityNEWLINENEWLINE def items(self):NEWLINE '''NEWLINE Returns list of items contained in the storageNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def keys(self):NEWLINE '''NEWLINE Returns keys (identifiers) of items in storageNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def values(self):NEWLINE '''NEWLINE Returns values of items in storageNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def __len__(self):NEWLINE '''NEWLINE Returns number of stored itemsNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def __contains__(self, item):NEWLINE '''NEWLINE Returns True if the storage contains itemNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def __getitem__(self, item):NEWLINE '''NEWLINE Returns the item specified by the keyNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def __setitem__(self, key, value):NEWLINE '''NEWLINE Sets a key to a valueNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def __delitem__(self, key):NEWLINE '''NEWLINE Removes key from storageNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def do_entity_descriptor(self, entity_descr):NEWLINE '''NEWLINE #FIXME - Add descriptionNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def parse(self, xmlstr):NEWLINE '''NEWLINE #FIXME - Add descriptionNEWLINE '''NEWLINE raise NotImplementedErrorNEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE '''NEWLINE Loads the metadataNEWLINE '''NEWLINE self.parse(self.metadata)NEWLINENEWLINE def service(self, entity_id, typ, service, binding=None):NEWLINE """ Get me all services with a specifiedNEWLINE entity ID and type, that supports the specified version of binding.NEWLINENEWLINE :param entity_id: The EntityIdNEWLINE :param typ: Type of service (idp, attribute_authority, ...)NEWLINE :param service: which service that is sought forNEWLINE :param binding: A binding identifierNEWLINE :return: list of service descriptions.NEWLINE Or if no binding was specified a list of 2-tuples (binding, srv)NEWLINE """NEWLINE raise NotImplementedErrorNEWLINENEWLINE def ext_service(self, entity_id, typ, service, binding):NEWLINE try:NEWLINE srvs = self[entity_id][typ]NEWLINE except KeyError:NEWLINE return NoneNEWLINENEWLINE if not srvs:NEWLINE return srvsNEWLINENEWLINE res = []NEWLINE for srv in srvs:NEWLINE if "extensions" in srv:NEWLINE for elem in srv["extensions"]["extension_elements"]:NEWLINE if elem["__class__"] == service:NEWLINE if elem["binding"] == binding:NEWLINE res.append(elem)NEWLINENEWLINE return resNEWLINENEWLINE def any(self, typ, service, binding=None):NEWLINE """NEWLINE Return any entity that matches the specificationNEWLINENEWLINE :param typ: Type of entityNEWLINE :param service:NEWLINE :param binding:NEWLINE :return:NEWLINE """NEWLINE res = {}NEWLINE for ent in self.keys():NEWLINE bind = self.service(ent, typ, service, binding)NEWLINE if bind:NEWLINE res[ent] = bindNEWLINENEWLINE return resNEWLINENEWLINE def any2(self, typ, service, binding=None):NEWLINE """NEWLINENEWLINE :param type:NEWLINE :param service:NEWLINE :param binding:NEWLINE :return:NEWLINE """NEWLINE res = {}NEWLINE for entid, item in self.items():NEWLINE hit = FalseNEWLINE try:NEWLINE descr = item['{}sso_descriptor'.format(typ)]NEWLINE except KeyError:NEWLINE continueNEWLINE else:NEWLINE for desc in descr:NEWLINE try:NEWLINE srvs = desc[service]NEWLINE except KeyError:NEWLINE continueNEWLINE else:NEWLINE for srv in srvs:NEWLINE if srv['binding'] == binding:NEWLINE res[entid] = itemNEWLINE hit = TrueNEWLINE breakNEWLINE if hit:NEWLINE breakNEWLINE return resNEWLINENEWLINE def bindings(self, entity_id, typ, service):NEWLINE """NEWLINE Get me all the bindings that are registered for a service entityNEWLINENEWLINE :param entity_id:NEWLINE :param service:NEWLINE :return:NEWLINE """NEWLINE return self.service(entity_id, typ, service)NEWLINENEWLINE def attribute_requirement(self, entity_id, index=None):NEWLINE """ Returns what attributes the SP requires and which are optionalNEWLINE if any such demands are registered in the Metadata.NEWLINENEWLINE :param entity_id: The entity id of the SPNEWLINE :param index: which of the attribute consumer services its all aboutNEWLINE if index=None then return all attributes expected by allNEWLINE attribute_consuming_services.NEWLINE :return: 2-tuple, list of required and list of optional attributesNEWLINE """NEWLINE raise NotImplementedErrorNEWLINENEWLINE def dumps(self):NEWLINE return json.dumps(list(self.items()), indent=2)NEWLINENEWLINE def with_descriptor(self, descriptor):NEWLINE '''NEWLINE Returns any entities with the specified descriptorNEWLINE '''NEWLINE res = {}NEWLINE desc = "%s_descriptor" % descriptorNEWLINE for eid, ent in self.items():NEWLINE if desc in ent:NEWLINE res[eid] = entNEWLINE return resNEWLINENEWLINE def __str__(self):NEWLINE return "%s" % self.items()NEWLINENEWLINE def construct_source_id(self):NEWLINE raise NotImplementedErrorNEWLINENEWLINE def entity_categories(self, entity_id):NEWLINE res = []NEWLINE if "extensions" in self[entity_id]:NEWLINE for elem in self[entity_id]["extensions"]["extension_elements"]:NEWLINE if elem["__class__"] == classnames["mdattr_entityattributes"]:NEWLINE for attr in elem["attribute"]:NEWLINE res.append(attr["text"])NEWLINENEWLINE return resNEWLINENEWLINE def __eq__(self, other):NEWLINE if not isinstance(other, MetaData):NEWLINE return FalseNEWLINENEWLINE if len(self.entity) != len(other.entity):NEWLINE return FalseNEWLINENEWLINE if set(self.entity.keys()) != set(other.entity.keys()):NEWLINE return FalseNEWLINENEWLINE for key, item in self.entity.items():NEWLINE if item != other[key]:NEWLINE return FalseNEWLINENEWLINE return TrueNEWLINENEWLINE def certs(self, entity_id, descriptor, use="signing"):NEWLINE '''NEWLINE Returns certificates for the given EntityNEWLINE '''NEWLINE ent = self[entity_id]NEWLINENEWLINE def extract_certs(srvs):NEWLINE res = []NEWLINE for srv in srvs:NEWLINE if "key_descriptor" in srv:NEWLINE for key in srv["key_descriptor"]:NEWLINE if "use" in key and key["use"] == use:NEWLINE for dat in key["key_info"]["x509_data"]:NEWLINE cert = repack_cert(NEWLINE dat["x509_certificate"]["text"])NEWLINE if cert not in res:NEWLINE res.append(cert)NEWLINE elif not "use" in key:NEWLINE for dat in key["key_info"]["x509_data"]:NEWLINE cert = repack_cert(NEWLINE dat["x509_certificate"]["text"])NEWLINE if cert not in res:NEWLINE res.append(cert)NEWLINENEWLINE return resNEWLINENEWLINE if descriptor == "any":NEWLINE res = []NEWLINE for descr in ["spsso", "idpsso", "role", "authn_authority",NEWLINE "attribute_authority", "pdp"]:NEWLINE try:NEWLINE srvs = ent["%s_descriptor" % descr]NEWLINE except KeyError:NEWLINE continueNEWLINENEWLINE res.extend(extract_certs(srvs))NEWLINE else:NEWLINE srvs = ent["%s_descriptor" % descriptor]NEWLINE res = extract_certs(srvs)NEWLINENEWLINE return resNEWLINENEWLINENEWLINEclass InMemoryMetaData(MetaData):NEWLINE def __init__(self, attrc, metadata="", node_name=None,NEWLINE check_validity=True, security=None, **kwargs):NEWLINE super(InMemoryMetaData, self).__init__(attrc, metadata=metadata)NEWLINE self.entity = {}NEWLINE self.security = securityNEWLINE self.node_name = node_nameNEWLINE self.entities_descr = NoneNEWLINE self.entity_descr = NoneNEWLINE self.check_validity = check_validityNEWLINE try:NEWLINE self.filter = kwargs["filter"]NEWLINE except KeyError:NEWLINE self.filter = NoneNEWLINENEWLINE def items(self):NEWLINE return self.entity.items()NEWLINENEWLINE def keys(self):NEWLINE return self.entity.keys()NEWLINENEWLINE def values(self):NEWLINE return self.entity.values()NEWLINENEWLINE def __len__(self):NEWLINE return len(self.entity)NEWLINENEWLINE def __contains__(self, item):NEWLINE return item in self.entity.keys()NEWLINENEWLINE def __getitem__(self, item):NEWLINE return self.entity[item]NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE self.entity[key] = valueNEWLINENEWLINE def __delitem__(self, key):NEWLINE del self.entity[key]NEWLINENEWLINE def do_entity_descriptor(self, entity_descr):NEWLINE if self.check_validity:NEWLINE try:NEWLINE if not valid(entity_descr.valid_until):NEWLINE logger.error("Entity descriptor (entity id:%s) too old",NEWLINE entity_descr.entity_id)NEWLINE self.to_old.append(entity_descr.entity_id)NEWLINE returnNEWLINE except AttributeError:NEWLINE passNEWLINENEWLINE # have I seen this entity_id before ? If so if log: ignore itNEWLINE if entity_descr.entity_id in self.entity:NEWLINE print("Duplicated Entity descriptor (entity id: '%s')" %NEWLINE entity_descr.entity_id, file=sys.stderr)NEWLINE returnNEWLINENEWLINE _ent = to_dict(entity_descr, metadata_modules())NEWLINE flag = 0NEWLINE # verify support for SAML2NEWLINE for descr in ["spsso", "idpsso", "role", "authn_authority",NEWLINE "attribute_authority", "pdp", "affiliation"]:NEWLINE _res = []NEWLINE try:NEWLINE _items = _ent["%s_descriptor" % descr]NEWLINE except KeyError:NEWLINE continueNEWLINENEWLINE if descr == "affiliation": # Not protocol specificNEWLINE flag += 1NEWLINE continueNEWLINENEWLINE for item in _items:NEWLINE for prot in item["protocol_support_enumeration"].split(" "):NEWLINE if prot == samlp.NAMESPACE:NEWLINE item["protocol_support_enumeration"] = protNEWLINE _res.append(item)NEWLINE breakNEWLINE if not _res:NEWLINE del _ent["%s_descriptor" % descr]NEWLINE else:NEWLINE flag += 1NEWLINENEWLINE if self.filter:NEWLINE _ent = self.filter(_ent)NEWLINE if not _ent:NEWLINE flag = 0NEWLINENEWLINE if flag:NEWLINE self.entity[entity_descr.entity_id] = _entNEWLINENEWLINE def parse(self, xmlstr):NEWLINE try:NEWLINE self.entities_descr = md.entities_descriptor_from_string(xmlstr)NEWLINE except Exception as e:NEWLINE _md_desc = (NEWLINE f'metadata file: {self.filename}'NEWLINE if isinstance(self,MetaDataFile)NEWLINE else f'remote metadata: {self.url}'NEWLINE if isinstance(self, MetaDataExtern)NEWLINE else 'metadata'NEWLINE )NEWLINE raise SAMLError(f'Failed to parse {_md_desc}') from eNEWLINENEWLINE if not self.entities_descr:NEWLINE self.entity_descr = md.entity_descriptor_from_string(xmlstr)NEWLINE if self.entity_descr:NEWLINE self.do_entity_descriptor(self.entity_descr)NEWLINE else:NEWLINE try:NEWLINE valid_instance(self.entities_descr)NEWLINE except NotValid as exc:NEWLINE logger.error("Invalid XML message: %s", exc.args[0])NEWLINE returnNEWLINENEWLINE if self.check_validity:NEWLINE try:NEWLINE if not valid(self.entities_descr.valid_until):NEWLINE raise TooOld(NEWLINE "Metadata not valid anymore, it's only valid "NEWLINE "until %s" % (NEWLINE self.entities_descr.valid_until,))NEWLINE except AttributeError:NEWLINE passNEWLINENEWLINE for entity_descr in self.entities_descr.entity_descriptor:NEWLINE self.do_entity_descriptor(entity_descr)NEWLINENEWLINE def service(self, entity_id, typ, service, binding=None):NEWLINE """ Get me all services with a specifiedNEWLINE entity ID and type, that supports the specified version of binding.NEWLINENEWLINE :param entity_id: The EntityIdNEWLINE :param typ: Type of service (idp, attribute_authority, ...)NEWLINE :param service: which service that is sought forNEWLINE :param binding: A binding identifierNEWLINE :return: list of service descriptions.NEWLINE Or if no binding was specified a list of 2-tuples (binding, srv)NEWLINE """NEWLINE try:NEWLINE srvs = []NEWLINE for t in self[entity_id][typ]:NEWLINE try:NEWLINE srvs.extend(t[service])NEWLINE except KeyError:NEWLINE passNEWLINE except KeyError:NEWLINE return NoneNEWLINENEWLINE if not srvs:NEWLINE return srvsNEWLINENEWLINE if binding:NEWLINE res = []NEWLINE for srv in srvs:NEWLINE if srv["binding"] == binding:NEWLINE res.append(srv)NEWLINE else:NEWLINE res = {}NEWLINE for srv in srvs:NEWLINE try:NEWLINE res[srv["binding"]].append(srv)NEWLINE except KeyError:NEWLINE res[srv["binding"]] = [srv]NEWLINE logger.debug("service => %s", res)NEWLINE return resNEWLINENEWLINE def attribute_requirement(self, entity_id, index=None):NEWLINE """ Returns what attributes the SP requires and which are optionalNEWLINE if any such demands are registered in the Metadata.NEWLINENEWLINE :param entity_id: The entity id of the SPNEWLINE :param index: which of the attribute consumer services its all aboutNEWLINE if index=None then return all attributes expected by allNEWLINE attribute_consuming_services.NEWLINE :return: 2-tuple, list of required and list of optional attributesNEWLINE """NEWLINE res = {"required": [], "optional": []}NEWLINENEWLINE try:NEWLINE for sp in self[entity_id]["spsso_descriptor"]:NEWLINE _res = attribute_requirement(sp, index)NEWLINE res["required"].extend(_res["required"])NEWLINE res["optional"].extend(_res["optional"])NEWLINE except KeyError:NEWLINE return NoneNEWLINENEWLINE return resNEWLINENEWLINE def construct_source_id(self):NEWLINE res = {}NEWLINE for eid, ent in self.items():NEWLINE for desc in ["spsso_descriptor", "idpsso_descriptor"]:NEWLINE try:NEWLINE for srv in ent[desc]:NEWLINE if "artifact_resolution_service" in srv:NEWLINE if isinstance(eid, six.string_types):NEWLINE eid = eid.encode('utf-8')NEWLINE s = sha1(eid)NEWLINE res[s.digest()] = entNEWLINE except KeyError:NEWLINE passNEWLINENEWLINE return resNEWLINENEWLINE def signed(self):NEWLINE if self.entities_descr and self.entities_descr.signature:NEWLINE return TrueNEWLINENEWLINE if self.entity_descr and self.entity_descr.signature:NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINENEWLINE def parse_and_check_signature(self, txt):NEWLINE self.parse(txt)NEWLINENEWLINE if not self.cert:NEWLINE return TrueNEWLINENEWLINE if not self.signed():NEWLINE return TrueNEWLINENEWLINE fallback_name = "{ns}:{tag}".format(NEWLINE ns=md.EntitiesDescriptor.c_namespace, tag=md.EntitiesDescriptor.c_tagNEWLINE )NEWLINE node_name = self.node_name or fallback_nameNEWLINENEWLINE return self.security.verify_signature(NEWLINE txt, node_name=node_name, cert_file=self.certNEWLINE )NEWLINENEWLINENEWLINEclass MetaDataFile(InMemoryMetaData):NEWLINE """NEWLINE Handles Metadata file on the same machine. The format of the file isNEWLINE the SAML Metadata format.NEWLINE """NEWLINENEWLINE def __init__(self, attrc, filename=None, cert=None, **kwargs):NEWLINE super(MetaDataFile, self).__init__(attrc, **kwargs)NEWLINE if not filename:NEWLINE raise SAMLError('No file specified.')NEWLINE self.filename = filenameNEWLINE self.cert = certNEWLINENEWLINE def get_metadata_content(self):NEWLINE with open(self.filename, 'rb') as fp:NEWLINE return fp.read()NEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE _txt = self.get_metadata_content()NEWLINE return self.parse_and_check_signature(_txt)NEWLINENEWLINENEWLINEclass MetaDataLoader(MetaDataFile):NEWLINE """NEWLINE Handles Metadata file loaded by a passed in function.NEWLINE The format of the file is the SAML Metadata format.NEWLINE """NEWLINENEWLINE def __init__(self, attrc, loader_callable, cert=None,NEWLINE security=None, **kwargs):NEWLINE super(MetaDataLoader, self).__init__(attrc, **kwargs)NEWLINE self.metadata_provider_callable = self.get_metadata_loader(NEWLINE loader_callable)NEWLINE self.cert = certNEWLINE self.security = securityNEWLINENEWLINE @staticmethodNEWLINE def get_metadata_loader(func):NEWLINE if hasattr(func, '__call__'):NEWLINE return funcNEWLINENEWLINE i = func.rfind('.')NEWLINE module, attr = func[:i], func[i + 1:]NEWLINE try:NEWLINE mod = importlib.import_module(module)NEWLINE except Exception as e:NEWLINE raise RuntimeError(NEWLINE 'Cannot find metadata provider function %s: "%s"' % (func, e))NEWLINENEWLINE try:NEWLINE metadata_loader = getattr(mod, attr)NEWLINE except AttributeError:NEWLINE raise RuntimeError(NEWLINE 'Module "%s" does not define a "%s" metadata loader' % (NEWLINE module, attr))NEWLINENEWLINE if not hasattr(metadata_loader, '__call__'):NEWLINE raise RuntimeError(NEWLINE 'Metadata loader %s.%s must be callable' % (module, attr))NEWLINENEWLINE return metadata_loaderNEWLINENEWLINE def get_metadata_content(self):NEWLINE return self.metadata_provider_callable()NEWLINENEWLINENEWLINEclass MetaDataExtern(InMemoryMetaData):NEWLINE """NEWLINE Class that handles metadata store somewhere on the net.NEWLINE Accessible by HTTP GET.NEWLINE """NEWLINENEWLINE def __init__(self, attrc, url=None, security=None, cert=None,NEWLINE http=None, **kwargs):NEWLINE """NEWLINE :params attrc:NEWLINE :params url: Location of the metadataNEWLINE :params security: SecurityContext()NEWLINE :params cert: CertificMDloaderate used to sign the metadataNEWLINE :params http:NEWLINE """NEWLINE super(MetaDataExtern, self).__init__(attrc, **kwargs)NEWLINE if not url:NEWLINE raise SAMLError('URL not specified.')NEWLINE else:NEWLINE self.url = urlNEWLINENEWLINE # No cert is only an error if the metadata is unsignedNEWLINE self.cert = certNEWLINENEWLINE self.security = securityNEWLINE self.http = httpNEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE """ Imports metadata by the use of HTTP GET.NEWLINE If the fingerprint is known the file will be checked forNEWLINE compliance before it is imported.NEWLINE """NEWLINE response = self.http.send(self.url)NEWLINE if response.status_code == 200:NEWLINE _txt = response.contentNEWLINE return self.parse_and_check_signature(_txt)NEWLINE else:NEWLINE logger.info("Response status: %s", response.status_code)NEWLINE raise SourceNotFound(self.url)NEWLINENEWLINENEWLINEclass MetaDataMD(InMemoryMetaData):NEWLINE """NEWLINE Handles locally stored metadata, the file format is the text representationNEWLINE of the Python representation of the metadata.NEWLINE """NEWLINENEWLINE def __init__(self, attrc, filename, **kwargs):NEWLINE super(MetaDataMD, self).__init__(attrc, **kwargs)NEWLINE self.filename = filenameNEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE with open(self.filename) as fp:NEWLINE data = json.load(fp)NEWLINE for key, item in data:NEWLINE self.entity[key] = itemNEWLINENEWLINENEWLINEclass MetaDataMDX(InMemoryMetaData):NEWLINE """NEWLINE Uses the MDQ protocol to fetch entity information.NEWLINE The protocol is defined at:NEWLINE https://datatracker.ietf.org/doc/draft-young-md-query-saml/NEWLINE """NEWLINENEWLINE @staticmethodNEWLINE def sha1_entity_transform(entity_id):NEWLINE entity_id_sha1 = hashlib.sha1(entity_id.encode("utf-8")).hexdigest()NEWLINE transform = "{{sha1}}{digest}".format(digest=entity_id_sha1)NEWLINE return transformNEWLINENEWLINE def __init__(self, url=None, security=None, cert=None,NEWLINE entity_transform=None, freshness_period=None, **kwargs):NEWLINE """NEWLINE :params url: mdx service urlNEWLINE :params security: SecurityContext()NEWLINE :params cert: certificate used to check signature of signed metadataNEWLINE :params entity_transform: function transforming (e.g. base64,NEWLINE sha1 hash or URL quoteNEWLINE hash) the entity id. It is applied to the entity id before it isNEWLINE concatenated with the request URL sent to the MDX server. Defaults toNEWLINE sha1 transformation.NEWLINE :params freshness_period: a duration in the format described atNEWLINE https://www.w3.org/TR/xmlschema-2/#durationNEWLINE """NEWLINE super(MetaDataMDX, self).__init__(None, **kwargs)NEWLINE if not url:NEWLINE raise SAMLError('URL for MDQ server not specified.')NEWLINENEWLINE self.url = url.rstrip('/')NEWLINENEWLINE if entity_transform:NEWLINE self.entity_transform = entity_transformNEWLINE else:NEWLINE self.entity_transform = MetaDataMDX.sha1_entity_transformNEWLINENEWLINE self.cert = certNEWLINE self.security = securityNEWLINE self.freshness_period = freshness_period or DEFAULT_FRESHNESS_PERIODNEWLINE self.expiration_date = {}NEWLINENEWLINE # We assume that the MDQ server will return a single entityNEWLINE # described by a single <EntityDescriptor> element. The protocolNEWLINE # does allow multiple entities to be returned in anNEWLINE # <EntitiesDescriptor> element but we will not currently supportNEWLINE # that use case since it is unlikely to be leveraged for mostNEWLINE # flows.NEWLINE self.node_name = "{ns}:{tag}".format(NEWLINE ns=md.EntityDescriptor.c_namespace, tag=md.EntityDescriptor.c_tagNEWLINE )NEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE # Do nothingNEWLINE passNEWLINENEWLINE def _fetch_metadata(self, item):NEWLINE mdx_url = "{url}/entities/{id}".format(NEWLINE url=self.url, id=self.entity_transform(item)NEWLINE )NEWLINENEWLINE response = requests.get(mdx_url, headers={"Accept": SAML_METADATA_CONTENT_TYPE})NEWLINE if response.status_code != 200:NEWLINE error_msg = "Fething {item}: Got response status {status}".format(NEWLINE item=item, status=response.status_codeNEWLINE )NEWLINE logger.info(error_msg)NEWLINE raise KeyError(error_msg)NEWLINENEWLINE _txt = response.contentNEWLINE if not self.parse_and_check_signature(_txt):NEWLINE error_msg = "Fething {item}: invalid signature".format(NEWLINE item=item, status=response.status_codeNEWLINE )NEWLINE logger.info(error_msg)NEWLINE raise KeyError(error_msg)NEWLINENEWLINE curr_time = str_to_time(instant())NEWLINE self.expiration_date[item] = add_duration(curr_time, self.freshness_period)NEWLINE return self.entity[item]NEWLINENEWLINE def _is_metadata_fresh(self, item):NEWLINE return before(self.expiration_date[item])NEWLINENEWLINE def __getitem__(self, item):NEWLINE if item not in self.entity:NEWLINE entity = self._fetch_metadata(item)NEWLINE elif not self._is_metadata_fresh(item):NEWLINE msg = "Metadata for {} have expired; refreshing metadata".format(item)NEWLINE logger.info(msg)NEWLINE old_entity = self.entity.pop(item)NEWLINE entity = self._fetch_metadata(item)NEWLINE else:NEWLINE entity = self.entity[item]NEWLINE return entityNEWLINENEWLINE def single_sign_on_service(self, entity_id, binding=None, typ="idpsso"):NEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "idpsso_descriptor",NEWLINE "single_sign_on_service", binding)NEWLINENEWLINENEWLINEclass MetadataStore(MetaData):NEWLINE def __init__(self, attrc, config, ca_certs=None,NEWLINE check_validity=True,NEWLINE disable_ssl_certificate_validation=False,NEWLINE filter=None):NEWLINE """NEWLINE :params attrc:NEWLINE :params config: Config()NEWLINE :params ca_certs:NEWLINE :params disable_ssl_certificate_validation:NEWLINE """NEWLINE MetaData.__init__(self, attrc, check_validity=check_validity)NEWLINENEWLINE if disable_ssl_certificate_validation:NEWLINE self.http = HTTPBase(verify=False, ca_bundle=ca_certs)NEWLINE else:NEWLINE self.http = HTTPBase(verify=True, ca_bundle=ca_certs)NEWLINENEWLINE self.security = security_context(config)NEWLINE self.ii = 0NEWLINE self.metadata = {}NEWLINE self.check_validity = check_validityNEWLINE self.filter = filterNEWLINE self.to_old = {}NEWLINENEWLINE def load(self, *args, **kwargs):NEWLINE if self.filter:NEWLINE _args = {"filter": self.filter}NEWLINE else:NEWLINE _args = {}NEWLINENEWLINE typ = args[0]NEWLINE if typ == "local":NEWLINE key = args[1]NEWLINE # if library read every file in the libraryNEWLINE if os.path.isdir(key):NEWLINE files = [f for f in os.listdir(key) if isfile(join(key, f))]NEWLINE for fil in files:NEWLINE _fil = join(key, fil)NEWLINE _md = MetaDataFile(self.attrc, _fil, **_args)NEWLINE _md.load()NEWLINE self.metadata[_fil] = _mdNEWLINE returnNEWLINE else:NEWLINE # else it's just a plain old file so read itNEWLINE _md = MetaDataFile(self.attrc, key, **_args)NEWLINE elif typ == "inline":NEWLINE self.ii += 1NEWLINE key = self.iiNEWLINE kwargs.update(_args)NEWLINE _md = InMemoryMetaData(self.attrc, args[1])NEWLINE elif typ == "remote":NEWLINE if "url" not in kwargs:NEWLINE raise ValueError("Remote metadata must be structured as a dict containing the key 'url'")NEWLINE key = kwargs["url"]NEWLINE for _key in ["node_name", "check_validity"]:NEWLINE try:NEWLINE _args[_key] = kwargs[_key]NEWLINE except KeyError:NEWLINE passNEWLINENEWLINE if "cert" not in kwargs:NEWLINE kwargs["cert"] = ""NEWLINENEWLINE _md = MetaDataExtern(self.attrc,NEWLINE kwargs["url"], self.security,NEWLINE kwargs["cert"], self.http, **_args)NEWLINE elif typ == "mdfile":NEWLINE key = args[1]NEWLINE _md = MetaDataMD(self.attrc, args[1], **_args)NEWLINE elif typ == "loader":NEWLINE key = args[1]NEWLINE _md = MetaDataLoader(self.attrc, args[1], **_args)NEWLINE elif typ == "mdq":NEWLINE if 'url' in kwargs:NEWLINE key = kwargs['url']NEWLINE url = kwargs['url']NEWLINE cert = kwargs.get('cert')NEWLINE freshness_period = kwargs.get('freshness_period', None)NEWLINE security = self.securityNEWLINE entity_transform = kwargs.get('entity_transform', None)NEWLINE _md = MetaDataMDX(url, security, cert, entity_transform,NEWLINE freshness_period=freshness_period)NEWLINE else:NEWLINE key = args[1]NEWLINE url = args[1]NEWLINE _md = MetaDataMDX(url)NEWLINE else:NEWLINE raise SAMLError("Unknown metadata type '%s'" % typ)NEWLINE _md.load()NEWLINE self.metadata[key] = _mdNEWLINENEWLINE def imp(self, spec):NEWLINE # This serves as a backwards compatibilityNEWLINE if type(spec) is dict:NEWLINE # Old style...NEWLINE for key, vals in spec.items():NEWLINE for val in vals:NEWLINE if isinstance(val, dict):NEWLINE if not self.check_validity:NEWLINE val["check_validity"] = FalseNEWLINE self.load(key, **val)NEWLINE else:NEWLINE self.load(key, val)NEWLINE else:NEWLINE for item in spec:NEWLINE try:NEWLINE key = item['class']NEWLINE except (KeyError, AttributeError):NEWLINE raise SAMLError("Misconfiguration in metadata %s" % item)NEWLINE mod, clas = key.rsplit('.', 1)NEWLINE try:NEWLINE mod = importlib.import_module(mod)NEWLINE MDloader = getattr(mod, clas)NEWLINE except (ImportError, AttributeError):NEWLINE raise SAMLError("Unknown metadata loader %s" % key)NEWLINENEWLINE # Separately handle MDExternNEWLINE if MDloader == MetaDataExtern:NEWLINE kwargs = {NEWLINE 'http': self.http,NEWLINE 'security': self.securityNEWLINE }NEWLINE else:NEWLINE kwargs = {}NEWLINENEWLINE if self.filter:NEWLINE kwargs["filter"] = self.filterNEWLINENEWLINE for key in item['metadata']:NEWLINE # Separately handle MetaDataFile and directoryNEWLINE if MDloader == MetaDataFile and os.path.isdir(key[0]):NEWLINE files = [f for f in os.listdir(key[0]) ifNEWLINE isfile(join(key[0], f))]NEWLINE for fil in files:NEWLINE _fil = join(key[0], fil)NEWLINE _md = MetaDataFile(self.attrc, _fil)NEWLINE _md.load()NEWLINE self.metadata[_fil] = _mdNEWLINE if _md.to_old:NEWLINE self.to_old[_fil] = _md.to_oldNEWLINE returnNEWLINENEWLINE if len(key) == 2:NEWLINE kwargs["cert"] = key[1]NEWLINENEWLINE _md = MDloader(self.attrc, key[0], **kwargs)NEWLINE _md.load()NEWLINE self.metadata[key[0]] = _mdNEWLINE if _md.to_old:NEWLINE self.to_old[key[0]] = _md.to_oldNEWLINENEWLINE def service(self, entity_id, typ, service, binding=None):NEWLINE known_entity = FalseNEWLINE logger.debug("service(%s, %s, %s, %s)", entity_id, typ, service,NEWLINE binding)NEWLINE for key, _md in self.metadata.items():NEWLINE srvs = _md.service(entity_id, typ, service, binding)NEWLINE if srvs:NEWLINE return srvsNEWLINE elif srvs is None:NEWLINE passNEWLINE else:NEWLINE known_entity = TrueNEWLINENEWLINE if known_entity:NEWLINE logger.error("Unsupported binding: %s (%s)", binding, entity_id)NEWLINE raise UnsupportedBinding(binding)NEWLINE else:NEWLINE logger.error("Unknown system entity: %s", entity_id)NEWLINE raise UnknownSystemEntity(entity_id)NEWLINENEWLINE def extension(self, entity_id, typ, service):NEWLINE for key, _md in self.metadata.items():NEWLINE try:NEWLINE srvs = _md[entity_id][typ]NEWLINE except KeyError:NEWLINE continueNEWLINENEWLINE res = []NEWLINE for srv in srvs:NEWLINE if "extensions" in srv:NEWLINE for elem in srv["extensions"]["extension_elements"]:NEWLINE if elem["__class__"] == service:NEWLINE res.append(elem)NEWLINE return resNEWLINENEWLINE return NoneNEWLINENEWLINE def ext_service(self, entity_id, typ, service, binding=None):NEWLINE known_entity = FalseNEWLINE for key, _md in self.metadata.items():NEWLINE srvs = _md.ext_service(entity_id, typ, service, binding)NEWLINE if srvs:NEWLINE return srvsNEWLINE elif srvs is None:NEWLINE passNEWLINE else:NEWLINE known_entity = TrueNEWLINENEWLINE if known_entity:NEWLINE raise UnsupportedBinding(binding)NEWLINE else:NEWLINE raise UnknownSystemEntity(entity_id)NEWLINENEWLINE def single_sign_on_service(self, entity_id, binding=None, typ="idpsso"):NEWLINE # IDPNEWLINENEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "idpsso_descriptor",NEWLINE "single_sign_on_service", binding)NEWLINENEWLINE def name_id_mapping_service(self, entity_id, binding=None, typ="idpsso"):NEWLINE # IDPNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "idpsso_descriptor",NEWLINE "name_id_mapping_service", binding)NEWLINENEWLINE def authn_query_service(self, entity_id, binding=None,NEWLINE typ="authn_authority"):NEWLINE # AuthnAuthorityNEWLINE if binding is None:NEWLINE binding = BINDING_SOAPNEWLINE return self.service(entity_id, "authn_authority_descriptor",NEWLINE "authn_query_service", binding)NEWLINENEWLINE def attribute_service(self, entity_id, binding=None,NEWLINE typ="attribute_authority"):NEWLINE # AttributeAuthorityNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "attribute_authority_descriptor",NEWLINE "attribute_service", binding)NEWLINENEWLINE def authz_service(self, entity_id, binding=None, typ="pdp"):NEWLINE # PDPNEWLINE if binding is None:NEWLINE binding = BINDING_SOAPNEWLINE return self.service(entity_id, "pdp_descriptor",NEWLINE "authz_service", binding)NEWLINENEWLINE def assertion_id_request_service(self, entity_id, binding=None, typ=None):NEWLINE # AuthnAuthority + IDP + PDP + AttributeAuthorityNEWLINE if typ is None:NEWLINE raise AttributeError("Missing type specification")NEWLINE if binding is None:NEWLINE binding = BINDING_SOAPNEWLINE return self.service(entity_id, "%s_descriptor" % typ,NEWLINE "assertion_id_request_service", binding)NEWLINENEWLINE def single_logout_service(self, entity_id, binding=None, typ=None):NEWLINE # IDP + SPNEWLINE if typ is None:NEWLINE raise AttributeError("Missing type specification")NEWLINE return self.service(entity_id, "%s_descriptor" % typ,NEWLINE "single_logout_service", binding)NEWLINENEWLINE def manage_name_id_service(self, entity_id, binding=None, typ=None):NEWLINE # IDP + SPNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "%s_descriptor" % typ,NEWLINE "manage_name_id_service", binding)NEWLINENEWLINE def artifact_resolution_service(self, entity_id, binding=None, typ=None):NEWLINE # IDP + SPNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "%s_descriptor" % typ,NEWLINE "artifact_resolution_service", binding)NEWLINENEWLINE def assertion_consumer_service(self, entity_id, binding=None, _="spsso"):NEWLINE # SPNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_POSTNEWLINE return self.service(entity_id, "spsso_descriptor",NEWLINE "assertion_consumer_service", binding)NEWLINENEWLINE def attribute_consuming_service(self, entity_id, binding=None, _="spsso"):NEWLINE # SPNEWLINE if binding is None:NEWLINE binding = BINDING_HTTP_REDIRECTNEWLINE return self.service(entity_id, "spsso_descriptor",NEWLINE "attribute_consuming_service", binding)NEWLINENEWLINE def discovery_response(self, entity_id, binding=None, _="spsso"):NEWLINE if binding is None:NEWLINE binding = BINDING_DISCONEWLINE return self.ext_service(entity_id, "spsso_descriptor",NEWLINE "%s&%s" % (DiscoveryResponse.c_namespace,NEWLINE DiscoveryResponse.c_tag),NEWLINE binding)NEWLINENEWLINE def attribute_requirement(self, entity_id, index=None):NEWLINE for _md in self.metadata.values():NEWLINE if entity_id in _md:NEWLINE return _md.attribute_requirement(entity_id, index)NEWLINENEWLINE def keys(self):NEWLINE res = []NEWLINE for _md in self.metadata.values():NEWLINE res.extend(_md.keys())NEWLINE return resNEWLINENEWLINE def __getitem__(self, item):NEWLINE for _md in self.metadata.values():NEWLINE try:NEWLINE return _md[item]NEWLINE except KeyError:NEWLINE passNEWLINENEWLINE raise KeyError(item)NEWLINENEWLINE def __setitem__(self, key, value):NEWLINE self.metadata[key] = valueNEWLINENEWLINE def entities(self):NEWLINE num = 0NEWLINE for _md in self.metadata.values():NEWLINE num += len(_md.items())NEWLINENEWLINE return numNEWLINENEWLINE def __len__(self):NEWLINE return len(self.metadata)NEWLINENEWLINE def with_descriptor(self, descriptor):NEWLINE res = {}NEWLINE for _md in self.metadata.values():NEWLINE res.update(_md.with_descriptor(descriptor))NEWLINE return resNEWLINENEWLINE def name(self, entity_id, langpref="en"):NEWLINE for _md in self.metadata.values():NEWLINE if entity_id in _md:NEWLINE return name(_md[entity_id], langpref)NEWLINE return NoneNEWLINENEWLINE def vo_members(self, entity_id):NEWLINE ad = self.__getitem__(entity_id)["affiliation_descriptor"]NEWLINE return [m["text"] for m in ad["affiliate_member"]]NEWLINENEWLINE def entity_categories(self, entity_id):NEWLINE """NEWLINE Get a list of entity categories for an entity id.NEWLINENEWLINE :param entity_id: Entity idNEWLINE :return: Entity categoriesNEWLINENEWLINE :type entity_id: stringNEWLINE :rtype: [string]NEWLINE """NEWLINE attributes = self.entity_attributes(entity_id)NEWLINE return attributes.get(ENTITY_CATEGORY, [])NEWLINENEWLINE def supported_entity_categories(self, entity_id):NEWLINE """NEWLINE Get a list of entity category support for an entity id.NEWLINENEWLINE :param entity_id: Entity idNEWLINE :return: Entity category supportNEWLINENEWLINE :type entity_id: stringNEWLINE :rtype: [string]NEWLINE """NEWLINE attributes = self.entity_attributes(entity_id)NEWLINE return attributes.get(ENTITY_CATEGORY_SUPPORT, [])NEWLINENEWLINE def assurance_certifications(self, entity_id):NEWLINE assurance_certifications = (NEWLINE certificationNEWLINE for name, values in self.entity_attributes(entity_id).items()NEWLINE if name == ASSURANCE_CERTIFICATIONNEWLINE for certification in valuesNEWLINE )NEWLINE return assurance_certificationsNEWLINENEWLINE def entity_attributes(self, entity_id):NEWLINE """NEWLINE Get all entity attributes for an entry in the metadata.NEWLINENEWLINE Example return data:NEWLINENEWLINE {'http://macedir.org/entity-category': ['something', 'something2'],NEWLINE 'http://example.org/saml-foo': ['bar']}NEWLINENEWLINE :param entity_id: Entity idNEWLINE :return: dict with keys and value-lists from metadataNEWLINENEWLINE :type entity_id: stringNEWLINE :rtype: dictNEWLINE """NEWLINE res = {}NEWLINE try:NEWLINE ext = self.__getitem__(entity_id)["extensions"]NEWLINE except KeyError:NEWLINE return resNEWLINE for elem in ext["extension_elements"]:NEWLINE if elem["__class__"] == classnames["mdattr_entityattributes"]:NEWLINE for attr in elem["attribute"]:NEWLINE if attr["name"] not in res:NEWLINE res[attr["name"]] = []NEWLINE res[attr["name"]] += [v["text"] for v in attr[NEWLINE "attribute_value"]]NEWLINE return resNEWLINENEWLINE def supported_algorithms(self, entity_id):NEWLINE """NEWLINE Get all supported algorithms for an entry in the metadata.NEWLINENEWLINE Example return data:NEWLINENEWLINE {'digest_methods': ['http://www.w3.org/2001/04/xmldsig-more#sha224', 'http://www.w3.org/2001/04/xmlenc#sha256'],NEWLINE 'signing_methods': ['http://www.w3.org/2001/04/xmldsig-more#rsa-sha256']}NEWLINENEWLINE :param entity_id: Entity idNEWLINE :return: dict with keys and value-lists from metadataNEWLINENEWLINE :type entity_id: stringNEWLINE :rtype: dictNEWLINE """NEWLINE res = {NEWLINE 'digest_methods': [],NEWLINE 'signing_methods': []NEWLINE }NEWLINE try:NEWLINE ext = self.__getitem__(entity_id)["extensions"]NEWLINE except KeyError:NEWLINE return resNEWLINE for elem in ext["extension_elements"]:NEWLINE if elem["__class__"] == classnames["algsupport_digest_method"]:NEWLINE res['digest_methods'].append(elem['algorithm'])NEWLINE elif elem["__class__"] == classnames["algsupport_signing_method"]:NEWLINE res['signing_methods'].append(elem['algorithm'])NEWLINE return resNEWLINENEWLINE def registration_info(self, entity_id):NEWLINE """NEWLINE Get all registration info for an entry in the metadata.NEWLINENEWLINE Example return data:NEWLINENEWLINE res = {NEWLINE 'registration_authority': 'http://www.example.com',NEWLINE 'registration_instant': '2013-06-15T18:15:03Z',NEWLINE 'registration_policy': {NEWLINE 'en': 'http://www.example.com/policy.html',NEWLINE 'sv': 'http://www.example.com/sv/policy.html',NEWLINE }NEWLINE }NEWLINENEWLINE :param entity_id: Entity idNEWLINE :return: dict with keys and value-lists from metadataNEWLINENEWLINE :type entity_id: stringNEWLINE :rtype: dictNEWLINE """NEWLINE try:NEWLINE ext = self.__getitem__(entity_id)NEWLINE except KeyError:NEWLINE ext = {}NEWLINENEWLINE ext_elems = ext.get("extensions", {}).get("extension_elements", [])NEWLINE reg_info = next(NEWLINE (NEWLINE elemNEWLINE for elem in ext_elemsNEWLINE if elem["__class__"] == classnames["mdrpi_registration_info"]NEWLINE ),NEWLINE {},NEWLINE )NEWLINE res = {NEWLINE "registration_authority": reg_info.get("registration_authority"),NEWLINE "registration_instant": reg_info.get("registration_instant"),NEWLINE "registration_policy": {NEWLINE policy["lang"]: policy["text"]NEWLINE for policy in reg_info.get("registration_policy", [])NEWLINE if policy["__class__"] == classnames["mdrpi_registration_policy"]NEWLINE },NEWLINE }NEWLINE return resNEWLINENEWLINE def _lookup_elements_by_cls(self, root, cls):NEWLINE elements = (NEWLINE elementNEWLINE for uiinfo in rootNEWLINE for element_key, elements in uiinfo.items()NEWLINE if element_key != "__class__"NEWLINE for element in elementsNEWLINE if element.get("__class__") == clsNEWLINE )NEWLINE return elementsNEWLINENEWLINE def _lookup_elements_by_key(self, root, key):NEWLINE elements = (NEWLINE elementNEWLINE for uiinfo in rootNEWLINE for elements in [uiinfo.get(key, [])]NEWLINE for element in elementsNEWLINE )NEWLINE return elementsNEWLINENEWLINE def sbibmd_scopes(self, entity_id, typ=None):NEWLINE try:NEWLINE md = self[entity_id]NEWLINE except KeyError:NEWLINE md = {}NEWLINENEWLINE descriptor_scopes = (NEWLINE {NEWLINE "regexp": is_regexp,NEWLINE "text": regex_compile(text) if is_regexp else text,NEWLINE }NEWLINE for elem in md.get("extensions", {}).get("extension_elements", [])NEWLINE if elem.get("__class__") == classnames["shibmd_scope"]NEWLINE for is_regexp, text in [NEWLINE (elem.get("regexp", "").lower() == "true", elem.get("text", "")),NEWLINE ]NEWLINE )NEWLINENEWLINE services_of_type = md.get(typ) or []NEWLINE services_of_type_scopes = (NEWLINE {NEWLINE "regexp": is_regexp,NEWLINE "text": regex_compile(text) if is_regexp else text,NEWLINE }NEWLINE for srv in services_of_typeNEWLINE for elem in srv.get("extensions", {}).get("extension_elements", [])NEWLINE if elem.get("__class__") == classnames["shibmd_scope"]NEWLINE for is_regexp, text in [NEWLINE (elem.get("regexp", "").lower() == "true", elem.get("text", "")),NEWLINE ]NEWLINE )NEWLINENEWLINE scopes = chain(descriptor_scopes, services_of_type_scopes)NEWLINE return scopesNEWLINENEWLINE def mdui_uiinfo(self, entity_id):NEWLINE try:NEWLINE data = self[entity_id]NEWLINE except KeyError:NEWLINE data = {}NEWLINENEWLINE descriptor_names = (NEWLINE itemNEWLINE for item in data.keys()NEWLINE if item.endswith("_descriptor")NEWLINE )NEWLINE descriptors = (NEWLINE descriptorNEWLINE for descriptor_name in descriptor_namesNEWLINE for descriptor in self[entity_id].get(descriptor_name, [])NEWLINE )NEWLINE extensions = (NEWLINE extensionNEWLINE for descriptor in descriptorsNEWLINE for extension in descriptor.get("extensions", {}).get("extension_elements", [])NEWLINE )NEWLINE uiinfos = (NEWLINE extensionNEWLINE for extension in extensionsNEWLINE if extension.get("__class__") == classnames["mdui_uiinfo"]NEWLINE )NEWLINE return uiinfosNEWLINENEWLINE def _mdui_uiinfo_i18n_elements_lookup(self, entity_id, langpref, element_hint, lookup):NEWLINE uiinfos = self.mdui_uiinfo(entity_id)NEWLINE elements = lookup(uiinfos, element_hint)NEWLINE lang_elements = (NEWLINE elementNEWLINE for element in elementsNEWLINE if langpref is None or element.get("lang") == langprefNEWLINE )NEWLINE values = (NEWLINE valueNEWLINE for element in lang_elementsNEWLINE for value in [element.get("text")]NEWLINE )NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_i18n_element_cls(self, entity_id, langpref, element_cls):NEWLINE values = self._mdui_uiinfo_i18n_elements_lookup(NEWLINE entity_id, langpref, element_cls, self._lookup_elements_by_clsNEWLINE )NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_i18n_element_key(self, entity_id, langpref, element_key):NEWLINE values = self._mdui_uiinfo_i18n_elements_lookup(NEWLINE entity_id, langpref, element_key, self._lookup_elements_by_keyNEWLINE )NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_display_name(self, entity_id, langpref=None):NEWLINE cls = classnames["mdui_uiinfo_display_name"]NEWLINE values = self.mdui_uiinfo_i18n_element_cls(entity_id, langpref, cls)NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_description(self, entity_id, langpref=None):NEWLINE cls = classnames["mdui_uiinfo_description"]NEWLINE values = self.mdui_uiinfo_i18n_element_cls(entity_id, langpref, cls)NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_information_url(self, entity_id, langpref=None):NEWLINE cls = classnames["mdui_uiinfo_information_url"]NEWLINE values = self.mdui_uiinfo_i18n_element_cls(entity_id, langpref, cls)NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_privacy_statement_url(self, entity_id, langpref=None):NEWLINE cls = classnames["mdui_uiinfo_privacy_statement_url"]NEWLINE values = self.mdui_uiinfo_i18n_element_cls(entity_id, langpref, cls)NEWLINE return valuesNEWLINENEWLINE def mdui_uiinfo_logo(self, entity_id, width=None, height=None):NEWLINE uiinfos = self.mdui_uiinfo(entity_id)NEWLINE cls = classnames["mdui_uiinfo_logo"]NEWLINE elements = self._lookup_elements_by_cls(uiinfos, cls)NEWLINE values = (NEWLINE elementNEWLINE for element in elementsNEWLINE if width is None or element.get("width") == widthNEWLINE if height is None or element.get("height") == heightNEWLINE )NEWLINE return valuesNEWLINENEWLINE def contact_person_data(self, entity_id, contact_type=None):NEWLINE try:NEWLINE data = self[entity_id]NEWLINE except KeyError:NEWLINE data = {}NEWLINENEWLINE contacts = (NEWLINE {NEWLINE "contact_type": _contact_type,NEWLINE "given_name": contact.get("given_name", {}).get("text", ""),NEWLINE "email_address": [NEWLINE addressNEWLINE for email in contact.get("email_address", {})NEWLINE for address in [email.get("text")]NEWLINE if addressNEWLINE ],NEWLINE }NEWLINE for contact in data.get("contact_person", [])NEWLINE for _contact_type in [contact.get("contact_type", "")]NEWLINE if contact_type is None or contact_type == _contact_typeNEWLINE )NEWLINENEWLINE return contactsNEWLINENEWLINE def bindings(self, entity_id, typ, service):NEWLINE for _md in self.metadata.values():NEWLINE if entity_id in _md.items():NEWLINE return _md.bindings(entity_id, typ, service)NEWLINENEWLINE return NoneNEWLINENEWLINE def __str__(self):NEWLINE _str = ["{"]NEWLINE for key, val in self.metadata.items():NEWLINE _str.append("%s: %s" % (key, val))NEWLINE _str.append("}")NEWLINE return "\n".join(_str)NEWLINENEWLINE def construct_source_id(self):NEWLINE res = {}NEWLINE for _md in self.metadata.values():NEWLINE res.update(_md.construct_source_id())NEWLINE return resNEWLINENEWLINE def items(self):NEWLINE res = {}NEWLINE for _md in self.metadata.values():NEWLINE res.update(_md.items())NEWLINE return res.items()NEWLINENEWLINE def _providers(self, descriptor):NEWLINE res = []NEWLINE for _md in self.metadata.values():NEWLINE for ent_id, ent_desc in _md.items():NEWLINE if descriptor in ent_desc:NEWLINE if ent_id in res:NEWLINE # print("duplicated entity_id: %s" % res)NEWLINE passNEWLINE else:NEWLINE res.append(ent_id)NEWLINE return resNEWLINENEWLINE def service_providers(self):NEWLINE return self._providers("spsso_descriptor")NEWLINENEWLINE def identity_providers(self):NEWLINE return self._providers("idpsso_descriptor")NEWLINENEWLINE def attribute_authorities(self):NEWLINE return self._providers("attribute_authority")NEWLINENEWLINE def dumps(self, format="local"):NEWLINE """NEWLINE Dumps the content in standard metadata format or the pysaml2 metadataNEWLINE formatNEWLINENEWLINE :param format: Which format to dump inNEWLINE :return: a stringNEWLINE """NEWLINE if format == "local":NEWLINE res = EntitiesDescriptor()NEWLINE for _md in self.metadata.values():NEWLINE try:NEWLINE res.entity_descriptor.extend(NEWLINE _md.entities_descr.entity_descriptor)NEWLINE except AttributeError:NEWLINE res.entity_descriptor.append(_md.entity_descr)NEWLINENEWLINE return "%s" % resNEWLINE elif format == "md":NEWLINE # self.items() returns dictitems(), convert that back into a dictNEWLINE return json.dumps(dict(self.items()), indent=2)NEWLINE
# -*- coding: utf-8 -*-NEWLINEfrom __future__ import absolute_import, division, print_function, unicode_literalsNEWLINENEWLINEfrom copy import deepcopyNEWLINENEWLINEfrom django.test.testcases import TestCaseNEWLINENEWLINEfrom djstripe.models import CouponNEWLINENEWLINEfrom . import FAKE_COUPONNEWLINENEWLINENEWLINEclass TransferTest(TestCase):NEWLINE def test_retrieve_coupon(self):NEWLINE coupon_data = deepcopy(FAKE_COUPON)NEWLINE coupon = Coupon.sync_from_stripe_data(coupon_data)NEWLINE self.assertEqual(coupon.stripe_id, FAKE_COUPON["id"])NEWLINENEWLINENEWLINEclass HumanReadableCouponTest(TestCase):NEWLINE def test_human_readable_usd_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "$10.00 USD off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_eur_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-amount-off-forever", amount_off=10, currency="eur",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "€10.00 EUR off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_forever(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-forever", percent_off=10, currency="usd",NEWLINE duration="forever",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off forever")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_once(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-once", percent_off=10, currency="usd",NEWLINE duration="once",NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off once")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_one_month(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-1month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=1,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 1 month")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINENEWLINE def test_human_readable_percent_off_three_months(self):NEWLINE coupon = Coupon.objects.create(NEWLINE stripe_id="coupon-test-percent-off-3month", percent_off=10, currency="usd",NEWLINE duration="repeating", duration_in_months=3,NEWLINE )NEWLINE self.assertEqual(coupon.human_readable, "10% off for 3 months")NEWLINE self.assertEqual(str(coupon), coupon.human_readable)NEWLINE
from __future__ import absolute_importNEWLINENEWLINEimport sixNEWLINEimport pytzNEWLINENEWLINEfrom datetime import datetimeNEWLINENEWLINEfrom sentry.coreapi import APIUnauthorizedNEWLINEfrom sentry.mediators import Mediator, ParamNEWLINEfrom sentry.mediators.token_exchange.validator import ValidatorNEWLINEfrom sentry.mediators.token_exchange.util import token_expirationNEWLINEfrom sentry.models import ApiApplication, ApiToken, SentryAppNEWLINEfrom sentry.utils.cache import memoizeNEWLINENEWLINENEWLINEclass Refresher(Mediator):NEWLINE """NEWLINE Exchanges a Refresh Token for a new Access TokenNEWLINE """NEWLINENEWLINE install = Param('sentry.models.SentryAppInstallation')NEWLINE refresh_token = Param(six.string_types)NEWLINE client_id = Param(six.string_types)NEWLINE user = Param('sentry.models.User')NEWLINENEWLINE def call(self):NEWLINE self._validate()NEWLINE self._expire_token()NEWLINENEWLINE return ApiToken.objects.create(NEWLINE user=self.user,NEWLINE application=self.application,NEWLINE scope_list=self.sentry_app.scope_list,NEWLINE expires_at=token_expiration(),NEWLINE )NEWLINENEWLINE def _validate(self):NEWLINE Validator.run(NEWLINE install=self.install,NEWLINE client_id=self.client_id,NEWLINE user=self.user,NEWLINE )NEWLINENEWLINE self._validate_token_belongs_to_app()NEWLINE self._validate_token_is_active()NEWLINENEWLINE def _validate_token_belongs_to_app(self):NEWLINE if self.token.application != self.application:NEWLINE raise APIUnauthorizedNEWLINENEWLINE def _validate_token_is_active(self):NEWLINE if self.token.expires_at < datetime.utcnow().replace(tzinfo=pytz.UTC):NEWLINE raise APIUnauthorizedNEWLINENEWLINE def _expire_token(self):NEWLINE self.token.update(expires_at=datetime.utcnow())NEWLINENEWLINE @memoizeNEWLINE def token(self):NEWLINE try:NEWLINE return ApiToken.objects.get(refresh_token=self.refresh_token)NEWLINE except ApiToken.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINENEWLINE @memoizeNEWLINE def application(self):NEWLINE try:NEWLINE return ApiApplication.objects.get(client_id=self.client_id)NEWLINE except ApiApplication.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINENEWLINE @propertyNEWLINE def sentry_app(self):NEWLINE try:NEWLINE return self.application.sentry_appNEWLINE except SentryApp.DoesNotExist:NEWLINE raise APIUnauthorizedNEWLINE
import abcNEWLINEfrom typing import Type, UnionNEWLINEimport numpy as npNEWLINENEWLINEfrom uncertainty_framework.report._report import Report as ReportBaseClassNEWLINEfrom uncertainty_framework.report.margins import MarginReportNEWLINEfrom uncertainty_framework.report.console import ConsoleReportNEWLINEfrom uncertainty_framework.report.plot import PlotReportNEWLINENEWLINENEWLINEclass Simulator(abc.ABC):NEWLINE def __init__(self):NEWLINE self.result = NoneNEWLINENEWLINE """Simulator base class"""NEWLINE @abc.abstractmethodNEWLINE def run(self, **kwargs) -> np.ndarray:NEWLINE """NEWLINE The run function has to run the actual simulation NEWLINE and needs at least to be implemented.NEWLINE It has to return a numpy array with all simulation NEWLINE results in it, which can be used by reporting NEWLINE and statistics tools.NEWLINE """NEWLINE passNEWLINENEWLINE def __call__(self, **kwargs) -> np.ndarray:NEWLINE self.result = self.run(**kwargs)NEWLINE return self.resultNEWLINENEWLINE def render(self, Report: Union[Type[ReportBaseClass], str] ='console', result: np.ndarray =None, **kwargs):NEWLINE """NEWLINE Render the results with the given classNEWLINE """NEWLINE # TODO: here we could accept some strings like 'html'NEWLINE # and so on to load default reporting classesNEWLINE NEWLINE # check if a result is calculatedNEWLINE if result is None:NEWLINE result = self.resultNEWLINE if result is None:NEWLINE raise RuntimeError("No simulation result found. Call this instance or pass the result matrix.")NEWLINE NEWLINE # load a predefined Report classNEWLINE if isinstance(Report, str):NEWLINE if Report.lower() == 'margin':NEWLINE Report = MarginReportNEWLINE elif Report.lower() == 'console':NEWLINE Report = ConsoleReportNEWLINE elif Report.lower() == 'plot':NEWLINE Report = PlotReportNEWLINE else:NEWLINE raise ValueError("'%s' is not a known Report option." % Report)NEWLINE NEWLINE # instantiate a reportNEWLINE report = Report(result=result)NEWLINENEWLINE # return the reportNEWLINE return report(**kwargs)NEWLINE
import jsonNEWLINEimport subprocessNEWLINEfrom pathlib import PathNEWLINEfrom pprint import pprintNEWLINEfrom urllib.parse import urlencodeNEWLINEfrom urllib.request import Request, urlopenNEWLINENEWLINEimport clickNEWLINEfrom InquirerPy import promptNEWLINENEWLINEfrom .utils import cdNEWLINENEWLINENEWLINEdef read_lines(file):NEWLINE fpath = Path(file)NEWLINE if fpath.is_file():NEWLINE with open(fpath, "r") as f:NEWLINE lines = f.readlines()NEWLINE result = [l.strip() for l in lines if l.strip()]NEWLINE else:NEWLINE result = []NEWLINE return resultNEWLINENEWLINENEWLINEdef io_handler(file, data=None, op="r"):NEWLINE fpath = Path(file)NEWLINE if op == "r":NEWLINE if fpath.is_file():NEWLINE with open(fpath, "r") as f:NEWLINE return [l.rstrip("\n") for l in f if l.rstrip("\n")]NEWLINE return []NEWLINE else:NEWLINE with open(fpath, "w+") as f:NEWLINE f.writelines("\n".join(data))NEWLINENEWLINENEWLINEdef repo_cloned():NEWLINE repos = {}NEWLINE for dir in Path(".").iterdir():NEWLINE if dir.is_dir() and Path(dir / ".git").is_dir():NEWLINE with cd(dir):NEWLINE command = ["git", "config", "--get", "remote.origin.url"]NEWLINE link = subprocess.check_output(command, text=True).strip()NEWLINE repos[link] = dirNEWLINE return reposNEWLINENEWLINENEWLINEdef _sync():NEWLINE repos = repo_cloned()NEWLINE links = io_handler("repo.txt", op="r")NEWLINENEWLINE click.secho("update repo.txt", fg="yellow", bold=True)NEWLINE links = sorted(list(set(links) | set(repos.keys())))NEWLINE io_handler("repo.txt", data=links, op="w")NEWLINE subprocess.run(["cat", "repo.txt"])NEWLINENEWLINE click.echo("\n")NEWLINE click.secho("update .gitignore", fg="yellow", bold=True)NEWLINE gitignore = io_handler(".gitignore", op="r")NEWLINE addtions = []NEWLINE for dir in repos.values():NEWLINE has_found = FalseNEWLINE for ignore in gitignore:NEWLINE if dir.name in ignore:NEWLINE has_found = TrueNEWLINE continueNEWLINE if not has_found:NEWLINE addtions.append(dir.name + "/")NEWLINE gitignore.extend(addtions)NEWLINE io_handler(".gitignore", data=gitignore, op="w")NEWLINE subprocess.run(["cat", ".gitignore"])NEWLINENEWLINENEWLINE@click.group()NEWLINEdef cli():NEWLINE passNEWLINENEWLINENEWLINE@cli.command()NEWLINE@click.argument("q")NEWLINE@click.option("-l", "--language")NEWLINE@click.option(NEWLINE "-s",NEWLINE "--sort",NEWLINE type=click.Choice(["best-match", "stars", "forks", "help-wanted-issues", "updated"]),NEWLINE default="best-match",NEWLINE)NEWLINE@click.option("-o", "--order", type=click.Choice(["desc", "asc"]), default="desc")NEWLINEdef search(q, language, sort, order):NEWLINE if language:NEWLINE params = urlencode({"q": f"{q}+language:{language}", "sort": sort, "order": order})NEWLINE else:NEWLINE params = urlencode({"q": q, "sort": sort, "order": order})NEWLINENEWLINE click.secho(f"Command: repo search {params} ↩︎", fg="green", bold=True)NEWLINE base_url = "https://api.github.com/search/repositories"NEWLINE request = Request(f"{base_url}?{params}")NEWLINE request.add_header("Accept", "application/vnd.github.v3+json")NEWLINENEWLINE result = []NEWLINE for item in json.load(urlopen(request))["items"]:NEWLINE result.append(NEWLINE {NEWLINE "name": item["name"],NEWLINE "full_name": item["full_name"],NEWLINE "description": item["description"],NEWLINE "ssh_url": item["ssh_url"],NEWLINE "html_url": item["html_url"],NEWLINE "visibility": item["visibility"],NEWLINE "updated_at": item["updated_at"],NEWLINE "created_at": item["created_at"],NEWLINE }NEWLINE )NEWLINENEWLINE pprint(result, sort_dicts=False)NEWLINENEWLINENEWLINE@cli.command()NEWLINE@click.option("--all", is_flag=True)NEWLINEdef clone(all):NEWLINE links = io_handler("repo.txt", op="r")NEWLINE if all:NEWLINE click.secho("Command: repo clone --all ↩︎", fg="green", bold=True)NEWLINE for link in links:NEWLINE name = link.rpartition(".")[0].partition(":")[-1].partition("/")[-1]NEWLINE if not Path(name).is_dir():NEWLINE click.secho(f"clone {link}", fg="yellow", bold=True)NEWLINE subprocess.run(["git", "clone", link])NEWLINE else:NEWLINE click.secho("Command: repo clone ↩︎", fg="green", bold=True)NEWLINE question = [NEWLINE {NEWLINE "type": "list",NEWLINE "name": "repo",NEWLINE "message": "Which repo do you want?",NEWLINE "choices": links,NEWLINE }NEWLINE ]NEWLINE link = prompt(question)["repo"]NEWLINE name = link.rpartition(".")[0].partition(":")[-1].partition("/")[-1]NEWLINE if not Path(name).is_dir():NEWLINE click.secho(f"git clone {link}", fg="yellow", bold=True)NEWLINE subprocess.run(["git", "clone", link])NEWLINE _sync()NEWLINENEWLINENEWLINE@cli.command()NEWLINE@click.option("--all", is_flag=True)NEWLINEdef pull(all):NEWLINE repos = repo_cloned()NEWLINE if all:NEWLINE click.secho("Command: repo pull --all ↩︎", fg="green", bold=True)NEWLINE for dir in repos.values():NEWLINE with cd(dir):NEWLINE click.secho(f"cd {dir.name}; git pull", fg="yellow", bold=True)NEWLINE subprocess.run(["git", "pull"])NEWLINENEWLINE else:NEWLINE click.secho("Command: repo pull ↩︎", fg="green", bold=True)NEWLINE question = [NEWLINE {NEWLINE "type": "list",NEWLINE "name": "repo",NEWLINE "message": "Which repo do you want?",NEWLINE "choices": [dir.name for dir in repos.values()],NEWLINE }NEWLINE ]NEWLINE name = prompt(question)["repo"]NEWLINE with cd(name):NEWLINE click.secho(f"cd {name}; git pull", fg="yellow", bold=True)NEWLINE subprocess.run(["git", "pull"])NEWLINENEWLINENEWLINE@cli.command()NEWLINE@click.option("-o", "--output", default="repo.txt")NEWLINEdef sync(output):NEWLINE click.secho(f"Command: repo sync ↩︎", fg="green", bold=True)NEWLINE _sync()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE cli()NEWLINE
# PyYAML libraryNEWLINE__license__ = 'MIT'NEWLINE__author__ = 'Kirill Simonov'NEWLINE__copyright__ = """NEWLINE Copyright (c) 2017-2020 Ingy döt NetNEWLINE Copyright (c) 2006-2016 Kirill SimonovNEWLINE """NEWLINENEWLINE# For changes regarding this port for Ignition usage, please contact:NEWLINE__maintainer__ = 'Andrew Geiger'NEWLINE__email__ = 'andrew.geiger@corsosystems.com'NEWLINENEWLINENEWLINE__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError']NEWLINENEWLINEclass Mark(object):NEWLINENEWLINE def __init__(self, name, index, line, column, buffer, pointer):NEWLINE self.name = nameNEWLINE self.index = indexNEWLINE self.line = lineNEWLINE self.column = columnNEWLINE self.buffer = bufferNEWLINE self.pointer = pointerNEWLINENEWLINE def get_snippet(self, indent=4, max_length=75):NEWLINE if self.buffer is None:NEWLINE return NoneNEWLINE head = ''NEWLINE start = self.pointerNEWLINE while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029':NEWLINE start -= 1NEWLINE if self.pointer-start > max_length/2-1:NEWLINE head = ' ... 'NEWLINE start += 5NEWLINE breakNEWLINE tail = ''NEWLINE end = self.pointerNEWLINE while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029':NEWLINE end += 1NEWLINE if end-self.pointer > max_length/2-1:NEWLINE tail = ' ... 'NEWLINE end -= 5NEWLINE breakNEWLINE snippet = self.buffer[start:end].encode('utf-8')NEWLINE return ' '*indent + head + snippet + tail + '\n' \NEWLINE + ' '*(indent+self.pointer-start+len(head)) + '^'NEWLINENEWLINE def __str__(self):NEWLINE snippet = self.get_snippet()NEWLINE where = " in \"%s\", line %d, column %d" \NEWLINE % (self.name, self.line+1, self.column+1)NEWLINE if snippet is not None:NEWLINE where += ":\n"+snippetNEWLINE return whereNEWLINENEWLINEclass YAMLError(Exception):NEWLINE passNEWLINENEWLINEclass MarkedYAMLError(YAMLError):NEWLINENEWLINE def __init__(self, context=None, context_mark=None,NEWLINE problem=None, problem_mark=None, note=None):NEWLINE self.context = contextNEWLINE self.context_mark = context_markNEWLINE self.problem = problemNEWLINE self.problem_mark = problem_markNEWLINE self.note = noteNEWLINENEWLINE def __str__(self):NEWLINE lines = []NEWLINE if self.context is not None:NEWLINE lines.append(self.context)NEWLINE if self.context_mark is not None \NEWLINE and (self.problem is None or self.problem_mark is NoneNEWLINE or self.context_mark.name != self.problem_mark.nameNEWLINE or self.context_mark.line != self.problem_mark.lineNEWLINE or self.context_mark.column != self.problem_mark.column):NEWLINE lines.append(str(self.context_mark))NEWLINE if self.problem is not None:NEWLINE lines.append(self.problem)NEWLINE if self.problem_mark is not None:NEWLINE lines.append(str(self.problem_mark))NEWLINE if self.note is not None:NEWLINE lines.append(self.note)NEWLINE return '\n'.join(lines)NEWLINE
for c in range(0,51):NEWLINE if c % 2 == 0:NEWLINE print(c)NEWLINEprint('Programa Finalizado')NEWLINE
import importlibNEWLINEimport osNEWLINEimport timeNEWLINEimport randomNEWLINENEWLINEimport torchNEWLINEimport torch.nn.functional as FNEWLINEimport numpy as npNEWLINEimport ComputePostBNNEWLINEfrom utils.setlogger import get_loggerNEWLINENEWLINEfrom utils.model_profiling import model_profilingNEWLINEfrom utils.config import FLAGSNEWLINEfrom utils.datasets import get_datasetNEWLINENEWLINE# set log filesNEWLINEsaved_path = os.path.join("logs", '{}-{}'.format(FLAGS.dataset, FLAGS.model[7:]))NEWLINEif not os.path.exists(saved_path):NEWLINE os.makedirs(saved_path)NEWLINElogger = get_logger(os.path.join(saved_path, '{}_div1optimizer.log'.format('test' if FLAGS.test_only else 'train')))NEWLINENEWLINEdef set_random_seed():NEWLINE """set random seed"""NEWLINE if hasattr(FLAGS, 'random_seed'):NEWLINE seed = FLAGS.random_seedNEWLINE else:NEWLINE seed = 0NEWLINE random.seed(seed)NEWLINE np.random.seed(seed)NEWLINE torch.manual_seed(seed)NEWLINE torch.cuda.manual_seed(seed)NEWLINE torch.cuda.manual_seed_all(seed)NEWLINENEWLINEdef get_model():NEWLINE """get model"""NEWLINE model_lib = importlib.import_module(FLAGS.model)NEWLINE model = model_lib.Model(FLAGS.num_classes, input_size=FLAGS.image_size)NEWLINE return modelNEWLINENEWLINEdef get_optimizer(model):NEWLINE """get optimizer"""NEWLINE # all depthwise convolution (N, 1, x, x) has no weight decayNEWLINE # weight decay only on normal conv and fcNEWLINE if FLAGS.dataset == 'imagenet1k':NEWLINE model_params = []NEWLINE for params in model.parameters():NEWLINE ps = list(params.size())NEWLINE if len(ps) == 4 and ps[1] != 1: # normal convNEWLINE weight_decay = FLAGS.weight_decayNEWLINE elif len(ps) == 2: # fcNEWLINE weight_decay = FLAGS.weight_decayNEWLINE else:NEWLINE weight_decay = 0NEWLINE item = {'params': params, 'weight_decay': weight_decay,NEWLINE 'lr': FLAGS.lr, 'momentum': FLAGS.momentum,NEWLINE 'nesterov': FLAGS.nesterov}NEWLINE model_params.append(item)NEWLINE optimizer = torch.optim.SGD(model_params)NEWLINE else:NEWLINE optimizer = torch.optim.SGD(model.parameters(), FLAGS.lr,NEWLINE momentum=FLAGS.momentum, nesterov=FLAGS.nesterov,NEWLINE weight_decay=FLAGS.weight_decay)NEWLINE return optimizerNEWLINENEWLINEdef profiling(model, use_cuda):NEWLINE """profiling on either gpu or cpu"""NEWLINE print('Start model profiling, use_cuda:{}.'.format(use_cuda))NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(NEWLINE lambda m: setattr(m, 'width_mult', width_mult))NEWLINE print('Model profiling with width mult {}x:'.format(width_mult))NEWLINE verbose = width_mult == max(FLAGS.width_mult_list)NEWLINE model_profiling(NEWLINE model, FLAGS.image_size, FLAGS.image_size,NEWLINE verbose=getattr(FLAGS, 'model_profiling_verbose', verbose))NEWLINENEWLINEdef train(epoch, loader, model, criterion, optimizer, lr_scheduler):NEWLINE t_start = time.time()NEWLINE model.train()NEWLINE for batch_idx, (input_list, target) in enumerate(loader):NEWLINE target = target.cuda(non_blocking=True)NEWLINE optimizer.zero_grad()NEWLINE # do max widthNEWLINE max_width = FLAGS.width_mult_range[1]NEWLINE model.apply(lambda m: setattr(m, 'width_mult', max_width))NEWLINE max_output = model(input_list[0])NEWLINE loss = criterion(max_output, target)NEWLINE loss.backward()NEWLINE max_output_detach = max_output.detach()NEWLINE # do other widths and resolutionNEWLINE min_width = FLAGS.width_mult_range[0]NEWLINE width_mult_list = [min_width]NEWLINE sampled_width = list(np.random.uniform(FLAGS.width_mult_range[0], FLAGS.width_mult_range[1], 2))NEWLINE width_mult_list.extend(sampled_width)NEWLINE for width_mult in sorted(width_mult_list, reverse=True):NEWLINE model.apply(NEWLINE lambda m: setattr(m, 'width_mult', width_mult))NEWLINE output = model(input_list[random.randint(0, 3)])NEWLINE loss = torch.nn.KLDivLoss(reduction='batchmean')(F.log_softmax(output, dim=1), F.softmax(max_output_detach, dim=1))NEWLINE loss.backward()NEWLINE optimizer.step()NEWLINE lr_scheduler.step()NEWLINE # print training logNEWLINE if batch_idx % FLAGS.print_freq == 0 or batch_idx == len(loader)-1:NEWLINE with torch.no_grad():NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE output = model(input_list[0])NEWLINE loss = criterion(output, target).cpu().numpy()NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc = (indices == target).sum().cpu().numpy() / indices.size()[0]NEWLINE logger.info('TRAIN {:.1f}s LR:{:.4f} {}x Epoch:{}/{} Iter:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, optimizer.param_groups[0]['lr'], str(width_mult), epoch,NEWLINE FLAGS.num_epochs, batch_idx, len(loader), loss, acc))NEWLINENEWLINENEWLINEdef validate(epoch, loader, model, criterion, postloader):NEWLINE t_start = time.time()NEWLINE model.eval()NEWLINE resolution = FLAGS.image_sizeNEWLINE with torch.no_grad():NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE model = ComputePostBN.ComputeBN(model, postloader, resolution)NEWLINE loss, acc, cnt = 0, 0, 0NEWLINE for batch_idx, (input, target) in enumerate(loader):NEWLINE input, target = input.cuda(non_blocking=True), target.cuda(non_blocking=True)NEWLINE output = model(input)NEWLINE loss += criterion(output, target).cpu().numpy() * target.size()[0]NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc += (indices == target).sum().cpu().numpy()NEWLINE cnt += target.size()[0]NEWLINE logger.info('VAL {:.1f}s {}x Epoch:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, str(width_mult), epoch,NEWLINE FLAGS.num_epochs, loss/cnt, acc/cnt))NEWLINENEWLINEdef test(epoch, loader, model, criterion, postloader):NEWLINE t_start = time.time()NEWLINE model.eval()NEWLINE with torch.no_grad():NEWLINE for resolution in FLAGS.resolution_list:NEWLINE for width_mult in sorted(FLAGS.width_mult_list, reverse=True):NEWLINE model.apply(lambda m: setattr(m, 'width_mult', width_mult))NEWLINE model = ComputePostBN.ComputeBN(model, postloader, resolution)NEWLINE loss, acc, cnt = 0, 0, 0NEWLINE for batch_idx, (input, target) in enumerate(loader):NEWLINE input, target =input.cuda(non_blocking=True), target.cuda(non_blocking=True)NEWLINE output = model(F.interpolate(input, (resolution, resolution), mode='bilinear', align_corners=True))NEWLINE loss += criterion(output, target).cpu().numpy() * target.size()[0]NEWLINE indices = torch.max(output, dim=1)[1]NEWLINE acc += (indices==target).sum().cpu().numpy()NEWLINE cnt += target.size()[0]NEWLINE logger.info('VAL {:.1f}s {}x-{} Epoch:{}/{} Loss:{:.4f} Acc:{:.3f}'.format(NEWLINE time.time() - t_start, str(width_mult), str(resolution), epoch,NEWLINE FLAGS.num_epochs, loss/cnt, acc/cnt))NEWLINENEWLINEdef train_val_test():NEWLINE """train and val"""NEWLINE # seedNEWLINE set_random_seed()NEWLINENEWLINE # modelNEWLINE model = get_model()NEWLINE model_wrapper = torch.nn.DataParallel(model).cuda()NEWLINE criterion = torch.nn.CrossEntropyLoss().cuda()NEWLINE train_loader, val_loader = get_dataset()NEWLINENEWLINE # check pretrainedNEWLINE if FLAGS.pretrained:NEWLINE checkpoint = torch.load(FLAGS.pretrained)NEWLINE # update keys from external modelsNEWLINE if type(checkpoint) == dict and 'model' in checkpoint:NEWLINE checkpoint = checkpoint['model']NEWLINE new_keys = list(model_wrapper.state_dict().keys())NEWLINE old_keys = list(checkpoint.keys())NEWLINE new_keys = [key for key in new_keys if 'running' not in key]NEWLINE new_keys = [key for key in new_keys if 'tracked' not in key]NEWLINE old_keys = [key for key in old_keys if 'running' not in key]NEWLINE old_keys = [key for key in old_keys if 'tracked' not in key]NEWLINE if not FLAGS.test_only:NEWLINE old_keys = old_keys[:-2]NEWLINE new_keys = new_keys[:-2]NEWLINENEWLINE new_checkpoint = {}NEWLINE for key_new, key_old in zip(new_keys, old_keys):NEWLINE new_checkpoint[key_new] = checkpoint[key_old]NEWLINE model_wrapper.load_state_dict(new_checkpoint, strict=False)NEWLINE print('Loaded model {}.'.format(FLAGS.pretrained))NEWLINE optimizer = get_optimizer(model_wrapper)NEWLINE # check resume trainingNEWLINE if FLAGS.resume:NEWLINE checkpoint = torch.load(FLAGS.resume)NEWLINE model_wrapper.load_state_dict(checkpoint['model'])NEWLINE optimizer.load_state_dict(checkpoint['optimizer'])NEWLINE last_epoch = checkpoint['last_epoch']NEWLINE lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*FLAGS.num_epochs)NEWLINE lr_scheduler.last_epoch = last_epochNEWLINE print('Loaded checkpoint {} at epoch {}.'.format(NEWLINE FLAGS.resume, last_epoch))NEWLINE else:NEWLINE lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*FLAGS.num_epochs)NEWLINE last_epoch = lr_scheduler.last_epochNEWLINE # print model and do profilingNEWLINE print(model_wrapper)NEWLINE if FLAGS.profiling:NEWLINE if 'gpu' in FLAGS.profiling:NEWLINE profiling(model, use_cuda=True)NEWLINE if 'cpu' in FLAGS.profiling:NEWLINE profiling(model, use_cuda=False)NEWLINENEWLINE if FLAGS.test_only:NEWLINE logger.info('Start testing.')NEWLINE test(last_epoch, val_loader, model_wrapper, criterion, train_loader)NEWLINE returnNEWLINENEWLINE logger.info('Start training.')NEWLINE for epoch in range(last_epoch + 1, FLAGS.num_epochs):NEWLINE # trainNEWLINE train(epoch, train_loader, model_wrapper, criterion, optimizer, lr_scheduler)NEWLINENEWLINE # valNEWLINE validate(epoch, val_loader, model_wrapper, criterion, train_loader)NEWLINENEWLINE # lr_scheduler.step()NEWLINE torch.save(NEWLINE {NEWLINE 'model': model_wrapper.state_dict(),NEWLINE 'optimizer': optimizer.state_dict(),NEWLINE 'last_epoch': epoch,NEWLINE },NEWLINE os.path.join(saved_path, 'checkpoint_{}.pt'.format(epoch)))NEWLINE returnNEWLINENEWLINENEWLINEdef main():NEWLINE """train and eval model"""NEWLINE train_val_test()NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE main()
import numpy as npNEWLINEimport copyNEWLINENEWLINEfrom . import ekf_utilsNEWLINENEWLINEgtrack_MIN_DISPERSION_ALPHA = 0.1NEWLINEgtrack_EST_POINTS = 10NEWLINEgtrack_MIN_POINTS_TO_UPDATE_DISPERSION = 3NEWLINEgtrack_KNOWN_TARGET_POINTS_THRESHOLD = 50NEWLINENEWLINENEWLINE# GTRACK Module calls this function to instantiate GTRACK Unit with desired configuration parameters. NEWLINE# Function returns a handle, which is used my module to call units' methodsNEWLINENEWLINEdef unit_create(params):NEWLINE inst = ekf_utils.GtrackUnitInstance()NEWLINENEWLINE inst.gatingParams = params.gatingParamsNEWLINE inst.stateParams = params.stateParamsNEWLINE inst.allocationParams = params.allocationParamsNEWLINE inst.unrollingParams = params.unrollingParamsNEWLINE inst.variationParams = params.variationParamsNEWLINE inst.sceneryParams = params.sceneryParamsNEWLINENEWLINE inst.uid = params.uidNEWLINE inst.maxAcceleration = params.maxAccelerationNEWLINE inst.maxRadialVelocity = params.maxRadialVelocityNEWLINE inst.radialVelocityResolution = params.radialVelocityResolutionNEWLINE inst.verbose = params.verboseNEWLINE inst.initialRadialVelocity = params.initialRadialVelocityNEWLINENEWLINE inst.F4 = params.F4NEWLINE inst.Q4 = params.Q4NEWLINE inst.F6 = params.F6NEWLINE inst.Q6 = params.Q6NEWLINENEWLINE if params.stateVectorType == ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DA:NEWLINE inst.stateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DANEWLINE inst.stateVectorLength = 6NEWLINE inst.measurementVectorLength = 3NEWLINE else:NEWLINE raise ValueError('not supported, unit_create')NEWLINENEWLINE inst.dt = params.deltaTNEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINENEWLINE return instNEWLINENEWLINENEWLINE# GTRACK Module calls this function to run GTRACK unit prediction step NEWLINEdef unit_predict(handle):NEWLINE inst = handleNEWLINE inst.heartBeatCount += 1NEWLINE temp1 = np.zeros(shape=(36,), dtype=np.float32)NEWLINE temp2 = np.zeros(shape=(36,), dtype=np.float32)NEWLINE temp3 = np.zeros(shape=(36,), dtype=np.float32)NEWLINENEWLINE # Current state vector lengthNEWLINE sLen = inst.stateVectorLengthNEWLINENEWLINE if inst.processVariance != 0:NEWLINE inst.S_apriori_hat = ekf_utils.gtrack_matrixMultiply(sLen, sLen, 1, inst.F, inst.S_hat)NEWLINE temp1 = ekf_utils.gtrack_matrixMultiply(6, 6, 6, inst.F, inst.P_hat)NEWLINE temp2 = ekf_utils.gtrack_matrixTransposeMultiply(6, 6, 6, temp1, inst.F)NEWLINE temp1 = ekf_utils.gtrack_matrixScalerMultiply(sLen, sLen, inst.Q, inst.processVariance)NEWLINE temp3 = ekf_utils.gtrack_matrixAdd(sLen, sLen, temp1, temp2)NEWLINENEWLINE inst.P_apriori_hat = ekf_utils.gtrack_matrixMakeSymmetrical(sLen, temp3)NEWLINE else:NEWLINE inst.S_apriori_hat = copy.deepcopy(inst.S_hat)NEWLINE inst.P_apriori_hat = copy.deepcopy(inst.P_hat)NEWLINENEWLINE ekf_utils.gtrack_cartesian2spherical(inst.stateVectorType, inst.S_apriori_hat, inst.H_s)NEWLINENEWLINENEWLINE# GTRACK Module calls this function to obtain the measurement vector scoring from the GTRACK unit perspectiveNEWLINEdef unit_score(handle, point, best_score, best_ind, num):NEWLINE limits = np.zeros(shape=(3,), dtype=np.float32)NEWLINE u_tilda = np.zeros(shape=(3,), dtype=np.float32)NEWLINENEWLINE inst = handleNEWLINENEWLINE limits[0] = inst.gatingParams.limits[0].lengthNEWLINE limits[1] = inst.gatingParams.limits[0].widthNEWLINE limits[2] = inst.gatingParams.limits[0].velNEWLINENEWLINE if inst.processVariance == 0:NEWLINE inst.G = 1NEWLINE else:NEWLINE inst.G = ekf_utils.gtrack_gateCreateLim(inst.gatingParams.volume, inst.gC_inv, inst.H_s[0], limits)NEWLINENEWLINE det = ekf_utils.gtrack_matrixDet3(inst.gC)NEWLINENEWLINE log_det = np.float32(np.log(det))NEWLINENEWLINE for n in range(num):NEWLINE if best_ind[n] == ekf_utils.gtrack_ID_POINT_BEHIND_THE_WALL:NEWLINE continueNEWLINENEWLINE u_tilda[0] = np.float32(point[n].range - inst.H_s[0])NEWLINE u_tilda[1] = np.float32(point[n].angle - inst.H_s[1])NEWLINENEWLINE if inst.velocityHandling < ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:NEWLINE # Radial velocity estimation is not yet known, unroll based on velocity measured at allocation timeNEWLINE rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.allocationVelocity,NEWLINE point[n].doppler)NEWLINE u_tilda[2] = np.float32(rv_out - inst.allocationVelocity)NEWLINE else:NEWLINE # Radial velocity estimation is known NEWLINE rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], point[n].doppler)NEWLINE u_tilda[2] = np.float32(rv_out - inst.H_s[2])NEWLINENEWLINE chi2 = ekf_utils.gtrack_computeMahalanobis3(u_tilda, inst.gC_inv)NEWLINE # print(inst.gC_inv)NEWLINENEWLINE if chi2 < inst.G:NEWLINE score = np.float32(log_det + chi2)NEWLINE if score < best_score[n]:NEWLINE best_score[n] = scoreNEWLINE best_ind[n] = np.uint8(inst.uid)NEWLINE point[n].doppler = rv_outNEWLINENEWLINENEWLINE# GTRACK Module calls this function to start target tracking. This function is called during modules' allocation step,NEWLINE# once new set of points passes allocation thresholds NEWLINEdef unit_start(handle, time_stamp, tid, um):NEWLINE inst = handleNEWLINENEWLINE m = np.zeros(shape=(3,), dtype=np.float32)NEWLINENEWLINE inst.tid = tidNEWLINE inst.heartBeatCount = time_stampNEWLINE inst.allocationTime = time_stampNEWLINE inst.allocationRange = um[0]NEWLINE inst.allocationVelocity = um[2]NEWLINE inst.associatedPoints = 0NEWLINENEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_DETECTIONNEWLINE inst.currentStateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DANEWLINE inst.stateVectorLength = 6NEWLINENEWLINE inst.processVariance = (0.5 * inst.maxAcceleration) * (0.5 * inst.maxAcceleration)NEWLINENEWLINE inst.F = inst.F6NEWLINE inst.Q = inst.Q6NEWLINENEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_INITNEWLINENEWLINE m[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.initialRadialVelocity, um[2])NEWLINENEWLINE inst.rangeRate = m[2]NEWLINENEWLINE m[0] = um[0]NEWLINE m[1] = um[1]NEWLINENEWLINE ekf_utils.gtrack_spherical2cartesian(inst.currentStateVectorType, m, inst.S_apriori_hat)NEWLINE inst.H_s = copy.deepcopy(m)NEWLINENEWLINE inst.P_apriori_hat = copy.deepcopy(ekf_utils.pinit6x6)NEWLINE inst.gD = copy.deepcopy(ekf_utils.zero3x3)NEWLINE inst.G = 1.NEWLINENEWLINENEWLINE# GTRACK Module calls this function to perform an update step for the tracking unit. NEWLINEdef unit_update(handle, point, var, pInd, num):NEWLINE J = np.zeros(shape=(18,), dtype=np.float32) # 3x6NEWLINE PJ = np.zeros(shape=(18,), dtype=np.float32) # 6x3NEWLINE JPJ = np.zeros(shape=(9,), dtype=np.float32) # 3x3NEWLINE U = np.zeros(shape=(3,), dtype=np.float32)NEWLINE u_tilda = np.zeros(shape=(3,), dtype=np.float32)NEWLINE cC = np.zeros(shape=(9,), dtype=np.float32)NEWLINE cC_inv = np.zeros(shape=(9,), dtype=np.float32)NEWLINE K = np.zeros(shape=(18,), dtype=np.float32) # 6x3NEWLINENEWLINE u_mean = ekf_utils.gtrack_measurementPoint()NEWLINENEWLINE D = np.zeros(shape=(9,), dtype=np.float32)NEWLINE Rm = np.zeros(shape=(9,), dtype=np.float32)NEWLINE Rc = np.zeros(shape=(9,), dtype=np.float32)NEWLINENEWLINE temp1 = np.zeros(shape=(36,), dtype=np.float32)NEWLINENEWLINE inst = handleNEWLINE mlen = inst.measurementVectorLengthNEWLINE slen = inst.stateVectorLengthNEWLINENEWLINE myPointNum = 0NEWLINENEWLINE for n in range(num):NEWLINE if pInd[n] == inst.uid:NEWLINE myPointNum += 1NEWLINE u_mean.range += point[n].rangeNEWLINE u_mean.angle += point[n].angleNEWLINENEWLINE if var != None:NEWLINE Rm[0] += var[n].rangeVarNEWLINE Rm[4] += var[n].angleVarNEWLINE Rm[8] += var[n].dopplerVarNEWLINENEWLINE if myPointNum == 1:NEWLINE rvPilot = point[n].dopplerNEWLINE u_mean.doppler = rvPilotNEWLINE else:NEWLINE rvCurrent = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, rvPilot, point[n].doppler)NEWLINE point[n].doppler = rvCurrentNEWLINE u_mean.doppler += rvCurrentNEWLINENEWLINE if myPointNum == 0:NEWLINE # INACTIVENEWLINE if (np.abs(inst.S_hat[2]) < inst.radialVelocityResolution) and \NEWLINE (np.abs(inst.S_hat[3]) < inst.radialVelocityResolution):NEWLINE inst.S_hat = np.zeros(shape=(inst.S_hat.shape), dtype=np.float32)NEWLINENEWLINE inst.S_hat[0] = inst.S_apriori_hat[0]NEWLINE inst.S_hat[1] = inst.S_apriori_hat[1]NEWLINENEWLINE inst.P_hat = copy.deepcopy(inst.P_apriori_hat)NEWLINENEWLINE inst.processVariance = 0NEWLINE else:NEWLINE inst.S_hat = copy.deepcopy(inst.S_apriori_hat)NEWLINE inst.P_hat = copy.deepcopy(inst.P_apriori_hat)NEWLINENEWLINE unit_event(inst, myPointNum)NEWLINE return inst.stateNEWLINENEWLINE inst.associatedPoints += myPointNumNEWLINENEWLINE if inst.processVariance == 0:NEWLINE inst.processVariance = np.float32((0.5 * (inst.maxAcceleration)) * (0.5 * (inst.maxAcceleration)))NEWLINENEWLINE u_mean.range = np.float32(u_mean.range / myPointNum)NEWLINE u_mean.angle = np.float32(u_mean.angle / myPointNum)NEWLINE u_mean.doppler = np.float32(u_mean.doppler / myPointNum)NEWLINENEWLINE if var != None:NEWLINE Rm[0] = np.float32(Rm[0] / myPointNum)NEWLINE Rm[4] = np.float32(Rm[4] / myPointNum)NEWLINE Rm[8] = np.float32(Rm[8] / myPointNum)NEWLINE else:NEWLINE dRangeVar = np.float32((inst.variationParams.lengthStd) * (inst.variationParams.lengthStd))NEWLINE dDopplerVar = np.float32((inst.variationParams.dopplerStd) * (inst.variationParams.dopplerStd))NEWLINENEWLINE Rm[0] = dRangeVarNEWLINE angleStd = np.float32(2 * np.float32(np.arctan(0.5 * (inst.variationParams.widthStd) / inst.H_s[0])))NEWLINE Rm[4] = angleStd * angleStdNEWLINE Rm[8] = dDopplerVarNEWLINENEWLINE U[0] = u_mean.rangeNEWLINE U[1] = u_mean.angleNEWLINE U[2] = u_mean.dopplerNEWLINENEWLINE velocity_state_handling(inst, U)NEWLINENEWLINE if myPointNum > gtrack_MIN_POINTS_TO_UPDATE_DISPERSION:NEWLINE for n in range(num):NEWLINE if pInd[n] == inst.uid:NEWLINE D[0] += np.float32((point[n].range - u_mean.range) * (point[n].range - u_mean.range))NEWLINE D[4] += np.float32((point[n].angle - u_mean.angle) * (point[n].angle - u_mean.angle))NEWLINE D[8] += np.float32((point[n].doppler - u_mean.doppler) * (point[n].doppler - u_mean.doppler))NEWLINE D[1] += np.float32((point[n].range - u_mean.range) * (point[n].angle - u_mean.angle))NEWLINE D[2] += np.float32((point[n].range - u_mean.range) * (point[n].doppler - u_mean.doppler))NEWLINE D[5] += np.float32((point[n].angle - u_mean.angle) * (point[n].doppler - u_mean.doppler))NEWLINENEWLINE D[0] = np.float32(D[0] / myPointNum)NEWLINE D[4] = np.float32(D[4] / myPointNum)NEWLINE D[8] = np.float32(D[8] / myPointNum)NEWLINE D[1] = np.float32(D[1] / myPointNum)NEWLINE D[2] = np.float32(D[2] / myPointNum)NEWLINE D[5] = np.float32(D[5] / myPointNum)NEWLINENEWLINE alpha = np.float32(myPointNum / (inst.associatedPoints))NEWLINE # print(alpha)NEWLINE if alpha < gtrack_MIN_DISPERSION_ALPHA:NEWLINE alpha = gtrack_MIN_DISPERSION_ALPHANEWLINENEWLINE inst.gD[0] = np.float32((1. - alpha) * inst.gD[0] + alpha * D[0])NEWLINE inst.gD[1] = np.float32((1. - alpha) * inst.gD[1] + alpha * D[1])NEWLINE inst.gD[2] = np.float32((1. - alpha) * inst.gD[2] + alpha * D[2])NEWLINE inst.gD[3] = np.float32(inst.gD[1])NEWLINE inst.gD[4] = np.float32((1. - alpha) * inst.gD[4] + alpha * D[4])NEWLINE inst.gD[5] = np.float32((1. - alpha) * inst.gD[5] + alpha * D[5])NEWLINE inst.gD[6] = np.float32(inst.gD[2])NEWLINE inst.gD[7] = np.float32(inst.gD[5])NEWLINE inst.gD[8] = np.float32((1. - alpha) * inst.gD[8] + alpha * D[8])NEWLINENEWLINE if myPointNum > gtrack_EST_POINTS:NEWLINE alpha = 0NEWLINE else:NEWLINE alpha = np.float32((gtrack_EST_POINTS - myPointNum) / ((gtrack_EST_POINTS - 1) * myPointNum))NEWLINENEWLINE Rc[0] = np.float32((Rm[0] / myPointNum) + alpha * (inst.gD[0]))NEWLINE Rc[4] = np.float32((Rm[4] / myPointNum) + alpha * (inst.gD[4]))NEWLINE Rc[8] = np.float32((Rm[8] / myPointNum) + alpha * (inst.gD[8]))NEWLINENEWLINE ekf_utils.gtrack_computeJacobian(inst.currentStateVectorType, inst.S_apriori_hat, J)NEWLINENEWLINE u_tilda = ekf_utils.gtrack_matrixSub(mlen, 1, U, inst.H_s)NEWLINE PJ = ekf_utils.gtrack_matrixComputePJT(inst.P_apriori_hat, J)NEWLINE JPJ = ekf_utils.gtrack_matrixMultiply(mlen, slen, mlen, J, PJ)NEWLINE cC = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rc)NEWLINENEWLINE cC_inv = ekf_utils.gtrack_matrixInv3(cC)NEWLINENEWLINE K = ekf_utils.gtrack_matrixMultiply(slen, mlen, mlen, PJ, cC_inv)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixMultiply(slen, mlen, 1, K, u_tilda)NEWLINE inst.S_hat = ekf_utils.gtrack_matrixAdd(slen, 1, inst.S_apriori_hat, temp1)NEWLINE # print(temp1)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixTransposeMultiply(slen, mlen, slen, K, PJ)NEWLINE inst.P_hat = ekf_utils.gtrack_matrixSub(slen, slen, inst.P_apriori_hat, temp1)NEWLINENEWLINE temp1 = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rm)NEWLINE inst.gC = ekf_utils.gtrack_matrixAdd(mlen, mlen, temp1, inst.gD)NEWLINENEWLINE inst.gC_inv = ekf_utils.gtrack_matrixInv3(inst.gC)NEWLINENEWLINE unit_event(inst, myPointNum)NEWLINE return inst.stateNEWLINENEWLINENEWLINE# this is the helper function for GTRACK unit updateNEWLINEdef velocity_state_handling(handle, um):NEWLINE inst = handleNEWLINE rvIn = um[2]NEWLINE # print(inst.velocityHandling)NEWLINENEWLINE if inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_INIT:NEWLINE um[2] = inst.rangeRateNEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTERNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTER:NEWLINE instanteneousRangeRate = np.float32(NEWLINE (um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * (inst.dt)))NEWLINE inst.rangeRate = np.float32((inst.unrollingParams.alpha) * (inst.rangeRate) + (NEWLINE 1 - (inst.unrollingParams.alpha)) * instanteneousRangeRate)NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)NEWLINENEWLINE rrError = np.float32((instanteneousRangeRate - inst.rangeRate) / inst.rangeRate)NEWLINENEWLINE if np.abs(rrError) < inst.unrollingParams.confidence:NEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_TRACKINGNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_TRACKING:NEWLINE instanteneousRangeRate = np.float32(NEWLINE (um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * inst.dt))NEWLINENEWLINE inst.rangeRate = np.float32(NEWLINE (inst.unrollingParams.alpha) * inst.rangeRate + (1 - inst.unrollingParams.alpha) * instanteneousRangeRate)NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)NEWLINE rvError = np.float32((inst.H_s[2] - um[2]) / um[2])NEWLINE if np.abs(rvError) < 0.1:NEWLINE inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_LOCKEDNEWLINE elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:NEWLINE um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], um[2])NEWLINENEWLINENEWLINE# GTRACK Module calls this function to run GTRACK unit level state machineNEWLINEdef unit_event(handle, num):NEWLINE inst = handleNEWLINENEWLINE if inst.state == ekf_utils.TrackState().TRACK_STATE_DETECTION:NEWLINE if num > inst.allocationParams.pointsThre:NEWLINE inst.detect2freeCount = 0NEWLINE inst.detect2activeCount += 1NEWLINE if inst.detect2activeCount > inst.stateParams.det2actThre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_ACTIVENEWLINE else:NEWLINE if num == 0:NEWLINE inst.detect2freeCount += 1NEWLINE if inst.detect2activeCount > 0:NEWLINE inst.detect2activeCount -= 1NEWLINE if inst.detect2freeCount > inst.stateParams.det2freeThre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINE elif inst.state == ekf_utils.TrackState().TRACK_STATE_ACTIVE:NEWLINE if num != 0:NEWLINE inst.active2freeCount = 0NEWLINE else:NEWLINE inst.active2freeCount += 1NEWLINENEWLINE if inst.sceneryParams.numStaticBoxes != 0:NEWLINE thre = inst.stateParams.exit2freeThreNEWLINE for numBoxes in range(inst.sceneryParams.numStaticBoxes):NEWLINE if ekf_utils.isPointInsideBox(inst.S_hat[0], inst.S_hat[1],NEWLINE inst.sceneryParams.boundaryBox[numBoxes]) == 1:NEWLINE if inst.processVariance == 0:NEWLINE thre = inst.stateParams.static2freeThreNEWLINE else:NEWLINE thre = inst.stateParams.active2freeThreNEWLINE breakNEWLINE else:NEWLINE thre = inst.stateParams.active2freeThreNEWLINENEWLINE if thre > inst.heartBeatCount:NEWLINE thre = np.uint16(inst.heartBeatCount)NEWLINENEWLINE if inst.active2freeCount > thre:NEWLINE inst.state = ekf_utils.TrackState().TRACK_STATE_FREENEWLINENEWLINENEWLINE# GTRACK Module calls this function to report GTRACK unit results to the target descriptorNEWLINEdef unit_report(handle, target):NEWLINE inst = handleNEWLINENEWLINE target.uid = inst.uidNEWLINE target.tid = inst.tidNEWLINENEWLINE target.S = copy.deepcopy(inst.S_hat)NEWLINE target.EC = copy.deepcopy(inst.gC_inv)NEWLINE target.G = inst.GNEWLINE
#!/usr/bin/env python3NEWLINE# -*- coding: utf-8 -*-NEWLINENEWLINEfrom .effect import ShortEffectLayer, LongEffectLayer, LongEffectAllRangeLayerNEWLINEfrom .combine import CombineLayerNEWLINENEWLINE__author__ = 'Yasuhiro'NEWLINE__date__ = '2018/2/15'NEWLINE
import osNEWLINEimport win32security,win32file,win32api,ntsecuritycon,win32conNEWLINEfrom security_enums import TRUSTEE_TYPE,TRUSTEE_FORM,ACE_FLAGS,ACCESS_MODENEWLINENEWLINEfname = os.path.join(win32api.GetTempPath(), "win32security_test.txt")NEWLINEf=open(fname, "w")NEWLINEf.write("Hello from Python\n");NEWLINEf.close()NEWLINEprint "Testing on file", fnameNEWLINENEWLINEnew_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SECURITY_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SHUTDOWN_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_TAKE_OWNERSHIP_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_CREATE_PERMANENT_NAME),win32con.SE_PRIVILEGE_ENABLED),NEWLINE (win32security.LookupPrivilegeValue('','SeEnableDelegationPrivilege'),win32con.SE_PRIVILEGE_ENABLED) ##doesn't seem to be in ntsecuritycon.py ?NEWLINE )NEWLINENEWLINEph = win32api.GetCurrentProcess()NEWLINEth = win32security.OpenProcessToken(ph,win32security.TOKEN_ALL_ACCESS) ##win32con.TOKEN_ADJUST_PRIVILEGES)NEWLINEwin32security.AdjustTokenPrivileges(th,0,new_privs)NEWLINENEWLINEall_security_info = \NEWLINE win32security.OWNER_SECURITY_INFORMATION|win32security.GROUP_SECURITY_INFORMATION| \NEWLINE win32security.DACL_SECURITY_INFORMATION|win32security.SACL_SECURITY_INFORMATIONNEWLINENEWLINEsd=win32security.GetFileSecurity(fname,all_security_info)NEWLINENEWLINEold_sacl=sd.GetSecurityDescriptorSacl()NEWLINEif old_sacl==None:NEWLINE old_sacl=win32security.ACL()NEWLINEold_dacl=sd.GetSecurityDescriptorDacl()NEWLINEif old_dacl==None:NEWLINE old_dacl=win32security.ACL()NEWLINENEWLINEmy_sid = win32security.GetTokenInformation(th,ntsecuritycon.TokenUser)[0]NEWLINEtmp_sid = win32security.LookupAccountName('','tmp')[0]NEWLINEpwr_sid = win32security.LookupAccountName('','Power Users')[0]NEWLINENEWLINENEWLINE## MultipleTrustee,MultipleTrusteeOperation,TrusteeForm,TrusteeType,IdentifierNEWLINE## first two are ignoredNEWLINEmy_trustee = {}NEWLINEmy_trustee['MultipleTrustee']=NoneNEWLINEmy_trustee['MultipleTrusteeOperation']=0NEWLINEmy_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_SIDNEWLINEmy_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEmy_trustee['Identifier']=my_sidNEWLINENEWLINEtmp_trustee = {}NEWLINEtmp_trustee['MultipleTrustee']=NoneNEWLINEtmp_trustee['MultipleTrusteeOperation']=0NEWLINEtmp_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_NAMENEWLINEtmp_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEtmp_trustee['Identifier']='rupole\\tmp'NEWLINENEWLINEpwr_trustee = {}NEWLINEpwr_trustee['MultipleTrustee']=NoneNEWLINEpwr_trustee['MultipleTrusteeOperation']=0NEWLINEpwr_trustee['TrusteeForm']=TRUSTEE_FORM.TRUSTEE_IS_SIDNEWLINEpwr_trustee['TrusteeType']=TRUSTEE_TYPE.TRUSTEE_IS_USERNEWLINEpwr_trustee['Identifier']=pwr_sidNEWLINENEWLINEexpl_list=[]NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_SUCCESS, ##|ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_SUCCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.SET_AUDIT_FAILURE,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINEold_sacl.SetEntriesInAcl(expl_list)NEWLINENEWLINEexpl_list=[]NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.DENY_ACCESS,NEWLINE 'AccessPermissions':win32con.DELETENEWLINE }NEWLINE )NEWLINENEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':tmp_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.WRITE_OWNERNEWLINE }NEWLINE )NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':pwr_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_READNEWLINE }NEWLINE )NEWLINEexpl_list.append(NEWLINE {NEWLINE 'Trustee':my_trustee,NEWLINE 'Inheritance':ACE_FLAGS.NO_INHERITANCE,NEWLINE 'AccessMode':ACCESS_MODE.GRANT_ACCESS,NEWLINE 'AccessPermissions':win32con.GENERIC_ALLNEWLINE }NEWLINE )NEWLINENEWLINEold_dacl.SetEntriesInAcl(expl_list)NEWLINEsd.SetSecurityDescriptorSacl(1,old_sacl,1)NEWLINEsd.SetSecurityDescriptorDacl(1,old_dacl,1)NEWLINEsd.SetSecurityDescriptorOwner(pwr_sid,1)NEWLINENEWLINEwin32security.SetFileSecurity(fname,NEWLINE all_security_info,NEWLINE sd)NEWLINE
import numpy as npNEWLINENEWLINEfrom collections import deque, IterableNEWLINEimport sigvisa.infer.optimize.optim_utils as optim_utilsNEWLINENEWLINEclass CyclicGraphError(Exception):NEWLINE passNEWLINENEWLINENEWLINEclass DAG(object):NEWLINENEWLINE """NEWLINE Represents a directed acyclic graph.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, toplevel_nodes=None, leaf_nodes=None):NEWLINE self.toplevel_nodes = set(toplevel_nodes) if toplevel_nodes is not None else set()NEWLINE self.leaf_nodes = set(leaf_nodes) if leaf_nodes is not None else set()NEWLINENEWLINE # invariant: self._topo_sorted_list should always be a topologically sorted list of nodesNEWLINE self._topo_sort()NEWLINENEWLINE def __ts_visit(self, node):NEWLINE m = node.get_mark()NEWLINE if m == 2:NEWLINE raise CyclicGraphError("graph contains a cycle!")NEWLINE elif m == 0:NEWLINE node.set_mark(2) # visit node "temporarily"NEWLINE for pn in node.parents.values():NEWLINE self.__ts_visit(pn)NEWLINE node.set_mark(1)NEWLINE node._topo_sorted_list_index = len(self._topo_sorted_list)NEWLINE self._topo_sorted_list.append(node)NEWLINENEWLINE def _topo_sort(self):NEWLINE # check graph invariantsNEWLINE for tn in self.toplevel_nodes:NEWLINE assert(len(tn.parents) == 0)NEWLINE for ln in self.leaf_nodes:NEWLINE assert(len(ln.children) == 0)NEWLINENEWLINE self._topo_sorted_list = []NEWLINE for leaf in self.leaf_nodes:NEWLINE self.__ts_visit(leaf)NEWLINE self.clear_visited()NEWLINENEWLINENEWLINE # allow fast removing of nodes by setting their entries to NoneNEWLINE def _gc_topo_sorted_nodes(self):NEWLINE tsl = [n for n in self._topo_sorted_list if n is not None]NEWLINE for (i, n) in enumerate(tsl):NEWLINE n._topo_sorted_list_index = iNEWLINE self._topo_sorted_list = tslNEWLINENEWLINE def topo_sorted_nodes(self):NEWLINE self._gc_topo_sorted_nodes()NEWLINE return self._topo_sorted_listNEWLINENEWLINE def clear_visited(self):NEWLINE q = deque(self.toplevel_nodes)NEWLINE while len(q) > 0:NEWLINE node = q.pop()NEWLINE node.clear_mark()NEWLINE q.extendleft(node.children)NEWLINENEWLINENEWLINE def topo_sorted_nodes(self):NEWLINE self._gc_topo_sorted_nodes()NEWLINE assert(len(self._topo_sorted_list) == len(self.all_nodes))NEWLINE return self._topo_sorted_listNEWLINENEWLINE def recover_parents_from_children(self):NEWLINE for node in self.topo_sorted_nodes():NEWLINE for child in node.children:NEWLINE child.addParent(node, stealth=True)NEWLINENEWLINEdef get_relevant_nodes(node_list, exclude_nodes=None):NEWLINE # note, it's important that the nodes have a consistent order, sinceNEWLINE # we represent their joint values as a vector.NEWLINENEWLINE parents_of_deterministic = [node.parents[node.default_parent_key()] for node in node_list if node.deterministic()]NEWLINE node_list = [node for node in node_list if not node.deterministic()]NEWLINENEWLINE nlset = set(node_list + parents_of_deterministic)NEWLINE all_stochastic_children = [child for node in nlset for (child, intermediates) in node.get_stochastic_children()]NEWLINE relevant_nodes = set(node_list + all_stochastic_children + parents_of_deterministic)NEWLINE if exclude_nodes:NEWLINE for n in exclude_nodes:NEWLINE relevant_nodes.remove(n)NEWLINENEWLINE return node_list, relevant_nodesNEWLINENEWLINENEWLINEclass ParentConditionalNotDefined(Exception):NEWLINE passNEWLINENEWLINEclass DirectedGraphModel(DAG):NEWLINENEWLINE """NEWLINE A directed graphical probability model.NEWLINENEWLINE """NEWLINENEWLINE def __init__(self, **kwargs):NEWLINE super(DirectedGraphModel, self).__init__(**kwargs)NEWLINENEWLINE self.all_nodes = dict()NEWLINE self.nodes_by_key = dict()NEWLINENEWLINENEWLINE def add_children(n):NEWLINE if n.label not in self.all_nodes:NEWLINE self.add_node(n)NEWLINE for c in n.children:NEWLINE add_children(c)NEWLINENEWLINE if self.toplevel_nodes is not None:NEWLINE for n in self.toplevel_nodes:NEWLINE add_children(n)NEWLINENEWLINE def current_log_p(self, verbose=False):NEWLINE logp = 0NEWLINE for node in self.topo_sorted_nodes():NEWLINE if node.deterministic(): continueNEWLINENEWLINE try:NEWLINE lp = node.log_p()NEWLINE except ParentConditionalNotDefined:NEWLINE lp = node.upwards_message_normalizer()NEWLINENEWLINE if verbose:NEWLINE print "node %s has logp %.1f" % (node.label, lp)NEWLINE logp += lpNEWLINE return logpNEWLINENEWLINE def parent_predict_all(self):NEWLINE for node in self.topo_sorted_nodes():NEWLINE if not node._fixed:NEWLINE node.parent_predict()NEWLINENEWLINE def parent_sample_all(self):NEWLINE for node in self.topo_sorted_nodes():NEWLINE if not node._fixed:NEWLINE node.parent_sample()NEWLINENEWLINE def get_all(self, node_list):NEWLINE return np.concatenate([node.get_mutable_values() for node in node_list if not node.deterministic()])NEWLINENEWLINE def set_all(self, values, node_list):NEWLINE i = 0NEWLINE for node in node_list:NEWLINE if node.deterministic(): continueNEWLINE n = node.mutable_dimension()NEWLINE node.set_mutable_values(values[i:i+n])NEWLINE i += nNEWLINENEWLINE for dn in node.get_deterministic_children():NEWLINE dn.parent_predict()NEWLINENEWLINENEWLINE def joint_logprob(self, values, node_list, relevant_nodes, proxy_lps=None, c=1):NEWLINE # node_list: list of nodes whose values we are interested inNEWLINENEWLINE # relevant_nodes: all nodes whose log_p() depends on a valueNEWLINE # from a node in node_list.NEWLINENEWLINE #v = self.get_all(node_list = node_list)NEWLINE if values is not None:NEWLINE self.set_all(values=values, node_list=node_list)NEWLINENEWLINE joint_factors = set()NEWLINE if proxy_lps is not None:NEWLINE ll = np.sum([f() for (f, df) in proxy_lps.values()])NEWLINE ll += np.sum([node.log_p() for node in relevant_nodes if node.label not in proxy_lps.keys()])NEWLINE else:NEWLINE ll = 0NEWLINE for node in relevant_nodes:NEWLINE if len(node.params_modeled_jointly)==0:NEWLINE ll += node.log_p()NEWLINE else:NEWLINE ll += node.upwards_message_normalizer()NEWLINE joint_factors = joint_factors | node.params_modeled_jointlyNEWLINENEWLINE for jf in joint_factors:NEWLINE ll += jf.log_likelihood()NEWLINENEWLINENEWLINE return c * llNEWLINENEWLINE def joint_logprob_keys(self, relevant_nodes, keys=None, values=None, node_list=None, proxy_lps=None, c=1):NEWLINE # same as joint_logprob, but we specify values only for aNEWLINE # specific set of keys.NEWLINE # here, node_list contains one entry for each key (so willNEWLINE # have duplicates if we have multiple keys from the same node)NEWLINE if keys is not None:NEWLINE for (key, val, n) in zip(keys, values, node_list):NEWLINE n.set_value(key=key, value=val)NEWLINENEWLINENEWLINE joint_factors = set()NEWLINE if proxy_lps is not None:NEWLINE ll = np.sum([f() for (f, df) in proxy_lps.values()])NEWLINE ll += np.sum([node.log_p() for node in relevant_nodes if node.label not in proxy_lps.keys()])NEWLINE else:NEWLINE ll = 0NEWLINE for node in relevant_nodes:NEWLINE if len(node.params_modeled_jointly)==0:NEWLINE ll += node.log_p()NEWLINE else:NEWLINE ll += node.upwards_message_normalizer()NEWLINE joint_factors = joint_factors | node.params_modeled_jointlyNEWLINENEWLINE for jf in joint_factors:NEWLINE ll += jf.log_likelihood()NEWLINENEWLINE return c * llNEWLINENEWLINENEWLINE def log_p_grad(self, values, node_list, relevant_nodes, proxy_lps=None, eps=1e-4, c=1.0):NEWLINE try:NEWLINE eps0 = eps[0]NEWLINE except:NEWLINE eps = (eps,) * len(values)NEWLINENEWLINE proxy_lps = proxy_lps if proxy_lps is not None else {}NEWLINENEWLINE v = self.get_all(node_list = node_list)NEWLINE self.set_all(values=values, node_list=node_list)NEWLINE initial_lp = dict([(node.label, node.log_p() if node.label not in proxy_lps else proxy_lps[node.label][0]()) for node in relevant_nodes])NEWLINE grad = np.zeros((len(values),))NEWLINE i = 0NEWLINE for node in node_list:NEWLINE keys = node.mutable_keys()NEWLINE for (ni, key) in enumerate(keys):NEWLINE if node.label in proxy_lps:NEWLINE deriv = proxy_lps[node.label][1](key=key, eps=eps[i + ni], lp0=initial_lp[node.label])NEWLINE else:NEWLINE deriv = node.deriv_log_p(key=key, eps=eps[i + ni], lp0=initial_lp[node.label])NEWLINENEWLINE # sum the derivatives of all child nodes wrt to this value, includingNEWLINE # any deterministic nodes along the wayNEWLINE child_list = node.get_stochastic_children()NEWLINE for (child, intermediate_nodes) in child_list:NEWLINE current_key = keyNEWLINE d = 1.0NEWLINE for inode in intermediate_nodes:NEWLINE d *= inode.deriv_value_wrt_parent(parent_key = current_key)NEWLINE current_key = inode.labelNEWLINENEWLINE if child.label in proxy_lps:NEWLINE d *= proxy_lps[child.label][1](parent_key = current_key,NEWLINE eps=eps[i + ni],NEWLINE lp0=initial_lp[child.label])NEWLINE else:NEWLINE d *= child.deriv_log_p(parent_key = current_key,NEWLINE eps=eps[i + ni],NEWLINE lp0=initial_lp[child.label])NEWLINE deriv += dNEWLINENEWLINE grad[i + ni] = derivNEWLINE i += len(keys)NEWLINE self.set_all(values=v, node_list=node_list)NEWLINE return grad * cNEWLINENEWLINE def joint_optimize_nodes(self, node_list, optim_params, proxy_lps=None, use_grad=True):NEWLINE """NEWLINE Assume that the value at each node is a 1D array.NEWLINE """NEWLINE node_list, relevant_nodes = get_relevant_nodes(node_list)NEWLINENEWLINE start_values = self.get_all(node_list=node_list)NEWLINE low_bounds = np.concatenate([node.low_bounds() for node in node_list])NEWLINE high_bounds = np.concatenate([node.high_bounds() for node in node_list])NEWLINE #bounds = zip(low_bounds, high_bounds)NEWLINE bounds = NoneNEWLINENEWLINE jp = lambda v: self.joint_logprob(values=v, relevant_nodes=relevant_nodes, node_list=node_list, proxy_lps=proxy_lps, c=-1)NEWLINENEWLINE # this is included for profiling / debugging -- not real codeNEWLINE def time_joint_logprob():NEWLINE import timeNEWLINE st = time.time()NEWLINE for i in range(500):NEWLINE joint_logprob(start_values, relevant_nodes=relevant_nodes, proxy_lps=proxy_lps, c=-1)NEWLINE et = time.time()NEWLINE print "joint prob took %.3fs on average" % ((et-st)/500.0)NEWLINENEWLINE if use_grad:NEWLINE g = lambda v, eps=1e-4: self.log_p_grad(values=v, node_list=node_list, relevant_nodes=relevant_nodes, proxy_lps=proxy_lps, c=-1, eps=eps)NEWLINE else:NEWLINE g = NoneNEWLINENEWLINE result_vector, cost = optim_utils.minimize(f=jp, x0=start_values, fprime=g, optim_params=optim_params, bounds=bounds)NEWLINE self.set_all(values=result_vector, node_list=node_list)NEWLINE print "got optimized x", result_vectorNEWLINENEWLINENEWLINE def remove_node(self, node):NEWLINE del self.all_nodes[node.label]NEWLINE for key in node.keys():NEWLINE del self.nodes_by_key[key]NEWLINENEWLINE self.toplevel_nodes.discard(node)NEWLINE self.leaf_nodes.discard(node)NEWLINENEWLINE for child in node.children:NEWLINE child.removeParent(node)NEWLINE if len(child.parents) == 0:NEWLINE self.toplevel_nodes.add(child)NEWLINENEWLINE for parent in set(node.parents.values()):NEWLINE parent.removeChild(node)NEWLINE if len(parent.children) == 0:NEWLINE self.leaf_nodes.add(parent)NEWLINENEWLINENEWLINE def add_node(self, node):NEWLINE if node.label in self.all_nodes:NEWLINE raise ValueError("adding node '%s' to the graph, but a node with this label already exists!" % node.label)NEWLINE self.all_nodes[node.label] = nodeNEWLINE for key in node.keys():NEWLINE self.nodes_by_key[key] = nodeNEWLINE if len(node.children) == 0:NEWLINE self.leaf_nodes.add(node)NEWLINE if len(node.parents) == 0:NEWLINE self.toplevel_nodes.add(node)NEWLINE for child in node.children:NEWLINE self.toplevel_nodes.discard(child)NEWLINE for parent in node.parents.values():NEWLINE self.leaf_nodes.discard(parent)NEWLINENEWLINENEWLINE def get_node_from_key(self, key):NEWLINE return self.nodes_by_key[key]NEWLINENEWLINE def set_value(self, key, value, **kwargs):NEWLINE n = self.nodes_by_key[key]NEWLINE n.set_value(value=value, key=key, **kwargs)NEWLINENEWLINE def get_value(self, key):NEWLINE n = self.nodes_by_key[key]NEWLINE return n.get_value(key=key)NEWLINENEWLINE def save_graphviz(self, fname):NEWLINE f = open(fname, 'w')NEWLINE f.write("digraph G {\n")NEWLINE f.write("size =\"10,10\";")NEWLINENEWLINE for node in self.topo_sorted_nodes():NEWLINE for child in node.children:NEWLINE f.write("\"%s\" -> \"%s\";\n" % (node.label, child.label))NEWLINENEWLINE f.write("}\n")NEWLINE f.close()NEWLINE
# coding: utf-8NEWLINENEWLINE"""NEWLINE FlashBlade REST APINEWLINENEWLINE A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/).NEWLINENEWLINE OpenAPI spec version: 2.3NEWLINE NEWLINE Generated by: https://github.com/swagger-api/swagger-codegen.gitNEWLINE"""NEWLINENEWLINENEWLINEimport pprintNEWLINEimport reNEWLINENEWLINEimport sixNEWLINEimport typingNEWLINENEWLINEfrom ....properties import PropertyNEWLINEif typing.TYPE_CHECKING:NEWLINE from pypureclient.flashblade.FB_2_3 import modelsNEWLINENEWLINEclass CertificateUse(object):NEWLINE """NEWLINE Attributes:NEWLINE swagger_types (dict): The key is attribute nameNEWLINE and the value is attribute type.NEWLINE attribute_map (dict): The key is attribute nameNEWLINE and the value is json key in definition.NEWLINE """NEWLINE swagger_types = {NEWLINE 'name': 'str',NEWLINE 'id': 'str',NEWLINE 'group': 'FixedReference',NEWLINE 'use': 'FixedReferenceWithRemote'NEWLINE }NEWLINENEWLINE attribute_map = {NEWLINE 'name': 'name',NEWLINE 'id': 'id',NEWLINE 'group': 'group',NEWLINE 'use': 'use'NEWLINE }NEWLINENEWLINE required_args = {NEWLINE }NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE name=None, # type: strNEWLINE id=None, # type: strNEWLINE group=None, # type: models.FixedReferenceNEWLINE use=None, # type: models.FixedReferenceWithRemoteNEWLINE ):NEWLINE """NEWLINE Keyword args:NEWLINE name (str): Name of the object (e.g., a file system or snapshot).NEWLINE id (str): A non-modifiable, globally unique ID chosen by the system.NEWLINE group (FixedReference): A reference to a certificate group that is being used, if any, where this certificate is a member of the certificate-group. This field is `null` if the referenced use object is not using a group, but is rather using this certificate directly.NEWLINE use (FixedReferenceWithRemote): A reference to an object using this certificate.NEWLINE """NEWLINE if name is not None:NEWLINE self.name = nameNEWLINE if id is not None:NEWLINE self.id = idNEWLINE if group is not None:NEWLINE self.group = groupNEWLINE if use is not None:NEWLINE self.use = useNEWLINENEWLINE def __setattr__(self, key, value):NEWLINE if key not in self.attribute_map:NEWLINE raise KeyError("Invalid key `{}` for `CertificateUse`".format(key))NEWLINE self.__dict__[key] = valueNEWLINENEWLINE def __getattribute__(self, item):NEWLINE value = object.__getattribute__(self, item)NEWLINE if isinstance(value, Property):NEWLINE return NoneNEWLINE else:NEWLINE return valueNEWLINENEWLINE def to_dict(self):NEWLINE """Returns the model properties as a dict"""NEWLINE result = {}NEWLINENEWLINE for attr, _ in six.iteritems(self.swagger_types):NEWLINE if hasattr(self, attr):NEWLINE value = getattr(self, attr)NEWLINE if isinstance(value, list):NEWLINE result[attr] = list(map(NEWLINE lambda x: x.to_dict() if hasattr(x, "to_dict") else x,NEWLINE valueNEWLINE ))NEWLINE elif hasattr(value, "to_dict"):NEWLINE result[attr] = value.to_dict()NEWLINE elif isinstance(value, dict):NEWLINE result[attr] = dict(map(NEWLINE lambda item: (item[0], item[1].to_dict())NEWLINE if hasattr(item[1], "to_dict") else item,NEWLINE value.items()NEWLINE ))NEWLINE else:NEWLINE result[attr] = valueNEWLINE if issubclass(CertificateUse, dict):NEWLINE for key, value in self.items():NEWLINE result[key] = valueNEWLINENEWLINE return resultNEWLINENEWLINE def to_str(self):NEWLINE """Returns the string representation of the model"""NEWLINE return pprint.pformat(self.to_dict())NEWLINENEWLINE def __repr__(self):NEWLINE """For `print` and `pprint`"""NEWLINE return self.to_str()NEWLINENEWLINE def __eq__(self, other):NEWLINE """Returns true if both objects are equal"""NEWLINE if not isinstance(other, CertificateUse):NEWLINE return FalseNEWLINENEWLINE return self.__dict__ == other.__dict__NEWLINENEWLINE def __ne__(self, other):NEWLINE """Returns true if both objects are not equal"""NEWLINE return not self == otherNEWLINE
# Определение номера столбца с наибольшим количеством отрицательных элементов,NEWLINE# составление массива из элементов матрицы, находящихся под главной диагональю.NEWLINE# Котов НикитаNEWLINENEWLINE# n - размер матрицы;NEWLINE# a - заданная матрица;NEWLINE# maxNum - максимальное количество отрицательных элементов в столбце;NEWLINE# masUnder - массив из элементов матрицы, находящихся под главной диагональю;NEWLINE# i, j - рабочие переменные;NEWLINE# num - количество отрицательных элементов в столбце;NEWLINE# ind - номер столбца с наибольшим количеством отрицательных элементов.NEWLINENEWLINENEWLINEn = int(input('Введите размер матрицы: ' ))NEWLINEprint('Введите матрицу по', '{:d}'.format(n), 'элемента(ов) в строке.')NEWLINEa = [[float(j) for j in input().split()] for i in range(n)]NEWLINENEWLINE# Поиск столбца с наибольшим количеством отрицательных элементов иNEWLINE# элементов, находящихся ниже главной диагонали.NEWLINEmaxNum = 0NEWLINEmasUnder = []NEWLINEfor i in range(n):NEWLINE num = 0NEWLINE for j in range(n):NEWLINE if a[j][i] < 0:NEWLINE num += 1NEWLINE if i < j:NEWLINE masUnder.append(a[j][i])NEWLINE if num > maxNum:NEWLINE maxNum = numNEWLINE ind = iNEWLINENEWLINEprint()NEWLINEprint('Исходная матрица:')NEWLINEfor i in range(n):NEWLINE for j in range(n):NEWLINE print('{: 5.2f}'.format(a[i][j]), end =' ')NEWLINE print()NEWLINEprint()NEWLINEif maxNum == 0:NEWLINE print('В матрице нет отрицательных элементов.')NEWLINEelse:NEWLINE print('Номер столбца с наибольшим количеством отрицательных элементов: '\NEWLINE + '{:d}'.format(ind+1))NEWLINEprint()NEWLINEif masUnder:NEWLINE print('Массив элементов, находящихся под главной диагональю:')NEWLINE for i in range(len(masUnder)):NEWLINE print('{:.3f}'.format(masUnder[i]), end = ' ')NEWLINEelse:NEWLINE print('Под главной диагональю нет элементов.')NEWLINE NEWLINE
# @version: 1.0 date: 05/06/2015 by Sidney BartheNEWLINE# @author: robin.scheibler@epfl.ch, ivan.dokmanic@epfl.ch, sidney.barthe@epfl.chNEWLINE# @copyright: EPFL-IC-LCAV 2015NEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEimport numpy as npNEWLINEimport scipy.spatial as spatialNEWLINEimport ctypesNEWLINENEWLINE#import .beamforming as bfNEWLINEfrom . import beamforming as bfNEWLINEfrom . import geometry as geomNEWLINEfrom .soundsource import SoundSourceNEWLINEfrom .wall import WallNEWLINEfrom .geometry import area, ccw3pNEWLINEfrom .parameters import constants, epsNEWLINENEWLINEfrom .c_package import libroom_available, CWALL, CROOM, libroom, c_wall_p, c_int_p, c_float_p, c_room_pNEWLINENEWLINEclass Room(object):NEWLINE '''NEWLINE This class represents a room instance.NEWLINE NEWLINE A room instance is formed by wall instances. A MicrophoneArray and SoundSources can be added.NEWLINE NEWLINE :attribute walls: (Wall array) list of walls forming the roomNEWLINE :attribute fs: (int) sampling frequencyNEWLINE :attribute t0: (float) time offsetNEWLINE :attribute max_order: (int) the maximum computed order for imagesNEWLINE :attribute sigma2_awgn: (float) ambient additive white gaussian noise levelNEWLINE :attribute sources: (SoundSource array) list of sound sourcesNEWLINE :attribute mics: (MicrophoneArray) array of microphonesNEWLINE :attribute normals: (numpy.ndarray 2xN or 3xN, N=number of walls) array containing normal vector for each wall, used for calculationsNEWLINE :attribute corners: (numpy.ndarray 2xN or 3xN, N=number of walls) array containing a point belonging to each wall, used for calculationsNEWLINE :attribute absorption: (numpy.ndarray size N, N=number of walls) array containing the absorption factor for each wall, used for calculationsNEWLINE :attribute dim: (int) dimension of the room (2 or 3 meaning 2D or 3D)NEWLINE :attribute wallsId: (int dictionary) stores the mapping "wall name -> wall id (in the array walls)"NEWLINE '''NEWLINENEWLINE def __init__(NEWLINE self,NEWLINE walls,NEWLINE fs=8000,NEWLINE t0=0.,NEWLINE max_order=1,NEWLINE sigma2_awgn=None,NEWLINE sources=None,NEWLINE mics=None):NEWLINENEWLINE self.walls = wallsNEWLINE self.fs = fsNEWLINE self.max_order = max_orderNEWLINE self.sigma2_awgn = sigma2_awgnNEWLINENEWLINE # Compute the filter delay if not providedNEWLINE if t0 < (constants.get('frac_delay_length')-1)/float(fs)/2:NEWLINE self.t0 = (constants.get('frac_delay_length')-1)/float(fs)/2NEWLINE else:NEWLINE self.t0 = t0NEWLINE NEWLINE if (sources is list):NEWLINE self.sources = sourcesNEWLINE else:NEWLINE self.sources = []NEWLINENEWLINE self.mic_array = micsNEWLINE NEWLINE self.normals = np.array([wall.normal for wall in self.walls]).TNEWLINE self.corners = np.array([wall.corners[:, 0] for wall in self.walls]).TNEWLINE self.absorption = np.array([wall.absorption for wall in self.walls])NEWLINENEWLINE # Pre-compute RIR if neededNEWLINE if (len(self.sources) > 0 and self.mic_array is not None):NEWLINE self.compute_rir()NEWLINE else:NEWLINE self.rir = NoneNEWLINENEWLINE # in the beginning, nothing has been NEWLINE self.visibility = NoneNEWLINENEWLINE # Get the room dimension from that of the wallsNEWLINE self.dim = walls[0].dimNEWLINENEWLINE # mapping between wall names and indicesNEWLINE self.wallsId = {}NEWLINE for i in range(len(walls)):NEWLINE if self.walls[i].name is not None:NEWLINE self.wallsId[self.walls[i].name] = iNEWLINENEWLINE # check which walls are part of the convex hullNEWLINE self.convex_hull()NEWLINENEWLINE @classmethodNEWLINE def from_corners(NEWLINE cls,NEWLINE corners,NEWLINE absorption=0.,NEWLINE fs=8000,NEWLINE t0=0.,NEWLINE max_order=1,NEWLINE sigma2_awgn=None,NEWLINE sources=None,NEWLINE mics=None):NEWLINE '''NEWLINE Creates a 2D room by giving an array of corners.NEWLINE NEWLINE :arg corners: (np.array dim 2xN, N>2) list of corners, must be antiClockwise orientedNEWLINE :arg absorption: (float array or float) list of absorption factor for each wall or single value for all wallsNEWLINE NEWLINE :returns: (Room) instance of a 2D roomNEWLINE '''NEWLINE NEWLINE corners = np.array(corners)NEWLINE if (corners.shape[0] != 2 or corners.shape[1] < 3):NEWLINE raise ValueError('Arg corners must be more than two 2D points.')NEWLINENEWLINE if (geom.area(corners) <= 0):NEWLINE corners = corners[:,::-1]NEWLINENEWLINE cls.corners = cornersNEWLINE cls.dim = corners.shape[0] NEWLINE NEWLINE absorption = np.array(absorption, dtype='float64')NEWLINE if (absorption.ndim == 0):NEWLINE absorption = absorption * np.ones(corners.shape[1])NEWLINE elif (absorption.ndim > 1 and corners.shape[1] != len(absorption)):NEWLINE raise ValueError('Arg absorption must be the same size as corners or must be a single value.')NEWLINE NEWLINE walls = []NEWLINE for i in range(corners.shape[1]):NEWLINE walls.append(Wall(np.array([corners[:, i], corners[:, (i+1)%corners.shape[1]]]).T, absorption[i], "wall_"+str(i)))NEWLINE NEWLINE return cls(walls, fs, t0, max_order, sigma2_awgn, sources, mics)NEWLINENEWLINE def extrude(NEWLINE self,NEWLINE height,NEWLINE v_vec=None,NEWLINE absorption=0.):NEWLINE '''NEWLINE Creates a 3D room by extruding a 2D polygon. NEWLINE The polygon is typically the floor of the room and will have z-coordinate zero. The ceilingNEWLINENEWLINE ParametersNEWLINE ----------NEWLINE height : floatNEWLINE The extrusion heightNEWLINE v_vec : array-like 1D length 3, optionnalNEWLINE A unit vector. An orientation for the extrusion direction. TheNEWLINE ceiling will be placed as a translation of the floor with respectNEWLINE to this vector (The default is [0,0,1]).NEWLINE absorption : float or array-likeNEWLINE Absorption coefficients for all the walls. If a scalar, then all the wallsNEWLINE will have the same absorption. If an array is given, it should have as many elementsNEWLINE as there will be walls, that is the number of vertices of the polygon plus two. The twoNEWLINE last elements are for the floor and the ceiling, respectively. (default 1)NEWLINE '''NEWLINENEWLINE if self.dim != 2:NEWLINE raise ValueError('Can only extrude a 2D room.')NEWLINENEWLINE # default orientation vector is pointing upNEWLINE if v_vec is None:NEWLINE v_vec = np.array([0., 0., 1.])NEWLINENEWLINE # check that the walls are ordered counterclock wiseNEWLINE # that should be the case if created from from_corners functionNEWLINE nw = len(self.walls)NEWLINE floor_corners = np.zeros((2,nw))NEWLINE floor_corners[:,0] = self.walls[0].corners[:,0]NEWLINE ordered = TrueNEWLINE for iw, wall in enumerate(self.walls[1:]):NEWLINE if not np.allclose(self.walls[iw].corners[:,1], wall.corners[:,0]):NEWLINE ordered = FalseNEWLINE floor_corners[:,iw+1] = wall.corners[:,0]NEWLINE if not np.allclose(self.walls[-1].corners[:,1], self.walls[0].corners[:,0]):NEWLINE ordered = FalseNEWLINENEWLINE if not ordered:NEWLINE raise ValueError("The wall list should be ordered counter-clockwise, which is the case \NEWLINE if the room is created with Room.from_corners")NEWLINENEWLINE # make sure the floor_corners are ordered anti-clockwise (for now)NEWLINE if (geom.area(floor_corners) <= 0):NEWLINE floor_corners = np.fliplr(floor_corners)NEWLINENEWLINE walls = []NEWLINE for i in range(nw):NEWLINE corners = np.array([NEWLINE np.r_[floor_corners[:,i], 0],NEWLINE np.r_[floor_corners[:,(i+1)%nw], 0],NEWLINE np.r_[floor_corners[:,(i+1)%nw], 0] + height*v_vec,NEWLINE np.r_[floor_corners[:,i], 0] + height*v_vecNEWLINE ]).TNEWLINE walls.append(Wall(corners, self.walls[i].absorption, name=str(i)))NEWLINENEWLINE absorption = np.array(absorption)NEWLINE if absorption.ndim == 0:NEWLINE absorption = absorption * np.ones(2)NEWLINE elif absorption.ndim == 1 and absorption.shape[0] != 2:NEWLINE raise ValueError("The size of the absorption array must be 2 for extrude, for the floor and ceiling")NEWLINENEWLINE floor_corners = np.pad(floor_corners, ((0, 1),(0,0)), mode='constant')NEWLINE ceiling_corners = (floor_corners.T + height*v_vec).TNEWLINENEWLINE # we need the floor corners to ordered clockwise (for the normal to point outward)NEWLINE floor_corners = np.fliplr(floor_corners)NEWLINENEWLINE walls.append(Wall(floor_corners, absorption[0], name='floor'))NEWLINE walls.append(Wall(ceiling_corners, absorption[1], name='ceiling'))NEWLINENEWLINE self.walls = wallsNEWLINE self.dim = 3NEWLINENEWLINE # re-collect all normals, corners, absoptionNEWLINE self.normals = np.array([wall.normal for wall in self.walls]).TNEWLINE self.corners = np.array([wall.corners[:, 0] for wall in self.walls]).TNEWLINE self.absorption = np.array([wall.absorption for wall in self.walls])NEWLINENEWLINE # recheck which walls are in the convex hullNEWLINE self.convex_hull()NEWLINENEWLINENEWLINE def convex_hull(self):NEWLINENEWLINE ''' NEWLINE Finds the walls that are not in the convex hullNEWLINE '''NEWLINENEWLINE all_corners = []NEWLINE for wall in self.walls[1:]:NEWLINE all_corners.append(wall.corners.T)NEWLINE X = np.concatenate(all_corners, axis=0)NEWLINE convex_hull = spatial.ConvexHull(X, incremental=True)NEWLINENEWLINE # Now we need to check which walls are on the surfaceNEWLINE # of the hullNEWLINE self.in_convex_hull = [False] * len(self.walls)NEWLINE for i, wall in enumerate(self.walls):NEWLINE # We check if the center of the wall is co-linear or co-planarNEWLINE # with a face of the convex hullNEWLINE point = np.mean(wall.corners, axis=1)NEWLINENEWLINE for simplex in convex_hull.simplices:NEWLINE if point.shape[0] == 2:NEWLINE # check if co-linearNEWLINE p0 = convex_hull.points[simplex[0]]NEWLINE p1 = convex_hull.points[simplex[1]]NEWLINE if geom.ccw3p(p0, p1, point) == 0:NEWLINE # co-linear point add to hullNEWLINE self.in_convex_hull[i] = TrueNEWLINENEWLINE elif point.shape[0] == 3:NEWLINE # Check if co-planarNEWLINE p0 = convex_hull.points[simplex[0]]NEWLINE p1 = convex_hull.points[simplex[1]]NEWLINE p2 = convex_hull.points[simplex[2]]NEWLINENEWLINE normal = np.cross(p1 - p0, p2 - p0)NEWLINE if np.abs(np.inner(normal, point - p0)) < eps:NEWLINE # co-planar point found!NEWLINE self.in_convex_hull[i] = TrueNEWLINENEWLINE self.obstructing_walls = np.array([i for i in range(len(self.walls)) if not self.in_convex_hull[i]], dtype=np.int32)NEWLINENEWLINENEWLINE def plot(self, img_order=None, freq=None, figsize=None, no_axis=False, mic_marker_size=10, **kwargs):NEWLINE ''' Plots the room with its walls, microphones, sources and images '''NEWLINE NEWLINE import matplotlibNEWLINE from matplotlib.patches import Circle, Wedge, PolygonNEWLINE from matplotlib.collections import PatchCollectionNEWLINE import matplotlib.pyplot as pltNEWLINENEWLINE if (self.dim == 2):NEWLINE fig = plt.figure(figsize=figsize)NEWLINENEWLINE if no_axis is True:NEWLINE ax = fig.add_axes([0, 0, 1, 1], aspect='equal', **kwargs)NEWLINE ax.axis('off')NEWLINE rect = fig.patchNEWLINE rect.set_facecolor('gray')NEWLINE rect.set_alpha(0.15)NEWLINE else:NEWLINE ax = fig.add_subplot(111, aspect='equal', **kwargs)NEWLINENEWLINE # draw roomNEWLINE polygons = [Polygon(self.corners.T, True)]NEWLINE p = PatchCollection(polygons, cmap=matplotlib.cm.jet,NEWLINE facecolor=np.array([1, 1, 1]), edgecolor=np.array([0, 0, 0]))NEWLINE ax.add_collection(p)NEWLINENEWLINE # draw the microphonesNEWLINE if (self.mic_array is not None):NEWLINE for mic in self.mic_array.R.T:NEWLINE ax.scatter(mic[0], mic[1],NEWLINE marker='x', linewidth=0.5, s=mic_marker_size, c='k')NEWLINENEWLINE # draw the beam pattern of the beamformer if requested (and available)NEWLINE if freq is not None \NEWLINE and isinstance(self.mic_array, bf.Beamformer) \NEWLINE and (self.mic_array.weights is not None or self.mic_array.filters is not None):NEWLINENEWLINE freq = np.array(freq)NEWLINE if freq.ndim is 0:NEWLINE freq = np.array([freq])NEWLINENEWLINE # define a new set of colors for the beam patternsNEWLINE newmap = plt.get_cmap('autumn')NEWLINE desat = 0.7NEWLINE try:NEWLINE # this is for matplotlib >= 2.0.0NEWLINE ax.set_prop_cycle(color=[newmap(k) for k in desat*np.linspace(0, 1, len(freq))])NEWLINE except:NEWLINE # keep this for backward compatibilityNEWLINE ax.set_color_cycle([newmap(k) for k in desat*np.linspace(0, 1, len(freq))])NEWLINENEWLINE phis = np.arange(360) * 2 * np.pi / 360.NEWLINE newfreq = np.zeros(freq.shape)NEWLINE H = np.zeros((len(freq), len(phis)), dtype=complex)NEWLINE for i, f in enumerate(freq):NEWLINE newfreq[i], H[i] = self.mic_array.response(phis, f)NEWLINENEWLINE # normalize max amplitude to oneNEWLINE H = np.abs(H)**2/np.abs(H).max()**2NEWLINENEWLINE # a normalization factor according to room sizeNEWLINE norm = np.linalg.norm((self.corners - self.mic_array.center), axis=0).max()NEWLINENEWLINE # plot all the beam patternsNEWLINE i = 0NEWLINE for f, h in zip(newfreq, H):NEWLINE x = np.cos(phis) * h * norm + self.mic_array.center[0, 0]NEWLINE y = np.sin(phis) * h * norm + self.mic_array.center[1, 0]NEWLINE l = ax.plot(x, y, '-', linewidth=0.5)NEWLINENEWLINE # define some markers for different sources and colormap for dampingNEWLINE markers = ['o', 's', 'v', '.']NEWLINE cmap = plt.get_cmap('YlGnBu')NEWLINE # draw the scatter of imagesNEWLINE for i, source in enumerate(self.sources):NEWLINE # draw sourceNEWLINE ax.scatter(NEWLINE source.position[0],NEWLINE source.position[1],NEWLINE c=cmap(1.),NEWLINE s=20,NEWLINE marker=markers[i %len(markers)],NEWLINE edgecolor=cmap(1.))NEWLINENEWLINE # draw imagesNEWLINE if (img_order is None):NEWLINE img_order = self.max_orderNEWLINENEWLINE I = source.orders <= img_orderNEWLINENEWLINE val = (np.log2(source.damping[I]) + 10.) / 10.NEWLINE # plot the imagesNEWLINE ax.scatter(source.images[0, I],NEWLINE source.images[1, I],NEWLINE c=cmap(val),NEWLINE s=20,NEWLINE marker=markers[i % len(markers)],NEWLINE edgecolor=cmap(val))NEWLINENEWLINE return fig, axNEWLINE NEWLINE if(self.dim==3):NEWLINENEWLINE import mpl_toolkits.mplot3d as a3NEWLINE import matplotlib.colors as colorsNEWLINE import matplotlib.pyplot as pltNEWLINE import scipy as spNEWLINENEWLINE fig = plt.figure(figsize=figsize)NEWLINE ax = a3.Axes3D(fig)NEWLINENEWLINE # plot the wallsNEWLINE for w in self.walls:NEWLINE tri = a3.art3d.Poly3DCollection([w.corners.T], alpha=0.5)NEWLINE tri.set_color(colors.rgb2hex(sp.rand(3)))NEWLINE tri.set_edgecolor('k')NEWLINE ax.add_collection3d(tri)NEWLINENEWLINE # define some markers for different sources and colormap for dampingNEWLINE markers = ['o', 's', 'v', '.']NEWLINE cmap = plt.get_cmap('YlGnBu')NEWLINE # draw the scatter of imagesNEWLINE for i, source in enumerate(self.sources):NEWLINE # draw sourceNEWLINE ax.scatter(NEWLINE source.position[0],NEWLINE source.position[1],NEWLINE source.position[2],NEWLINE c=cmap(1.),NEWLINE s=20,NEWLINE marker=markers[i %len(markers)],NEWLINE edgecolor=cmap(1.))NEWLINENEWLINE # draw imagesNEWLINE if (img_order is None):NEWLINE img_order = self.max_orderNEWLINENEWLINE I = source.orders <= img_orderNEWLINENEWLINE val = (np.log2(source.damping[I]) + 10.) / 10.NEWLINE # plot the imagesNEWLINE ax.scatter(source.images[0, I],NEWLINE source.images[1, I],NEWLINE source.images[2, I],NEWLINE c=cmap(val),NEWLINE s=20,NEWLINE marker=markers[i % len(markers)],NEWLINE edgecolor=cmap(val))NEWLINENEWLINENEWLINE # draw the microphonesNEWLINE if (self.mic_array is not None):NEWLINE for mic in self.mic_array.R.T:NEWLINE ax.scatter(mic[0], mic[1], mic[2],NEWLINE marker='x', linewidth=0.5, s=mic_marker_size, c='k')NEWLINENEWLINENEWLINE return fig, axNEWLINENEWLINE def plot_rir(self, FD=False):NEWLINENEWLINE if self.rir is None:NEWLINE self.compute_rir()NEWLINENEWLINE import matplotlib.pyplot as pltNEWLINE from . import utilities as uNEWLINENEWLINE M = self.mic_array.MNEWLINE S = len(self.sources)NEWLINE for r in range(M):NEWLINE for s in range(S):NEWLINE h = self.rir[r][s]NEWLINE plt.subplot(M, S, r*S + s + 1)NEWLINE if not FD:NEWLINE plt.plot(np.arange(len(h)) / float(self.fs), h)NEWLINE else:NEWLINE u.real_spectrum(h)NEWLINE plt.title('RIR: mic'+str(r)+' source'+str(s))NEWLINE if r == M-1:NEWLINE if not FD:NEWLINE plt.xlabel('Time [s]')NEWLINE else:NEWLINE plt.xlabel('Normalized frequency')NEWLINENEWLINENEWLINE def add_microphone_array(self, micArray):NEWLINE self.mic_array = micArrayNEWLINENEWLINE def add_source(self, position, signal=None, delay=0):NEWLINENEWLINE if (not self.is_inside(np.array(position))):NEWLINE raise ValueError('The source must be added inside the room.')NEWLINENEWLINE self.sources.append(NEWLINE SoundSource(NEWLINE position,NEWLINE signal=signal,NEWLINE delay=delayNEWLINE )NEWLINE )NEWLINENEWLINE def first_order_images(self, source_position):NEWLINENEWLINE # projected length onto normalNEWLINE ip = np.sum(self.normals * (self.corners - source_position[:, np.newaxis]), axis=0)NEWLINENEWLINE # projected vector from source to wallNEWLINE d = ip * self.normalsNEWLINENEWLINE # compute images points, positivity is to get only the reflections outside the roomNEWLINE images = source_position[:, np.newaxis] + 2 * d[:, ip > 0]NEWLINENEWLINE # collect absorption factors of reflecting wallsNEWLINE damping = (1 - self.absorption[ip > 0])NEWLINENEWLINE # collect the index of the wall corresponding to the new imageNEWLINE wall_indices = np.arange(len(self.walls))[ip > 0]NEWLINENEWLINE return images, damping, wall_indicesNEWLINENEWLINENEWLINE def image_source_model(self, use_libroom=True):NEWLINENEWLINE self.visibility = []NEWLINENEWLINE for source in self.sources:NEWLINENEWLINE if use_libroom and not libroom_available:NEWLINE print("C-extension libroom unavailable. Falling back to pure python")NEWLINENEWLINE # Fall back to pure python if requested or C module unavailableNEWLINE if not use_libroom or not libroom_available:NEWLINE # Then do it in pure pythonNEWLINENEWLINE # First, we will generate all the image sourcesNEWLINENEWLINE # generate first order imagesNEWLINE i, d, w = self.first_order_images(np.array(source.position))NEWLINE images = [i]NEWLINE damping = [d]NEWLINE generators = [-np.ones(i.shape[1])]NEWLINE wall_indices = [w]NEWLINENEWLINE # generate all higher order images up to max_orderNEWLINE o = 1NEWLINE while o < self.max_order:NEWLINE # generate all images of images of previous orderNEWLINE img = np.zeros((self.dim, 0))NEWLINE dmp = np.array([])NEWLINE gen = np.array([])NEWLINE wal = np.array([])NEWLINE for ind, si, sd in zip(range(images[o-1].shape[1]), images[o - 1].T, damping[o - 1]):NEWLINE i, d, w = self.first_order_images(si)NEWLINE img = np.concatenate((img, i), axis=1)NEWLINE dmp = np.concatenate((dmp, d * sd))NEWLINE gen = np.concatenate((gen, ind*np.ones(i.shape[1])))NEWLINE wal = np.concatenate((wal, w))NEWLINENEWLINE # sortNEWLINE ordering = np.lexsort(img)NEWLINE img = img[:, ordering]NEWLINE dmp = dmp[ordering]NEWLINE gen = gen[ordering]NEWLINE wal = wal[ordering]NEWLINENEWLINE if isinstance(self, ShoeBox):NEWLINE '''NEWLINE For shoebox rooms, we can remove duplicateNEWLINE image sources from different wall orderingsNEWLINE '''NEWLINE diff = np.diff(img, axis=1)NEWLINE ui = np.ones(img.shape[1], 'bool')NEWLINE ui[1:] = (diff != 0).any(axis=0)NEWLINENEWLINE # add to array of imagesNEWLINE images.append(img[:, ui])NEWLINE damping.append(dmp[ui])NEWLINE generators.append(gen[ui])NEWLINE wall_indices.append(wal[ui])NEWLINENEWLINE else:NEWLINE '''NEWLINE But in general, we have to keep everythingNEWLINE '''NEWLINE # add to array of imagesNEWLINE images.append(img)NEWLINE damping.append(dmp)NEWLINE generators.append(gen)NEWLINE wall_indices.append(wal)NEWLINENEWLINE # next orderNEWLINE o += 1NEWLINE NEWLINE o_len = np.array([x.shape[0] for x in generators])NEWLINE # correct the pointers for linear structureNEWLINE for o in np.arange(2, len(generators)):NEWLINE generators[o] += np.sum(o_len[0:o-1])NEWLINE NEWLINE # linearize the arraysNEWLINE images_lin = np.concatenate(images, axis=1)NEWLINE damping_lin = np.concatenate(damping)NEWLINE generators_lin = np.concatenate(generators)NEWLINE walls_lin = np.concatenate(wall_indices)NEWLINE NEWLINE # store the corresponding orders in another arrayNEWLINE ordlist = []NEWLINE for o in range(len(generators)):NEWLINE ordlist.append((o+1)*np.ones(o_len[o]))NEWLINE orders_lin = np.concatenate(ordlist)NEWLINENEWLINE # add the direct source to the arraysNEWLINE source.images = np.concatenate((np.array([source.position]).T, images_lin), axis=1)NEWLINE source.damping = np.concatenate(([1], damping_lin))NEWLINE source.generators = np.concatenate(([-1], generators_lin+1)).astype(np.int)NEWLINE source.walls = np.concatenate(([-1], walls_lin)).astype(np.int)NEWLINE source.orders = np.array(np.concatenate(([0], orders_lin)), dtype=np.int)NEWLINENEWLINE # Then we will check the visibilty of the sourcesNEWLINE # visibility is a list with first index for sources, and second for micsNEWLINE self.visibility.append([])NEWLINE for mic in self.mic_array.R.T:NEWLINE if isinstance(self, ShoeBox):NEWLINE # All sources are visible in shoebox roomsNEWLINE self.visibility[-1].append(np.ones(source.images.shape[1], dtype=bool))NEWLINE else:NEWLINE # In general, we need to checkNEWLINE self.visibility[-1].append(NEWLINE self.check_visibility_for_all_images(source, mic, use_libroom=False)NEWLINE )NEWLINE self.visibility[-1] = np.array(self.visibility[-1])NEWLINENEWLINE I = np.zeros(self.visibility[-1].shape[1], dtype=bool)NEWLINE for mic_vis in self.visibility[-1]:NEWLINE I = np.logical_or(I, mic_vis == 1)NEWLINENEWLINE # Now we can get rid of the superfluous imagesNEWLINE source.images = source.images[:,I]NEWLINE source.damping = source.damping[I]NEWLINE source.generators = source.generators[I]NEWLINE source.walls = source.walls[I]NEWLINE source.orders = source.orders[I]NEWLINENEWLINE self.visibility[-1] = self.visibility[-1][:,I]NEWLINENEWLINENEWLINE else:NEWLINE # if libroom is available, use it!NEWLINENEWLINE c_room = self.make_c_room()NEWLINENEWLINE # copy microphone information to structNEWLINE mic = np.asfortranarray(self.mic_array.R, dtype=np.float32)NEWLINE c_room.n_microphones = ctypes.c_int(mic.shape[1])NEWLINE c_room.microphones = mic.ctypes.data_as(c_float_p)NEWLINENEWLINE src = np.array(source.position, dtype=np.float32)NEWLINENEWLINE if isinstance(self, ShoeBox):NEWLINENEWLINE # create absorption list in correct order for shoebox algorithmNEWLINE absorption_list_shoebox = np.array([self.absorption_dict[d] for d in self.wall_names], dtype=np.float32)NEWLINE room_dim = np.array(self.shoebox_dim, dtype=np.float32)NEWLINENEWLINE # Call the dedicated C routine for shoebox roomNEWLINE libroom.image_source_shoebox(NEWLINE ctypes.byref(c_room), NEWLINE src.ctypes.data_as(c_float_p), NEWLINE room_dim.ctypes.data_as(c_float_p),NEWLINE absorption_list_shoebox.ctypes.data_as(c_float_p),NEWLINE self.max_orderNEWLINE )NEWLINE else:NEWLINE # Call the general image source generatorNEWLINE libroom.image_source_model(ctypes.byref(c_room), src.ctypes.data_as(c_float_p), self.max_order)NEWLINENEWLINE # Recover all the arrays as ndarray from the c structNEWLINE n_sources = c_room.n_sourcesNEWLINENEWLINE if (n_sources > 0):NEWLINENEWLINE # numpy wrapper around C arraysNEWLINE images = np.ctypeslib.as_array(c_room.sources, shape=(n_sources, self.dim))NEWLINE orders = np.ctypeslib.as_array(c_room.orders, shape=(n_sources,))NEWLINE gen_walls = np.ctypeslib.as_array(c_room.gen_walls, shape=(n_sources,))NEWLINE attenuations = np.ctypeslib.as_array(c_room.attenuations, shape=(n_sources,))NEWLINE is_visible = np.ctypeslib.as_array(c_room.is_visible, shape=(mic.shape[1], n_sources))NEWLINENEWLINE # Copy to python managed memoryNEWLINE source.images = np.asfortranarray(images.copy().T)NEWLINE source.orders = orders.copy()NEWLINE source.walls = gen_walls.copy()NEWLINE source.damping = attenuations.copy()NEWLINE source.generators = -np.ones(source.walls.shape)NEWLINENEWLINE self.visibility.append(is_visible.copy())NEWLINENEWLINE # free the C malloc'ed memoryNEWLINE libroom.free_sources(ctypes.byref(c_room))NEWLINENEWLINE # We need to check that microphones are indeed in the roomNEWLINE for m in range(self.mic_array.R.shape[1]):NEWLINE # if not, it's not visible from anywhere!NEWLINE if not self.is_inside(self.mic_array.R[:,m]):NEWLINE self.visibility[-1][m,:] = 0NEWLINENEWLINENEWLINE def compute_rir(self):NEWLINE ''' Compute the room impulse response between every source and microphone '''NEWLINE NEWLINE self.rir = []NEWLINENEWLINE # Run image source model if this hasn't been doneNEWLINE if self.visibility is None:NEWLINE self.image_source_model()NEWLINENEWLINE for m, mic in enumerate(self.mic_array.R.T):NEWLINE h = []NEWLINE for s, source in enumerate(self.sources):NEWLINE h.append(source.get_rir(mic, self.visibility[s][m], self.fs, self.t0))NEWLINE self.rir.append(h)NEWLINENEWLINE def simulate(self, recompute_rir=False):NEWLINE ''' Simulates the microphone signal at every microphone in the array '''NEWLINENEWLINE # import convolution routineNEWLINE from scipy.signal import fftconvolveNEWLINENEWLINE # Throw an error if we are missing some hardware in the roomNEWLINE if (len(self.sources) is 0):NEWLINE raise ValueError('There are no sound sources in the room.')NEWLINE if (self.mic_array is None):NEWLINE raise ValueError('There is no microphone in the room.')NEWLINENEWLINE # compute RIR if necessaryNEWLINE if self.rir is None or len(self.rir) == 0 or recompute_rir:NEWLINE self.compute_rir()NEWLINENEWLINE # number of mics and sourcesNEWLINE M = self.mic_array.MNEWLINE S = len(self.sources)NEWLINENEWLINE # compute the maximum signal lengthNEWLINE from itertools import productNEWLINE max_len_rir = np.array([len(self.rir[i][j])NEWLINE for i, j in product(range(M), range(S))]).max()NEWLINE f = lambda i: len(NEWLINE self.sources[i].signal) + np.floor(self.sources[i].delay * self.fs)NEWLINE max_sig_len = np.array([f(i) for i in range(S)]).max()NEWLINE L = int(max_len_rir) + int(max_sig_len) - 1NEWLINE if L % 2 == 1:NEWLINE L += 1NEWLINENEWLINE # the array that will receive all the signalsNEWLINE signals = np.zeros((M, L))NEWLINENEWLINE # compute the signal at every microphone in the arrayNEWLINE for m in np.arange(M):NEWLINE rx = signals[m]NEWLINE for s in np.arange(S):NEWLINE sig = self.sources[s].signalNEWLINE if sig is None:NEWLINE continueNEWLINE d = int(np.floor(self.sources[s].delay * self.fs))NEWLINE h = self.rir[m][s]NEWLINE rx[d:d + len(sig) + len(h) - 1] += fftconvolve(h, sig)NEWLINENEWLINE # add white gaussian noise if necessaryNEWLINE if self.sigma2_awgn is not None:NEWLINE rx += np.random.normal(0., np.sqrt(self.sigma2_awgn), rx.shape)NEWLINENEWLINE # record the signals in the microphonesNEWLINE self.mic_array.record(signals, self.fs)NEWLINENEWLINENEWLINE def direct_snr(self, x, source=0):NEWLINE ''' Computes the direct Signal-to-Noise Ratio '''NEWLINENEWLINE if source >= len(self.sources):NEWLINE raise ValueError('No such source')NEWLINENEWLINE if self.sources[source].signal is None:NEWLINE raise ValueError('No signal defined for source ' + str(source))NEWLINENEWLINE if self.sigma2_awgn is None:NEWLINE return float('inf')NEWLINENEWLINE x = np.array(x)NEWLINENEWLINE sigma2_s = np.mean(self.sources[0].signal**2)NEWLINENEWLINE d2 = np.sum((x - self.sources[source].position)**2)NEWLINENEWLINE return sigma2_s/self.sigma2_awgn/(16*np.pi**2*d2)NEWLINENEWLINENEWLINE def get_wall_by_name(self, name):NEWLINE '''NEWLINE Returns the instance of the wall by giving its name.NEWLINE NEWLINE :arg name: (string) name of the wallNEWLINE NEWLINE :returns: (Wall) instance of the wall with this nameNEWLINE '''NEWLINE NEWLINE if (name in self.wallsId):NEWLINE return self.walls[self.wallsId[name]]NEWLINE else:NEWLINE raise ValueError('The wall '+name+' cannot be found.')NEWLINENEWLINE def print_wall_sequences(self, source):NEWLINENEWLINE visibilityCheck = np.zeros_like(source.images[0])-1NEWLINE NEWLINE for imageId in range(len(visibilityCheck)-1, -1, -1):NEWLINE print("%2d, %d,%.0f,%.0f --- "%(imageId,source.orders[imageId],source.generators[imageId],source.walls[imageId]), end='')NEWLINE p = imageIdNEWLINE while p >= 0:NEWLINE if not np.isnan(source.walls[p]):NEWLINE print(int(source.walls[p]), end='')NEWLINE p = source.generators[p]NEWLINE print()NEWLINENEWLINE def make_c_room(self):NEWLINE ''' Wrapper around the C libroom '''NEWLINENEWLINE # exit if libroom is not availableNEWLINE if not libroom_available:NEWLINE returnNEWLINENEWLINE # create the ctypes wall arrayNEWLINE c_walls = (CWALL * len(self.walls))()NEWLINE c_walls_array = ctypes.cast(c_walls, c_wall_p)NEWLINE for cwall, wall in zip(c_walls_array, self.walls):NEWLINENEWLINE c_corners = wall.corners.ctypes.data_as(c_float_p)NEWLINENEWLINE cwall.dim=wall.dimNEWLINE cwall.absorption=wall.absorptionNEWLINE cwall.normal=(ctypes.c_float * 3)(*wall.normal.tolist())NEWLINE cwall.n_corners=wall.corners.shape[1]NEWLINE cwall.corners=c_cornersNEWLINENEWLINE cwall.origin=(ctypes.c_float * 3)(*wall.plane_point.tolist())NEWLINENEWLINE if wall.dim == 3:NEWLINE c_corners_2d = wall.corners_2d.ctypes.data_as(c_float_p)NEWLINENEWLINE cwall.basis=(ctypes.c_float * 6)(*wall.plane_basis.flatten('F').tolist())NEWLINE cwall.flat_corners=c_corners_2dNEWLINENEWLINE # create the ctypes Room structNEWLINE c_room = CROOM(NEWLINE dim = self.dim,NEWLINE n_walls = len(self.walls),NEWLINE walls = c_walls_array,NEWLINE n_obstructing_walls = self.obstructing_walls.shape[0],NEWLINE obstructing_walls = self.obstructing_walls.ctypes.data_as(c_int_p),NEWLINE )NEWLINENEWLINE return c_roomNEWLINE NEWLINE def check_visibility_for_all_images(self, source, p, use_libroom=True):NEWLINE '''NEWLINE Checks visibility from a given point for all images of the given source.NEWLINE NEWLINE This function tests visibility for all images of the source and returns the resultsNEWLINE in an array.NEWLINE NEWLINE :arg source: (SoundSource) the sound source object (containing all its images)NEWLINE :arg p: (np.array size 2 or 3) coordinates of the point where we check visibilityNEWLINE NEWLINE :returns: (int array) list of results of visibility for each imageNEWLINE -1 : unchecked (only during execution of the function)NEWLINE 0 (False) : not visibleNEWLINE 1 (True) : visibleNEWLINE '''NEWLINE NEWLINE visibilityCheck = np.zeros_like(source.images[0], dtype=np.int32)-1NEWLINE NEWLINE if self.is_inside(np.array(p)):NEWLINE # Only check for points that are in the room!NEWLINE if use_libroom and libroom_available:NEWLINE # Call the C routine that checks visibilityNEWLINENEWLINE # Create the C structNEWLINE c_room = self.make_c_room()NEWLINENEWLINE # copy source information to structNEWLINE c_room.n_sources = ctypes.c_int(source.images.shape[1])NEWLINE c_room.sources = source.images.ctypes.data_as(c_float_p)NEWLINE c_room.parents = source.generators.ctypes.data_as(c_int_p)NEWLINE c_room.gen_walls = source.walls.ctypes.data_as(c_int_p)NEWLINE c_room.orders = source.orders.ctypes.data_as(c_int_p)NEWLINENEWLINE # copy microphone information to structNEWLINE mic = np.array(p, dtype=np.float32)NEWLINE c_room.n_microphones = ctypes.c_int(1)NEWLINE c_room.microphones = mic.ctypes.data_as(c_float_p)NEWLINENEWLINE # add the array for the visibility informationNEWLINE c_room.is_visible = visibilityCheck.ctypes.data_as(c_int_p)NEWLINENEWLINE # Run the routine hereNEWLINE libroom.check_visibility_all(ctypes.byref(c_room))NEWLINENEWLINE return visibilityCheckNEWLINE else:NEWLINE for imageId in range(len(visibilityCheck)-1, -1, -1):NEWLINE visibilityCheck[imageId] = self.is_visible(source, p, imageId)NEWLINE else:NEWLINE # If point is outside, nothing is visibleNEWLINE for imageId in range(len(visibilityCheck)-1, -1, -1):NEWLINE visibilityCheck[imageId] = FalseNEWLINE NEWLINE return visibilityCheckNEWLINENEWLINE NEWLINE def is_visible(self, source, p, imageId = 0):NEWLINE '''NEWLINE Returns true if the given sound source (with image source id) is visible from point p.NEWLINE NEWLINE :arg source: (SoundSource) the sound source (containing all its images)NEWLINE :arg p: (np.array size 2 or 3) coordinates of the point where we check visibilityNEWLINE :arg imageId: (int) id of the image within the SoundSource objectNEWLINE NEWLINE :return: (bool)NEWLINE False (0) : not visibleNEWLINE True (1) : visibleNEWLINE '''NEWLINENEWLINE p = np.array(p)NEWLINE imageId = int(imageId)NEWLINE NEWLINE # Check if there is an obstructionNEWLINE if(self.is_obstructed(source, p, imageId)):NEWLINE return FalseNEWLINE NEWLINE if (source.orders[imageId] > 0):NEWLINE NEWLINE # Check if the line of sight intersects the generating wallNEWLINE genWallId = int(source.walls[imageId])NEWLINENEWLINE # compute the location of the reflection on the wallNEWLINE intersection = self.walls[genWallId].intersection(p, np.array(source.images[:, imageId]))[0]NEWLINENEWLINE # the reflection point needs to be visible from the image source that generates the rayNEWLINE if intersection is not None:NEWLINE # Check visibility for the parent image by recursionNEWLINE return self.is_visible(source, intersection, source.generators[imageId])NEWLINE else:NEWLINE return FalseNEWLINE else:NEWLINE return TrueNEWLINE NEWLINE def is_obstructed(self, source, p, imageId = 0):NEWLINE '''NEWLINE Checks if there is a wall obstructing the line of sight going from a source to a point.NEWLINE NEWLINE :arg source: (SoundSource) the sound source (containing all its images)NEWLINE :arg p: (np.array size 2 or 3) coordinates of the point where we check obstructionNEWLINE :arg imageId: (int) id of the image within the SoundSource objectNEWLINE NEWLINE :returns: (bool)NEWLINE False (0) : not obstructedNEWLINE True (1) : obstructedNEWLINE '''NEWLINE NEWLINE imageId = int(imageId)NEWLINE if (np.isnan(source.walls[imageId])):NEWLINE genWallId = -1NEWLINE else:NEWLINE genWallId = int(source.walls[imageId])NEWLINE NEWLINE # Only 'non-convex' walls can be obstructingNEWLINE for wallId in self.obstructing_walls:NEWLINE NEWLINE # The generating wall can't be obstructiveNEWLINE if(wallId != genWallId):NEWLINE NEWLINE # Test if the line segment intersects the current wallNEWLINE # We ignore intersections at boundaries of the line of sightNEWLINE #intersects, borderOfWall, borderOfSegment = self.walls[wallId].intersects(source.images[:, imageId], p)NEWLINE intersectionPoint, borderOfSegment, borderOfWall = self.walls[wallId].intersection(source.images[:, imageId], p)NEWLINENEWLINE if (intersectionPoint is not None and not borderOfSegment):NEWLINE NEWLINE # Only images with order > 0 have a generating wall. NEWLINE # At this point, there is obstruction for source order 0.NEWLINE if (source.orders[imageId] > 0):NEWLINENEWLINE imageSide = self.walls[genWallId].side(source.images[:, imageId])NEWLINE NEWLINE # Test if the intersection point and the image are atNEWLINE # opposite sides of the generating wall NEWLINE # We ignore the obstruction if it is inside theNEWLINE # generating wall (it is what happens in a corner)NEWLINE intersectionPointSide = self.walls[genWallId].side(intersectionPoint)NEWLINE if (intersectionPointSide != imageSide and intersectionPointSide != 0):NEWLINE return TrueNEWLINE else:NEWLINE return TrueNEWLINE NEWLINE return FalseNEWLINENEWLINE def get_bbox(self):NEWLINE ''' Returns a bounding box for the room '''NEWLINENEWLINE lower = np.amin(np.concatenate([w.corners for w in self.walls], axis=1), axis=1)NEWLINE upper = np.amax(np.concatenate([w.corners for w in self.walls], axis=1), axis=1)NEWLINENEWLINE return np.c_[lower, upper]NEWLINENEWLINE def is_inside(self, p, include_borders = True):NEWLINE '''NEWLINE Checks if the given point is inside the room.NEWLINE NEWLINE ParametersNEWLINE ----------NEWLINE p: array_like, length 2 or 3NEWLINE point to be testedNEWLINE include_borders: bool, optionalNEWLINE set true if a point on the wall must be considered inside the roomNEWLINE NEWLINE ReturnsNEWLINE -------NEWLINE True if the given point is inside the room, False otherwise.NEWLINE '''NEWLINE NEWLINE p = np.array(p)NEWLINE if (self.dim != p.shape[0]):NEWLINE raise ValueError('Dimension of room and p must match.')NEWLINENEWLINE # The method works as follows: we pick a reference point *outside* the room andNEWLINE # draw a line between the point to check and the reference.NEWLINE # If the point to check is inside the room, the line will intersect an oddNEWLINE # number of walls. If it is outside, an even number.NEWLINE # Unfortunately, there are a lot of corner cases when the line intersectsNEWLINE # precisely on a corner of the room for example, or is aligned with a wall.NEWLINENEWLINENEWLINE # To avoid all these corner cases, we will do a randomized test.NEWLINE # We will pick a point at random outside the room so that the probabilityNEWLINE # a corner case happen is virtually zero. If the test raises a cornerNEWLINE # case, we will repeat the test with a different reference point.NEWLINENEWLINE # get the bounding boxNEWLINE bbox = self.get_bbox()NEWLINE bbox_center = np.mean(bbox, axis=1)NEWLINE bbox_max_dist = np.linalg.norm(bbox[:,1] - bbox[:,0]) / 2NEWLINENEWLINE # re-run until we get a non-ambiguous resultNEWLINE max_iter = 5NEWLINE it = 0NEWLINE while it < max_iter:NEWLINENEWLINE # Get random point outside the bounding boxNEWLINE random_vec = np.random.randn(self.dim)NEWLINE random_vec /= np.linalg.norm(random_vec)NEWLINE p0 = bbox_center + 2 * bbox_max_dist * random_vecNEWLINENEWLINE ambiguous = False # be optimisticNEWLINE is_on_border = False # we have to know if the point is on the boundaryNEWLINE count = 0 # wall intersection counterNEWLINE for i in range(len(self.walls)):NEWLINE intersects, border_of_wall, border_of_segment = self.walls[i].intersects(p0, p)NEWLINENEWLINE # this flag is True when p is on the wallNEWLINE if border_of_segment:NEWLINE is_on_border = TrueNEWLINE elif border_of_wall:NEWLINE # the intersection is on a corner of the roomNEWLINE # but the point to check itself is *not* on the wallNEWLINE # then things get trickyNEWLINE ambiguous = TrueNEWLINENEWLINE # count the wall intersectionsNEWLINE if intersects:NEWLINE count += 1NEWLINENEWLINE # start over when ambiguousNEWLINE if ambiguous:NEWLINE it += 1NEWLINE continueNEWLINENEWLINE else:NEWLINE if is_on_border and not include_borders:NEWLINE return FalseNEWLINE elif is_on_border and include_borders:NEWLINE return TrueNEWLINE elif count % 2 == 1:NEWLINE return TrueNEWLINE else:NEWLINE return FalseNEWLINENEWLINE # We should never reach thisNEWLINE raise ValueError(NEWLINE ''' NEWLINE Error could not determine if point is in or out in maximum number of iterations.NEWLINE This is most likely a bug, please report it.NEWLINE '''NEWLINE )NEWLINENEWLINENEWLINE# Room 3DNEWLINENEWLINEclass ShoeBox(Room):NEWLINE '''NEWLINE This class extends room for shoebox room in 3D space.NEWLINE '''NEWLINENEWLINE def __init__(self, NEWLINE p,NEWLINE fs=8000,NEWLINE t0=0.,NEWLINE absorption=0.,NEWLINE max_order=1,NEWLINE sigma2_awgn=None,NEWLINE sources=None,NEWLINE mics=None):NEWLINENEWLINE p = np.array(p, dtype=np.float32)NEWLINENEWLINE if len(p.shape) > 1:NEWLINE raise ValueError("p must be a vector of length 2 or 3.")NEWLINENEWLINE self.dim = p.shape[0]NEWLINENEWLINE # if only one point is provided, place the other at originNEWLINE p2 = np.array(p)NEWLINE p1 = np.zeros(self.dim)NEWLINENEWLINE # record shoebox dimension in objectNEWLINE self.shoebox_dim = p2NEWLINENEWLINE # Keep the correctly ordered naming of wallsNEWLINE # This is the correct order for the shoebox computation laterNEWLINE # W/E is for axis x, S/N for y-axis, F/C for z-axisNEWLINE self.wall_names = ['west', 'east', 'south', 'north']NEWLINE if self.dim == 3:NEWLINE self.wall_names += ['floor', 'ceiling']NEWLINENEWLINE # copy over the aborption coefficentNEWLINE if isinstance(absorption, float):NEWLINE self.absorption_dict = dict(zip(self.wall_names, [absorption] * len(self.wall_names)))NEWLINE absorption = self.absorption_dictNEWLINENEWLINE self.absorption = []NEWLINE if isinstance(absorption, dict):NEWLINE self.absorption_dict = absorptionNEWLINE for d in self.wall_names:NEWLINE if d in self.absorption_dict:NEWLINE self.absorption.append(self.absorption_dict[d])NEWLINE else:NEWLINE raise KeyError(NEWLINE "Absorbtion needs to have keys 'east', 'west', 'north', 'south', 'ceiling' (3d), 'floor' (3d)"NEWLINE )NEWLINENEWLINE self.absorption = np.array(self.absorption)NEWLINE else:NEWLINE raise ValueError("Absorption must be either a scalar or a 2x dim dictionnary with entries for 'east', 'west', etc.")NEWLINENEWLINENEWLINE if self.dim == 2:NEWLINE walls = []NEWLINE # seems the order of walls is important here, don't change!NEWLINE walls.append(Wall(np.array([[p1[0], p2[0]], [p1[1], p1[1]]]), absorption['south'], "south"))NEWLINE walls.append(Wall(np.array([[p2[0], p2[0]], [p1[1], p2[1]]]), absorption['east'], "east"))NEWLINE walls.append(Wall(np.array([[p2[0], p1[0]], [p2[1], p2[1]]]), absorption['north'], "north"))NEWLINE walls.append(Wall(np.array([[p1[0], p1[0]], [p2[1], p1[1]]]), absorption['west'], "west"))NEWLINENEWLINE elif self.dim == 3:NEWLINE walls = []NEWLINE walls.append(Wall(np.array([[p1[0], p1[0], p1[0], p1[0]], [p2[1], p1[1], p1[1], p2[1]], [p1[2], p1[2], p2[2], p2[2]]]), absorption['west'], "west"))NEWLINE walls.append(Wall(np.array([[p2[0], p2[0], p2[0], p2[0]], [p1[1], p2[1], p2[1], p1[1]], [p1[2], p1[2], p2[2], p2[2]]]), absorption['east'], "east"))NEWLINE walls.append(Wall(np.array([[p1[0], p2[0], p2[0], p1[0]], [p1[1], p1[1], p1[1], p1[1]], [p1[2], p1[2], p2[2], p2[2]]]), absorption['south'], "south"))NEWLINE walls.append(Wall(np.array([[p2[0], p1[0], p1[0], p2[0]], [p2[1], p2[1], p2[1], p2[1]], [p1[2], p1[2], p2[2], p2[2]]]), absorption['north'], "north"))NEWLINE walls.append(Wall(np.array([[p2[0], p1[0], p1[0], p2[0]], [p1[1], p1[1], p2[1], p2[1]], [p1[2], p1[2], p1[2], p1[2]]]), absorption['floor'], "floor"))NEWLINE walls.append(Wall(np.array([[p2[0], p2[0], p1[0], p1[0]], [p1[1], p2[1], p2[1], p1[1]], [p2[2], p2[2], p2[2], p2[2]]]), absorption['ceiling'], "ceiling"))NEWLINENEWLINE else:NEWLINE raise ValueError("Only 2D and 3D rooms are supported.")NEWLINENEWLINE Room.__init__(self, walls, fs, t0, max_order, sigma2_awgn, sources, mics)NEWLINENEWLINE def extrude(self, height):NEWLINE ''' Overload the extrude method from 3D rooms '''NEWLINENEWLINE Room.extrude(self, np.array([0., 0., height]))NEWLINENEWLINENEWLINE
from .models import Sentences,WordOptions,WordsinsentenceNEWLINEfrom table import TableNEWLINEfrom table.columns import ColumnNEWLINENEWLINE#this has been defined for the datatables on the siteNEWLINENEWLINE#WordOptionsTable holds required data displayed when clicked on the collapsible in the nav barNEWLINEclass WordOptionsTable(Table):NEWLINE id = Column(field='id',header='id')NEWLINE word = Column(field='word',header='word')NEWLINE lemma = Column(field='lemma',header='Lemma')NEWLINE morph = Column(field='morph',header='Morph')NEWLINE aux_info = Column(field='aux_info',header='aux_info')NEWLINE pre_verb = Column(field='pre_verb',header='pre_verb')NEWLINENEWLINE#SentenceTable holds required data displyed when clicked on the collapsible in the nav barNEWLINEclass SentencesTable(Table):NEWLINE id = Column(field='id',header='id')NEWLINE line = Column(field='line',header='Sentence')NEWLINENEWLINE#WordsinsentenceTable holds required data displyed when clicked on the collapsible in the nav barNEWLINEclass WordsinsentenceTable(Table):NEWLINE id = Column(field='id',header='id')NEWLINE word = Column(field='word',header='word')NEWLINE parent = Column(field='parent',header='parent')NEWLINE children = Column(field='children',header='children')NEWLINE relation = Column(field='relation',header='relation')NEWLINE wordoptions = Column(field='wordoptions',header='wordoptions')
from flask_script import Manager, ShellNEWLINEimport osNEWLINENEWLINEfrom app import create_appNEWLINENEWLINEapp = create_app(os.getenv('APP_SETTINGS'))NEWLINEmanager = Manager(app)NEWLINENEWLINENEWLINEdef make_shell_context():NEWLINE return dict(app=app)NEWLINENEWLINEmanager.add_command("shell", Shell(make_context=make_shell_context()))NEWLINENEWLINEif __name__ == '__main__':NEWLINE manager.run()
import torchNEWLINEimport numpy as npNEWLINENEWLINEfrom torch.nn.utils.clip_grad import clip_grad_norm_NEWLINEfrom maml.utils import accuracyNEWLINENEWLINEdef get_grad_norm(parameters, norm_type=2):NEWLINE if isinstance(parameters, torch.Tensor):NEWLINE parameters = [parameters]NEWLINE parameters = list(filter(lambda p: p.grad is not None, parameters))NEWLINE norm_type = float(norm_type)NEWLINE total_norm = 0NEWLINE for p in parameters:NEWLINE param_norm = p.grad.data.norm(norm_type)NEWLINE total_norm += param_norm.item() ** norm_typeNEWLINE total_norm = total_norm ** (1. / norm_type)NEWLINENEWLINE return total_normNEWLINENEWLINEclass MetaLearner(object):NEWLINE def __init__(self, model, embedding_model, optimizers, fast_lr, loss_func,NEWLINE first_order, num_updates, inner_loop_grad_clip,NEWLINE collect_accuracies, device, alternating=False,NEWLINE embedding_schedule=10, classifier_schedule=10,NEWLINE embedding_grad_clip=0):NEWLINE self._model = modelNEWLINE self._embedding_model = embedding_modelNEWLINE self._fast_lr = fast_lrNEWLINE self._optimizers = optimizersNEWLINE self._loss_func = loss_funcNEWLINE self._first_order = first_orderNEWLINE self._num_updates = num_updatesNEWLINE self._inner_loop_grad_clip = inner_loop_grad_clipNEWLINE self._collect_accuracies = collect_accuraciesNEWLINE self._device = deviceNEWLINE self._alternating = alternatingNEWLINE self._alternating_schedules = (classifier_schedule, embedding_schedule)NEWLINE self._alternating_count = 0NEWLINE self._alternating_index = 1NEWLINE self._embedding_grad_clip = embedding_grad_clipNEWLINE self._grads_mean = []NEWLINENEWLINE self.to(device)NEWLINENEWLINE self._reset_measurements()NEWLINENEWLINE def _reset_measurements(self):NEWLINE self._count_iters = 0.0NEWLINE self._cum_loss = 0.0NEWLINE self._cum_accuracy = 0.0NEWLINENEWLINE def _update_measurements(self, task, loss, preds):NEWLINE self._count_iters += 1.0NEWLINE self._cum_loss += loss.data.cpu().numpy()NEWLINE if self._collect_accuracies:NEWLINE self._cum_accuracy += accuracy(NEWLINE preds, task.y).data.cpu().numpy()NEWLINENEWLINE def _pop_measurements(self):NEWLINE measurements = {}NEWLINE loss = self._cum_loss / self._count_itersNEWLINE measurements['loss'] = lossNEWLINE if self._collect_accuracies:NEWLINE accuracy = self._cum_accuracy / self._count_itersNEWLINE measurements['accuracy'] = accuracyNEWLINE self._reset_measurements()NEWLINE return measurementsNEWLINENEWLINE def measure(self, tasks, train_tasks=None, adapted_params_list=None,NEWLINE embeddings_list=None):NEWLINE """Measures performance on tasks. Either train_tasks has to be a listNEWLINE of training task for computing embeddings, or adapted_params_list andNEWLINE embeddings_list have to contain adapted_params and embeddings"""NEWLINE if adapted_params_list is None:NEWLINE adapted_params_list = [None] * len(tasks)NEWLINE if embeddings_list is None:NEWLINE embeddings_list = [None] * len(tasks)NEWLINE for i in range(len(tasks)):NEWLINE params = adapted_params_list[i]NEWLINE if params is None:NEWLINE params = self._model.param_dictNEWLINE embeddings = embeddings_list[i]NEWLINE task = tasks[i]NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE self._update_measurements(task, loss, preds)NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurementsNEWLINENEWLINE def measure_each(self, tasks, train_tasks=None, adapted_params_list=None,NEWLINE embeddings_list=None):NEWLINE """Measures performance on tasks. Either train_tasks has to be a listNEWLINE of training task for computing embeddings, or adapted_params_list andNEWLINE embeddings_list have to contain adapted_params and embeddings"""NEWLINE """Return a list of losses and accuracies"""NEWLINE if adapted_params_list is None:NEWLINE adapted_params_list = [None] * len(tasks)NEWLINE if embeddings_list is None:NEWLINE embeddings_list = [None] * len(tasks)NEWLINE accuracies = []NEWLINE for i in range(len(tasks)):NEWLINE params = adapted_params_list[i]NEWLINE if params is None:NEWLINE params = self._model.param_dictNEWLINE embeddings = embeddings_list[i]NEWLINE task = tasks[i]NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE pred_y = np.argmax(preds.data.cpu().numpy(), axis=-1)NEWLINE accuracy = np.mean(NEWLINE task.y.data.cpu().numpy() == NEWLINE np.argmax(preds.data.cpu().numpy(), axis=-1))NEWLINE accuracies.append(accuracy)NEWLINENEWLINE return accuraciesNEWLINENEWLINE def update_params(self, loss, params):NEWLINE """Apply one step of gradient descent on the loss function `loss`,NEWLINE with step-size `self._fast_lr`, and returns the updated parameters.NEWLINE """NEWLINE create_graph = not self._first_orderNEWLINE grads = torch.autograd.grad(loss, params.values(),NEWLINE create_graph=create_graph, allow_unused=True)NEWLINE for (name, param), grad in zip(params.items(), grads):NEWLINE if self._inner_loop_grad_clip > 0 and grad is not None:NEWLINE grad = grad.clamp(min=-self._inner_loop_grad_clip,NEWLINE max=self._inner_loop_grad_clip)NEWLINE if grad is not None:NEWLINE params[name] = param - self._fast_lr * gradNEWLINENEWLINE return paramsNEWLINENEWLINE def adapt(self, train_tasks):NEWLINE adapted_params = []NEWLINE embeddings_list = []NEWLINENEWLINE for task in train_tasks:NEWLINE params = self._model.param_dictNEWLINE embeddings = NoneNEWLINE if self._embedding_model:NEWLINE embeddings = self._embedding_model(task)NEWLINE for i in range(self._num_updates):NEWLINE preds = self._model(task, params=params, embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE params = self.update_params(loss, params=params)NEWLINE if i == 0:NEWLINE self._update_measurements(task, loss, preds)NEWLINE adapted_params.append(params)NEWLINE embeddings_list.append(embeddings)NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurements, adapted_params, embeddings_listNEWLINENEWLINE def step(self, adapted_params_list, embeddings_list, val_tasks,NEWLINE is_training):NEWLINE for optimizer in self._optimizers:NEWLINE optimizer.zero_grad()NEWLINE post_update_losses = []NEWLINENEWLINE for adapted_params, embeddings, task in zip(NEWLINE adapted_params_list, embeddings_list, val_tasks):NEWLINE preds = self._model(task, params=adapted_params,NEWLINE embeddings=embeddings)NEWLINE loss = self._loss_func(preds, task.y)NEWLINE post_update_losses.append(loss)NEWLINE self._update_measurements(task, loss, preds)NEWLINENEWLINE mean_loss = torch.mean(torch.stack(post_update_losses))NEWLINE if is_training:NEWLINE mean_loss.backward()NEWLINE if self._alternating:NEWLINE self._optimizers[self._alternating_index].step()NEWLINE self._alternating_count += 1NEWLINE if self._alternating_count % self._alternating_schedules[self._alternating_index] == 0:NEWLINE self._alternating_index = (1 - self._alternating_index)NEWLINE self._alternating_count = 0NEWLINE else:NEWLINE self._optimizers[0].step()NEWLINE if len(self._optimizers) > 1:NEWLINE if self._embedding_grad_clip > 0:NEWLINE _grad_norm = clip_grad_norm_(self._embedding_model.parameters(), self._embedding_grad_clip)NEWLINE else:NEWLINE _grad_norm = get_grad_norm(self._embedding_model.parameters())NEWLINE # grad_normNEWLINE self._grads_mean.append(_grad_norm)NEWLINE self._optimizers[1].step()NEWLINENEWLINE measurements = self._pop_measurements()NEWLINE return measurementsNEWLINENEWLINE def to(self, device, **kwargs):NEWLINE self._device = deviceNEWLINE self._model.to(device, **kwargs)NEWLINE if self._embedding_model:NEWLINE self._embedding_model.to(device, **kwargs)NEWLINENEWLINE def state_dict(self):NEWLINE state = {NEWLINE 'model_state_dict': self._model.state_dict(),NEWLINE 'optimizers': [ optimizer.state_dict() for optimizer in self._optimizers ]NEWLINE }NEWLINE if self._embedding_model:NEWLINE state.update(NEWLINE {'embedding_model_state_dict':NEWLINE self._embedding_model.state_dict()})NEWLINE return stateNEWLINE
#!/usr/bin/env pythonNEWLINE#NEWLINE# Copyright 2007 Google Inc.NEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINENEWLINENEWLINENEWLINEimport sysNEWLINEfrom google.appengine._internal.antlr3 import *NEWLINEfrom google.appengine._internal.antlr3.compat import set, frozensetNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINEHIDDEN = BaseRecognizer.HIDDENNEWLINENEWLINENEWLINEDOLLAR=54NEWLINEEXPONENT=49NEWLINELT=11NEWLINELSQUARE=23NEWLINEASCII_LETTER=52NEWLINELOG=40NEWLINESNIPPET=44NEWLINEOCTAL_ESC=57NEWLINEMAX=41NEWLINECOUNT=38NEWLINEFLOAT=34NEWLINENAME_START=50NEWLINEHTML=28NEWLINENOT=10NEWLINEATOM=29NEWLINEAND=7NEWLINEEOF=-1NEWLINELPAREN=21NEWLINEINDEX=5NEWLINEQUOTE=47NEWLINERPAREN=22NEWLINEDISTANCE=39NEWLINET__58=58NEWLINENAME=26NEWLINEESC_SEQ=48NEWLINEPOW=43NEWLINECOMMA=36NEWLINEPLUS=17NEWLINEGEO=32NEWLINEDIGIT=46NEWLINEEQ=15NEWLINENE=16NEWLINEGE=14NEWLINEXOR=9NEWLINESWITCH=45NEWLINEUNICODE_ESC=56NEWLINENUMBER=31NEWLINEHEX_DIGIT=55NEWLINEUNDERSCORE=53NEWLINEINT=24NEWLINEMIN=42NEWLINETEXT=27NEWLINERSQUARE=25NEWLINEMINUS=18NEWLINEGEOPOINT=33NEWLINEPHRASE=35NEWLINEABS=37NEWLINEWS=51NEWLINENEG=4NEWLINEOR=8NEWLINEGT=13NEWLINEDIV=20NEWLINEDATE=30NEWLINETIMES=19NEWLINECOND=6NEWLINELE=12NEWLINENEWLINENEWLINEclass ExpressionLexer(Lexer):NEWLINENEWLINE grammarFileName = ""NEWLINE antlr_version = version_str_to_tuple("3.1.1")NEWLINE antlr_version_str = "3.1.1"NEWLINENEWLINE def __init__(self, input=None, state=None):NEWLINE if state is None:NEWLINE state = RecognizerSharedState()NEWLINE Lexer.__init__(self, input, state)NEWLINENEWLINE self.dfa9 = self.DFA9(NEWLINE self, 9,NEWLINE eot = self.DFA9_eot,NEWLINE eof = self.DFA9_eof,NEWLINE min = self.DFA9_min,NEWLINE max = self.DFA9_max,NEWLINE accept = self.DFA9_accept,NEWLINE special = self.DFA9_special,NEWLINE transition = self.DFA9_transitionNEWLINE )NEWLINENEWLINE self.dfa16 = self.DFA16(NEWLINE self, 16,NEWLINE eot = self.DFA16_eot,NEWLINE eof = self.DFA16_eof,NEWLINE min = self.DFA16_min,NEWLINE max = self.DFA16_max,NEWLINE accept = self.DFA16_accept,NEWLINE special = self.DFA16_special,NEWLINE transition = self.DFA16_transitionNEWLINE )NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mT__58(self, ):NEWLINENEWLINE try:NEWLINE _type = T__58NEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(46)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mABS(self, ):NEWLINENEWLINE try:NEWLINE _type = ABSNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("abs")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mCOUNT(self, ):NEWLINENEWLINE try:NEWLINE _type = COUNTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("count")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mDISTANCE(self, ):NEWLINENEWLINE try:NEWLINE _type = DISTANCENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("distance")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mGEOPOINT(self, ):NEWLINENEWLINE try:NEWLINE _type = GEOPOINTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("geopoint")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mLOG(self, ):NEWLINENEWLINE try:NEWLINE _type = LOGNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("log")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mMAX(self, ):NEWLINENEWLINE try:NEWLINE _type = MAXNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("max")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mMIN(self, ):NEWLINENEWLINE try:NEWLINE _type = MINNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("min")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mPOW(self, ):NEWLINENEWLINE try:NEWLINE _type = POWNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("pow")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mAND(self, ):NEWLINENEWLINE try:NEWLINE _type = ANDNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("AND")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mOR(self, ):NEWLINENEWLINE try:NEWLINE _type = ORNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("OR")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mXOR(self, ):NEWLINENEWLINE try:NEWLINE _type = XORNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("XOR")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mNOT(self, ):NEWLINENEWLINE try:NEWLINE _type = NOTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("NOT")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mSNIPPET(self, ):NEWLINENEWLINE try:NEWLINE _type = SNIPPETNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("snippet")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mSWITCH(self, ):NEWLINENEWLINE try:NEWLINE _type = SWITCHNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("switch")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mTEXT(self, ):NEWLINENEWLINE try:NEWLINE _type = TEXTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("text")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mHTML(self, ):NEWLINENEWLINE try:NEWLINE _type = HTMLNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("html")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mATOM(self, ):NEWLINENEWLINE try:NEWLINE _type = ATOMNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("atom")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mDATE(self, ):NEWLINENEWLINE try:NEWLINE _type = DATENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("date")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mNUMBER(self, ):NEWLINENEWLINE try:NEWLINE _type = NUMBERNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("number")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mGEO(self, ):NEWLINENEWLINE try:NEWLINE _type = GEONEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("geo")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mINT(self, ):NEWLINENEWLINE try:NEWLINE _type = INTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINENEWLINE cnt1 = 0NEWLINE while True:NEWLINE alt1 = 2NEWLINE LA1_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA1_0 <= 57)) :NEWLINE alt1 = 1NEWLINENEWLINENEWLINE if alt1 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE if cnt1 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(1, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt1 += 1NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mPHRASE(self, ):NEWLINENEWLINE try:NEWLINE _type = PHRASENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.mQUOTE()NEWLINENEWLINE while True:NEWLINE alt2 = 3NEWLINE LA2_0 = self.input.LA(1)NEWLINENEWLINE if (LA2_0 == 92) :NEWLINE alt2 = 1NEWLINE elif ((0 <= LA2_0 <= 33) or (35 <= LA2_0 <= 91) or (93 <= LA2_0 <= 65535)) :NEWLINE alt2 = 2NEWLINENEWLINENEWLINE if alt2 == 1:NEWLINENEWLINE passNEWLINE self.mESC_SEQ()NEWLINENEWLINENEWLINE elif alt2 == 2:NEWLINENEWLINE passNEWLINE if (0 <= self.input.LA(1) <= 33) or (35 <= self.input.LA(1) <= 91) or (93 <= self.input.LA(1) <= 65535):NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINE else:NEWLINE breakNEWLINENEWLINENEWLINE self.mQUOTE()NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mFLOAT(self, ):NEWLINENEWLINE try:NEWLINE _type = FLOATNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINE alt9 = 3NEWLINE alt9 = self.dfa9.predict(self.input)NEWLINE if alt9 == 1:NEWLINENEWLINE passNEWLINENEWLINE cnt3 = 0NEWLINE while True:NEWLINE alt3 = 2NEWLINE LA3_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA3_0 <= 57)) :NEWLINE alt3 = 1NEWLINENEWLINENEWLINE if alt3 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE if cnt3 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(3, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt3 += 1NEWLINENEWLINENEWLINE self.match(46)NEWLINENEWLINE while True:NEWLINE alt4 = 2NEWLINE LA4_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA4_0 <= 57)) :NEWLINE alt4 = 1NEWLINENEWLINENEWLINE if alt4 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE breakNEWLINENEWLINENEWLINENEWLINE alt5 = 2NEWLINE LA5_0 = self.input.LA(1)NEWLINENEWLINE if (LA5_0 == 69 or LA5_0 == 101) :NEWLINE alt5 = 1NEWLINE if alt5 == 1:NEWLINENEWLINE passNEWLINE self.mEXPONENT()NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE elif alt9 == 2:NEWLINENEWLINE passNEWLINE self.match(46)NEWLINENEWLINE cnt6 = 0NEWLINE while True:NEWLINE alt6 = 2NEWLINE LA6_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA6_0 <= 57)) :NEWLINE alt6 = 1NEWLINENEWLINENEWLINE if alt6 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE if cnt6 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(6, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt6 += 1NEWLINENEWLINENEWLINENEWLINE alt7 = 2NEWLINE LA7_0 = self.input.LA(1)NEWLINENEWLINE if (LA7_0 == 69 or LA7_0 == 101) :NEWLINE alt7 = 1NEWLINE if alt7 == 1:NEWLINENEWLINE passNEWLINE self.mEXPONENT()NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE elif alt9 == 3:NEWLINENEWLINE passNEWLINENEWLINE cnt8 = 0NEWLINE while True:NEWLINE alt8 = 2NEWLINE LA8_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA8_0 <= 57)) :NEWLINE alt8 = 1NEWLINENEWLINENEWLINE if alt8 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE if cnt8 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(8, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt8 += 1NEWLINENEWLINENEWLINE self.mEXPONENT()NEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mNAME(self, ):NEWLINENEWLINE try:NEWLINE _type = NAMENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.mNAME_START()NEWLINENEWLINE while True:NEWLINE alt10 = 2NEWLINE LA10_0 = self.input.LA(1)NEWLINENEWLINE if (LA10_0 == 36 or (48 <= LA10_0 <= 57) or (65 <= LA10_0 <= 90) or LA10_0 == 95 or (97 <= LA10_0 <= 122)) :NEWLINE alt10 = 1NEWLINENEWLINENEWLINE if alt10 == 1:NEWLINENEWLINE passNEWLINE if self.input.LA(1) == 36 or (48 <= self.input.LA(1) <= 57) or (65 <= self.input.LA(1) <= 90) or self.input.LA(1) == 95 or (97 <= self.input.LA(1) <= 122):NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINE else:NEWLINE breakNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mLPAREN(self, ):NEWLINENEWLINE try:NEWLINE _type = LPARENNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(40)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mRPAREN(self, ):NEWLINENEWLINE try:NEWLINE _type = RPARENNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(41)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mLSQUARE(self, ):NEWLINENEWLINE try:NEWLINE _type = LSQUARENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(91)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mRSQUARE(self, ):NEWLINENEWLINE try:NEWLINE _type = RSQUARENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(93)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mPLUS(self, ):NEWLINENEWLINE try:NEWLINE _type = PLUSNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(43)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mMINUS(self, ):NEWLINENEWLINE try:NEWLINE _type = MINUSNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(45)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mTIMES(self, ):NEWLINENEWLINE try:NEWLINE _type = TIMESNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(42)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mDIV(self, ):NEWLINENEWLINE try:NEWLINE _type = DIVNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(47)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mLT(self, ):NEWLINENEWLINE try:NEWLINE _type = LTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(60)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mLE(self, ):NEWLINENEWLINE try:NEWLINE _type = LENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("<=")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mGT(self, ):NEWLINENEWLINE try:NEWLINE _type = GTNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(62)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mGE(self, ):NEWLINENEWLINE try:NEWLINE _type = GENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(">=")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mEQ(self, ):NEWLINENEWLINE try:NEWLINE _type = EQNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(61)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mNE(self, ):NEWLINENEWLINE try:NEWLINE _type = NENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match("!=")NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mCOND(self, ):NEWLINENEWLINE try:NEWLINE _type = CONDNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(63)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mQUOTE(self, ):NEWLINENEWLINE try:NEWLINE _type = QUOTENEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(34)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mCOMMA(self, ):NEWLINENEWLINE try:NEWLINE _type = COMMANEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINE self.match(44)NEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mWS(self, ):NEWLINENEWLINE try:NEWLINE _type = WSNEWLINE _channel = DEFAULT_CHANNELNEWLINENEWLINENEWLINENEWLINE passNEWLINENEWLINE cnt11 = 0NEWLINE while True:NEWLINE alt11 = 2NEWLINE LA11_0 = self.input.LA(1)NEWLINENEWLINE if ((9 <= LA11_0 <= 10) or LA11_0 == 13 or LA11_0 == 32) :NEWLINE alt11 = 1NEWLINENEWLINENEWLINE if alt11 == 1:NEWLINENEWLINE passNEWLINE if (9 <= self.input.LA(1) <= 10) or self.input.LA(1) == 13 or self.input.LA(1) == 32:NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINE else:NEWLINE if cnt11 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(11, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt11 += 1NEWLINENEWLINENEWLINENEWLINE _channel = HIDDEN;NEWLINENEWLINENEWLINENEWLINENEWLINE self._state.type = _typeNEWLINE self._state.channel = _channelNEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mEXPONENT(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE if self.input.LA(1) == 69 or self.input.LA(1) == 101:NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINE alt12 = 2NEWLINE LA12_0 = self.input.LA(1)NEWLINENEWLINE if (LA12_0 == 43 or LA12_0 == 45) :NEWLINE alt12 = 1NEWLINE if alt12 == 1:NEWLINENEWLINE passNEWLINE if self.input.LA(1) == 43 or self.input.LA(1) == 45:NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE cnt13 = 0NEWLINE while True:NEWLINE alt13 = 2NEWLINE LA13_0 = self.input.LA(1)NEWLINENEWLINE if ((48 <= LA13_0 <= 57)) :NEWLINE alt13 = 1NEWLINENEWLINENEWLINE if alt13 == 1:NEWLINENEWLINE passNEWLINE self.mDIGIT()NEWLINENEWLINENEWLINE else:NEWLINE if cnt13 >= 1:NEWLINE breakNEWLINENEWLINE eee = EarlyExitException(13, self.input)NEWLINE raise eeeNEWLINENEWLINE cnt13 += 1NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mNAME_START(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE if self.input.LA(1) == 36 or (65 <= self.input.LA(1) <= 90) or self.input.LA(1) == 95 or (97 <= self.input.LA(1) <= 122):NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mASCII_LETTER(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE if (65 <= self.input.LA(1) <= 90) or (97 <= self.input.LA(1) <= 122):NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mDIGIT(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 57)NEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mDOLLAR(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE self.match(36)NEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mUNDERSCORE(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE self.match(95)NEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mHEX_DIGIT(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE if (48 <= self.input.LA(1) <= 57) or (65 <= self.input.LA(1) <= 70) or (97 <= self.input.LA(1) <= 102):NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mESC_SEQ(self, ):NEWLINENEWLINE try:NEWLINENEWLINE alt14 = 3NEWLINE LA14_0 = self.input.LA(1)NEWLINENEWLINE if (LA14_0 == 92) :NEWLINE LA14 = self.input.LA(2)NEWLINE if LA14 == 34 or LA14 == 39 or LA14 == 92 or LA14 == 98 or LA14 == 102 or LA14 == 110 or LA14 == 114 or LA14 == 116:NEWLINE alt14 = 1NEWLINE elif LA14 == 117:NEWLINE alt14 = 2NEWLINE elif LA14 == 48 or LA14 == 49 or LA14 == 50 or LA14 == 51 or LA14 == 52 or LA14 == 53 or LA14 == 54 or LA14 == 55:NEWLINE alt14 = 3NEWLINE else:NEWLINE nvae = NoViableAltException("", 14, 1, self.input)NEWLINENEWLINE raise nvaeNEWLINENEWLINE else:NEWLINE nvae = NoViableAltException("", 14, 0, self.input)NEWLINENEWLINE raise nvaeNEWLINENEWLINE if alt14 == 1:NEWLINENEWLINE passNEWLINE self.match(92)NEWLINE if self.input.LA(1) == 34 or self.input.LA(1) == 39 or self.input.LA(1) == 92 or self.input.LA(1) == 98 or self.input.LA(1) == 102 or self.input.LA(1) == 110 or self.input.LA(1) == 114 or self.input.LA(1) == 116:NEWLINE self.input.consume()NEWLINE else:NEWLINE mse = MismatchedSetException(None, self.input)NEWLINE self.recover(mse)NEWLINE raise mseNEWLINENEWLINENEWLINENEWLINE elif alt14 == 2:NEWLINENEWLINE passNEWLINE self.mUNICODE_ESC()NEWLINENEWLINENEWLINE elif alt14 == 3:NEWLINENEWLINE passNEWLINE self.mOCTAL_ESC()NEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mOCTAL_ESC(self, ):NEWLINENEWLINE try:NEWLINENEWLINE alt15 = 3NEWLINE LA15_0 = self.input.LA(1)NEWLINENEWLINE if (LA15_0 == 92) :NEWLINE LA15_1 = self.input.LA(2)NEWLINENEWLINE if ((48 <= LA15_1 <= 51)) :NEWLINE LA15_2 = self.input.LA(3)NEWLINENEWLINE if ((48 <= LA15_2 <= 55)) :NEWLINE LA15_5 = self.input.LA(4)NEWLINENEWLINE if ((48 <= LA15_5 <= 55)) :NEWLINE alt15 = 1NEWLINE else:NEWLINE alt15 = 2NEWLINE else:NEWLINE alt15 = 3NEWLINE elif ((52 <= LA15_1 <= 55)) :NEWLINE LA15_3 = self.input.LA(3)NEWLINENEWLINE if ((48 <= LA15_3 <= 55)) :NEWLINE alt15 = 2NEWLINE else:NEWLINE alt15 = 3NEWLINE else:NEWLINE nvae = NoViableAltException("", 15, 1, self.input)NEWLINENEWLINE raise nvaeNEWLINENEWLINE else:NEWLINE nvae = NoViableAltException("", 15, 0, self.input)NEWLINENEWLINE raise nvaeNEWLINENEWLINE if alt15 == 1:NEWLINENEWLINE passNEWLINE self.match(92)NEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 51)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 55)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 55)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE elif alt15 == 2:NEWLINENEWLINE passNEWLINE self.match(92)NEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 55)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 55)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE elif alt15 == 3:NEWLINENEWLINE passNEWLINE self.match(92)NEWLINENEWLINENEWLINE passNEWLINE self.matchRange(48, 55)NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mUNICODE_ESC(self, ):NEWLINENEWLINE try:NEWLINENEWLINENEWLINE passNEWLINE self.match(92)NEWLINE self.match(117)NEWLINE self.mHEX_DIGIT()NEWLINE self.mHEX_DIGIT()NEWLINE self.mHEX_DIGIT()NEWLINE self.mHEX_DIGIT()NEWLINENEWLINENEWLINENEWLINENEWLINE finally:NEWLINENEWLINE passNEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE def mTokens(self):NEWLINENEWLINE alt16 = 43NEWLINE alt16 = self.dfa16.predict(self.input)NEWLINE if alt16 == 1:NEWLINENEWLINE passNEWLINE self.mT__58()NEWLINENEWLINENEWLINE elif alt16 == 2:NEWLINENEWLINE passNEWLINE self.mABS()NEWLINENEWLINENEWLINE elif alt16 == 3:NEWLINENEWLINE passNEWLINE self.mCOUNT()NEWLINENEWLINENEWLINE elif alt16 == 4:NEWLINENEWLINE passNEWLINE self.mDISTANCE()NEWLINENEWLINENEWLINE elif alt16 == 5:NEWLINENEWLINE passNEWLINE self.mGEOPOINT()NEWLINENEWLINENEWLINE elif alt16 == 6:NEWLINENEWLINE passNEWLINE self.mLOG()NEWLINENEWLINENEWLINE elif alt16 == 7:NEWLINENEWLINE passNEWLINE self.mMAX()NEWLINENEWLINENEWLINE elif alt16 == 8:NEWLINENEWLINE passNEWLINE self.mMIN()NEWLINENEWLINENEWLINE elif alt16 == 9:NEWLINENEWLINE passNEWLINE self.mPOW()NEWLINENEWLINENEWLINE elif alt16 == 10:NEWLINENEWLINE passNEWLINE self.mAND()NEWLINENEWLINENEWLINE elif alt16 == 11:NEWLINENEWLINE passNEWLINE self.mOR()NEWLINENEWLINENEWLINE elif alt16 == 12:NEWLINENEWLINE passNEWLINE self.mXOR()NEWLINENEWLINENEWLINE elif alt16 == 13:NEWLINENEWLINE passNEWLINE self.mNOT()NEWLINENEWLINENEWLINE elif alt16 == 14:NEWLINENEWLINE passNEWLINE self.mSNIPPET()NEWLINENEWLINENEWLINE elif alt16 == 15:NEWLINENEWLINE passNEWLINE self.mSWITCH()NEWLINENEWLINENEWLINE elif alt16 == 16:NEWLINENEWLINE passNEWLINE self.mTEXT()NEWLINENEWLINENEWLINE elif alt16 == 17:NEWLINENEWLINE passNEWLINE self.mHTML()NEWLINENEWLINENEWLINE elif alt16 == 18:NEWLINENEWLINE passNEWLINE self.mATOM()NEWLINENEWLINENEWLINE elif alt16 == 19:NEWLINENEWLINE passNEWLINE self.mDATE()NEWLINENEWLINENEWLINE elif alt16 == 20:NEWLINENEWLINE passNEWLINE self.mNUMBER()NEWLINENEWLINENEWLINE elif alt16 == 21:NEWLINENEWLINE passNEWLINE self.mGEO()NEWLINENEWLINENEWLINE elif alt16 == 22:NEWLINENEWLINE passNEWLINE self.mINT()NEWLINENEWLINENEWLINE elif alt16 == 23:NEWLINENEWLINE passNEWLINE self.mPHRASE()NEWLINENEWLINENEWLINE elif alt16 == 24:NEWLINENEWLINE passNEWLINE self.mFLOAT()NEWLINENEWLINENEWLINE elif alt16 == 25:NEWLINENEWLINE passNEWLINE self.mNAME()NEWLINENEWLINENEWLINE elif alt16 == 26:NEWLINENEWLINE passNEWLINE self.mLPAREN()NEWLINENEWLINENEWLINE elif alt16 == 27:NEWLINENEWLINE passNEWLINE self.mRPAREN()NEWLINENEWLINENEWLINE elif alt16 == 28:NEWLINENEWLINE passNEWLINE self.mLSQUARE()NEWLINENEWLINENEWLINE elif alt16 == 29:NEWLINENEWLINE passNEWLINE self.mRSQUARE()NEWLINENEWLINENEWLINE elif alt16 == 30:NEWLINENEWLINE passNEWLINE self.mPLUS()NEWLINENEWLINENEWLINE elif alt16 == 31:NEWLINENEWLINE passNEWLINE self.mMINUS()NEWLINENEWLINENEWLINE elif alt16 == 32:NEWLINENEWLINE passNEWLINE self.mTIMES()NEWLINENEWLINENEWLINE elif alt16 == 33:NEWLINENEWLINE passNEWLINE self.mDIV()NEWLINENEWLINENEWLINE elif alt16 == 34:NEWLINENEWLINE passNEWLINE self.mLT()NEWLINENEWLINENEWLINE elif alt16 == 35:NEWLINENEWLINE passNEWLINE self.mLE()NEWLINENEWLINENEWLINE elif alt16 == 36:NEWLINENEWLINE passNEWLINE self.mGT()NEWLINENEWLINENEWLINE elif alt16 == 37:NEWLINENEWLINE passNEWLINE self.mGE()NEWLINENEWLINENEWLINE elif alt16 == 38:NEWLINENEWLINE passNEWLINE self.mEQ()NEWLINENEWLINENEWLINE elif alt16 == 39:NEWLINENEWLINE passNEWLINE self.mNE()NEWLINENEWLINENEWLINE elif alt16 == 40:NEWLINENEWLINE passNEWLINE self.mCOND()NEWLINENEWLINENEWLINE elif alt16 == 41:NEWLINENEWLINE passNEWLINE self.mQUOTE()NEWLINENEWLINENEWLINE elif alt16 == 42:NEWLINENEWLINE passNEWLINE self.mCOMMA()NEWLINENEWLINENEWLINE elif alt16 == 43:NEWLINENEWLINE passNEWLINE self.mWS()NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE DFA9_eot = DFA.unpack(NEWLINE "\5\uffff"NEWLINE )NEWLINENEWLINE DFA9_eof = DFA.unpack(NEWLINE "\5\uffff"NEWLINE )NEWLINENEWLINE DFA9_min = DFA.unpack(NEWLINE "\2\56\3\uffff"NEWLINE )NEWLINENEWLINE DFA9_max = DFA.unpack(NEWLINE "\1\71\1\145\3\uffff"NEWLINE )NEWLINENEWLINE DFA9_accept = DFA.unpack(NEWLINE "\2\uffff\1\2\1\1\1\3"NEWLINE )NEWLINENEWLINE DFA9_special = DFA.unpack(NEWLINE "\5\uffff"NEWLINE )NEWLINENEWLINENEWLINE DFA9_transition = [NEWLINE DFA.unpack("\1\2\1\uffff\12\1"),NEWLINE DFA.unpack("\1\3\1\uffff\12\1\13\uffff\1\4\37\uffff\1\4"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("")NEWLINE ]NEWLINENEWLINENEWLINENEWLINE DFA9 = DFANEWLINENEWLINENEWLINE DFA16_eot = DFA.unpack(NEWLINE "\1\uffff\1\43\17\23\1\70\1\71\11\uffff\1\74\1\76\7\uffff\13\23"NEWLINE "\1\112\7\23\7\uffff\1\122\4\23\1\130\1\131\1\132\1\133\1\134\1"NEWLINE "\135\1\uffff\1\136\1\137\5\23\1\uffff\1\145\2\23\1\150\1\23\10"NEWLINE "\uffff\2\23\1\154\1\155\1\23\1\uffff\1\157\1\23\1\uffff\3\23\2"NEWLINE "\uffff\1\23\1\uffff\3\23\1\170\1\171\2\23\1\174\2\uffff\1\175\1"NEWLINE "\176\3\uffff"NEWLINE )NEWLINENEWLINE DFA16_eof = DFA.unpack(NEWLINE "\177\uffff"NEWLINE )NEWLINENEWLINE DFA16_min = DFA.unpack(NEWLINE "\1\11\1\60\1\142\1\157\1\141\1\145\1\157\1\141\1\157\1\116\1\122"NEWLINE "\2\117\1\156\1\145\1\164\1\165\1\56\1\0\11\uffff\2\75\7\uffff\1"NEWLINE "\163\1\157\1\165\1\163\1\164\1\157\1\147\1\170\1\156\1\167\1\104"NEWLINE "\1\44\1\122\1\124\2\151\1\170\2\155\7\uffff\1\44\1\155\1\156\1"NEWLINE "\164\1\145\6\44\1\uffff\2\44\1\160\2\164\1\154\1\142\1\uffff\1"NEWLINE "\44\1\164\1\141\1\44\1\157\10\uffff\1\160\1\143\2\44\1\145\1\uffff"NEWLINE "\1\44\1\156\1\uffff\1\151\1\145\1\150\2\uffff\1\162\1\uffff\1\143"NEWLINE "\1\156\1\164\2\44\1\145\1\164\1\44\2\uffff\2\44\3\uffff"NEWLINE )NEWLINENEWLINE DFA16_max = DFA.unpack(NEWLINE "\1\172\1\71\1\164\1\157\1\151\1\145\1\157\1\151\1\157\1\116\1\122"NEWLINE "\2\117\1\167\1\145\1\164\1\165\1\145\1\uffff\11\uffff\2\75\7\uffff"NEWLINE "\1\163\1\157\1\165\1\163\1\164\1\157\1\147\1\170\1\156\1\167\1"NEWLINE "\104\1\172\1\122\1\124\2\151\1\170\2\155\7\uffff\1\172\1\155\1"NEWLINE "\156\1\164\1\145\6\172\1\uffff\2\172\1\160\2\164\1\154\1\142\1"NEWLINE "\uffff\1\172\1\164\1\141\1\172\1\157\10\uffff\1\160\1\143\2\172"NEWLINE "\1\145\1\uffff\1\172\1\156\1\uffff\1\151\1\145\1\150\2\uffff\1"NEWLINE "\162\1\uffff\1\143\1\156\1\164\2\172\1\145\1\164\1\172\2\uffff"NEWLINE "\2\172\3\uffff"NEWLINE )NEWLINENEWLINE DFA16_accept = DFA.unpack(NEWLINE "\23\uffff\1\31\1\32\1\33\1\34\1\35\1\36\1\37\1\40\1\41\2\uffff"NEWLINE "\1\46\1\47\1\50\1\52\1\53\1\1\1\30\23\uffff\1\26\1\51\1\27\1\43"NEWLINE "\1\42\1\45\1\44\13\uffff\1\13\7\uffff\1\2\5\uffff\1\25\1\6\1\7"NEWLINE "\1\10\1\11\1\12\1\14\1\15\5\uffff\1\22\2\uffff\1\23\3\uffff\1\20"NEWLINE "\1\21\1\uffff\1\3\10\uffff\1\17\1\24\2\uffff\1\16\1\4\1\5"NEWLINE )NEWLINENEWLINE DFA16_special = DFA.unpack(NEWLINE "\22\uffff\1\0\154\uffff"NEWLINE )NEWLINENEWLINENEWLINE DFA16_transition = [NEWLINE DFA.unpack("\2\42\2\uffff\1\42\22\uffff\1\42\1\37\1\22\1\uffff\1"NEWLINE "\23\3\uffff\1\24\1\25\1\32\1\30\1\41\1\31\1\1\1\33\12\21\2\uffff"NEWLINE "\1\34\1\36\1\35\1\40\1\uffff\1\11\14\23\1\14\1\12\10\23\1\13\2"NEWLINE "\23\1\26\1\uffff\1\27\1\uffff\1\23\1\uffff\1\2\1\23\1\3\1\4\2\23"NEWLINE "\1\5\1\17\3\23\1\6\1\7\1\20\1\23\1\10\2\23\1\15\1\16\6\23"),NEWLINE DFA.unpack("\12\44"),NEWLINE DFA.unpack("\1\45\21\uffff\1\46"),NEWLINE DFA.unpack("\1\47"),NEWLINE DFA.unpack("\1\51\7\uffff\1\50"),NEWLINE DFA.unpack("\1\52"),NEWLINE DFA.unpack("\1\53"),NEWLINE DFA.unpack("\1\54\7\uffff\1\55"),NEWLINE DFA.unpack("\1\56"),NEWLINE DFA.unpack("\1\57"),NEWLINE DFA.unpack("\1\60"),NEWLINE DFA.unpack("\1\61"),NEWLINE DFA.unpack("\1\62"),NEWLINE DFA.unpack("\1\63\10\uffff\1\64"),NEWLINE DFA.unpack("\1\65"),NEWLINE DFA.unpack("\1\66"),NEWLINE DFA.unpack("\1\67"),NEWLINE DFA.unpack("\1\44\1\uffff\12\21\13\uffff\1\44\37\uffff\1\44"),NEWLINE DFA.unpack("\0\72"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\73"),NEWLINE DFA.unpack("\1\75"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\77"),NEWLINE DFA.unpack("\1\100"),NEWLINE DFA.unpack("\1\101"),NEWLINE DFA.unpack("\1\102"),NEWLINE DFA.unpack("\1\103"),NEWLINE DFA.unpack("\1\104"),NEWLINE DFA.unpack("\1\105"),NEWLINE DFA.unpack("\1\106"),NEWLINE DFA.unpack("\1\107"),NEWLINE DFA.unpack("\1\110"),NEWLINE DFA.unpack("\1\111"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\113"),NEWLINE DFA.unpack("\1\114"),NEWLINE DFA.unpack("\1\115"),NEWLINE DFA.unpack("\1\116"),NEWLINE DFA.unpack("\1\117"),NEWLINE DFA.unpack("\1\120"),NEWLINE DFA.unpack("\1\121"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\123"),NEWLINE DFA.unpack("\1\124"),NEWLINE DFA.unpack("\1\125"),NEWLINE DFA.unpack("\1\126"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\17\23\1\127\12\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\140"),NEWLINE DFA.unpack("\1\141"),NEWLINE DFA.unpack("\1\142"),NEWLINE DFA.unpack("\1\143"),NEWLINE DFA.unpack("\1\144"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\146"),NEWLINE DFA.unpack("\1\147"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\151"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\152"),NEWLINE DFA.unpack("\1\153"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\156"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\160"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\161"),NEWLINE DFA.unpack("\1\162"),NEWLINE DFA.unpack("\1\163"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\164"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\165"),NEWLINE DFA.unpack("\1\166"),NEWLINE DFA.unpack("\1\167"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\172"),NEWLINE DFA.unpack("\1\173"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack("\1\23\13\uffff\12\23\7\uffff\32\23\4\uffff\1\23\1\uffff"NEWLINE "\32\23"),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack(""),NEWLINE DFA.unpack("")NEWLINE ]NEWLINENEWLINENEWLINENEWLINE class DFA16(DFA):NEWLINE def specialStateTransition(self_, s, input):NEWLINENEWLINENEWLINENEWLINENEWLINENEWLINE self = self_.recognizerNEWLINENEWLINE _s = sNEWLINENEWLINE if s == 0:NEWLINE LA16_18 = input.LA(1)NEWLINENEWLINE s = -1NEWLINE if ((0 <= LA16_18 <= 65535)):NEWLINE s = 58NEWLINENEWLINE else:NEWLINE s = 57NEWLINENEWLINE if s >= 0:NEWLINE return sNEWLINENEWLINE nvae = NoViableAltException(self_.getDescription(), 16, _s, input)NEWLINE self_.error(nvae)NEWLINE raise nvaeNEWLINENEWLINENEWLINENEWLINENEWLINEdef main(argv, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):NEWLINE from google.appengine._internal.antlr3.main import LexerMainNEWLINE main = LexerMain(ExpressionLexer)NEWLINE main.stdin = stdinNEWLINE main.stdout = stdoutNEWLINE main.stderr = stderrNEWLINE main.execute(argv)NEWLINENEWLINENEWLINEif __name__ == '__main__':NEWLINE main(sys.argv)NEWLINE
import pytestNEWLINEimport mockNEWLINEimport jsonNEWLINEfrom functools import wrapsNEWLINEfrom unittest.mock import patchNEWLINENEWLINEfrom app import storageNEWLINEfrom data.registry_model.blobuploader import upload_blob, BlobUploadSettingsNEWLINEfrom image.docker.schema2.manifest import DockerSchema2ManifestBuilderNEWLINEfrom data.registry_model import registry_modelNEWLINEfrom data.registry_model.datatypes import RepositoryReferenceNEWLINEfrom data.model.test.test_repo_mirroring import create_mirror_repo_robotNEWLINEfrom data.model.user import retrieve_robot_tokenNEWLINEfrom data.database import Manifest, RepoMirrorConfig, RepoMirrorStatusNEWLINENEWLINEfrom workers.repomirrorworker import delete_obsolete_tagsNEWLINEfrom workers.repomirrorworker.repomirrorworker import RepoMirrorWorkerNEWLINEfrom io import BytesIONEWLINEfrom util.repomirror.skopeomirror import SkopeoResults, SkopeoMirrorNEWLINENEWLINEfrom test.fixtures import *NEWLINENEWLINENEWLINEdef disable_existing_mirrors(func):NEWLINE @wraps(func)NEWLINE def wrapper(*args, **kwargs):NEWLINE for mirror in RepoMirrorConfig.select():NEWLINE mirror.is_enabled = FalseNEWLINE mirror.save()NEWLINENEWLINE func(*args, **kwargs)NEWLINENEWLINE for mirror in RepoMirrorConfig.select():NEWLINE mirror.is_enabled = TrueNEWLINE mirror.save()NEWLINENEWLINE return wrapperNEWLINENEWLINENEWLINEdef _create_tag(repo, name):NEWLINE repo_ref = RepositoryReference.for_repo_obj(repo)NEWLINENEWLINE with upload_blob(repo_ref, storage, BlobUploadSettings(500, 500)) as upload:NEWLINE app_config = {"TESTING": True}NEWLINE config_json = json.dumps(NEWLINE {NEWLINE "config": {NEWLINE "author": "Repo Mirror",NEWLINE },NEWLINE "rootfs": {"type": "layers", "diff_ids": []},NEWLINE "history": [NEWLINE {NEWLINE "created": "2019-07-30T18:37:09.284840891Z",NEWLINE "created_by": "base",NEWLINE "author": "Repo Mirror",NEWLINE },NEWLINE ],NEWLINE }NEWLINE )NEWLINE upload.upload_chunk(app_config, BytesIO(config_json.encode("utf-8")))NEWLINE blob = upload.commit_to_blob(app_config)NEWLINE assert blobNEWLINENEWLINE builder = DockerSchema2ManifestBuilder()NEWLINE builder.set_config_digest(blob.digest, blob.compressed_size)NEWLINE builder.add_layer("sha256:abcd", 1234, urls=["http://hello/world"])NEWLINE manifest = builder.build()NEWLINENEWLINE manifest, tag = registry_model.create_manifest_and_retarget_tag(NEWLINE repo_ref, manifest, name, storage, raise_on_error=TrueNEWLINE )NEWLINE assert tagNEWLINE assert tag.name == nameNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_mirror(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(NEWLINE ["latest", "7.1"], external_registry_config={"verify_tls": False}NEWLINE )NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=False",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=False",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_mirror_unsigned_images(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Test whether the insecure-policy option is added when a repository is passed with unsigned_images.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(NEWLINE ["latest"], external_registry_config={"verify_tls": False, "unsigned_images": True}NEWLINE )NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=False",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--insecure-policy",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=False",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_disabled_sync_now(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Disabled mirrors still allow "sync now".NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.is_enabled = FalseNEWLINE mirror.sync_status = RepoMirrorStatus.SYNC_NOWNEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_successful_mirror_verbose_logs(run_skopeo_mock, initialized_db, app, monkeypatch):NEWLINE """NEWLINE Basic test of successful mirror with verbose logs turned on.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE monkeypatch.setenv("DEBUGLOG", "true")NEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINE@mock.patch("workers.repomirrorworker.retarget_tag")NEWLINE@mock.patch("workers.repomirrorworker.delete_tag")NEWLINEdef test_rollback(delete_tag_mock, retarget_tag_mock, run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Tags in the repo:NEWLINENEWLINE "updated" - this tag will be updated during the mirrorNEWLINE "removed" - this tag will be removed during the mirrorNEWLINE "created" - this tag will be created during the mirrorNEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["updated", "created", "zzerror"])NEWLINE _create_tag(repo, "updated")NEWLINE _create_tag(repo, "deleted")NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:updated",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE True, [], '{"RepoTags": ["latest", "zzerror", "created", "updated"]}', ""NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:created",NEWLINE "docker://localhost:5000/mirror/repo:created",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:updated",NEWLINE "docker://localhost:5000/mirror/repo:updated",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:zzerror",NEWLINE "docker://localhost:5000/mirror/repo:zzerror",NEWLINE ],NEWLINE "results": SkopeoResults(False, [], "", "ERROR"),NEWLINE },NEWLINE ]NEWLINENEWLINE retarget_tag_calls = [NEWLINE "updated",NEWLINE ]NEWLINENEWLINE delete_tag_calls = [NEWLINE "deleted",NEWLINE "updated",NEWLINE "created",NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE if args[1] == "copy" and args[8].endswith(":updated"):NEWLINE _create_tag(repo, "updated")NEWLINE elif args[1] == "copy" and args[8].endswith(":created"):NEWLINE _create_tag(repo, "created")NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE def retarget_tag_test(name, manifest, is_reversion=False):NEWLINE assert retarget_tag_calls.pop(0) == nameNEWLINE assert is_reversionNEWLINENEWLINE def delete_tag_test(repository_id, tag_name):NEWLINE assert delete_tag_calls.pop(0) == tag_nameNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINE retarget_tag_mock.side_effect = retarget_tag_testNEWLINE delete_tag_mock.side_effect = delete_tag_testNEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINE assert [] == retarget_tag_callsNEWLINE assert [] == delete_tag_callsNEWLINENEWLINENEWLINEdef test_remove_obsolete_tags(initialized_db):NEWLINE """NEWLINE As part of the mirror, the set of tags on the remote repository is compared to the localNEWLINE existing tags.NEWLINENEWLINE Those not present on the remote are removed locally.NEWLINE """NEWLINENEWLINE mirror, repository = create_mirror_repo_robot(["updated", "created"], repo_name="removed")NEWLINENEWLINE _create_tag(repository, "oldtag")NEWLINENEWLINE incoming_tags = ["one", "two"]NEWLINE deleted_tags = delete_obsolete_tags(mirror, incoming_tags)NEWLINENEWLINE assert [tag.name for tag in deleted_tags] == ["oldtag"]NEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_mirror_config_server_hostname(run_skopeo_mock, initialized_db, app, monkeypatch):NEWLINE """NEWLINE Set REPO_MIRROR_SERVER_HOSTNAME to override SERVER_HOSTNAME config.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "--debug",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE "docker://config_server_hostname/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "Success", ""),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE monkeypatch.setenv("DEBUGLOG", "true")NEWLINE with patch.dict(NEWLINE "data.model.config.app_config", {"REPO_MIRROR_SERVER_HOSTNAME": "config_server_hostname"}NEWLINE ):NEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_quote_params(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.external_reference = "& rm -rf /;/namespace/repository"NEWLINE mirror.external_registry_username = "`rm -rf /`"NEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "--creds",NEWLINE "`rm -rf /`",NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "--src-creds",NEWLINE "`rm -rf /`",NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_quote_params_password(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Basic test of successful mirror.NEWLINE """NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["latest", "7.1"])NEWLINE mirror.external_reference = "& rm -rf /;/namespace/repository"NEWLINE mirror.external_registry_username = "`rm -rf /`"NEWLINE mirror.external_registry_password = '""$PATH\\"'NEWLINE mirror.save()NEWLINENEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "--creds",NEWLINE '`rm -rf /`:""$PATH\\"',NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], '{"RepoTags": ["latest"]}', ""),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "copy",NEWLINE "--all",NEWLINE "--remove-signatures",NEWLINE "--src-tls-verify=True",NEWLINE "--dest-tls-verify=True",NEWLINE "--dest-creds",NEWLINE "%s:%s"NEWLINE % (mirror.internal_robot.username, retrieve_robot_token(mirror.internal_robot)),NEWLINE "--src-creds",NEWLINE '`rm -rf /`:""$PATH\\"',NEWLINE "'docker://& rm -rf /;/namespace/repository:latest'",NEWLINE "docker://localhost:5000/mirror/repo:latest",NEWLINE ],NEWLINE "results": SkopeoResults(True, [], "stdout", "stderr"),NEWLINE },NEWLINE ]NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINENEWLINE worker = RepoMirrorWorker()NEWLINE worker._process_mirrors()NEWLINENEWLINE assert [] == skopeo_callsNEWLINENEWLINENEWLINE@disable_existing_mirrorsNEWLINE@mock.patch("util.repomirror.skopeomirror.SkopeoMirror.run_skopeo")NEWLINEdef test_inspect_error_mirror(run_skopeo_mock, initialized_db, app):NEWLINE """NEWLINE Test for no tag for skopeo inspect.NEWLINENEWLINE The mirror is processed four times, asserting that the remaining syncs decrement until next syncNEWLINE is bumped to the future, confirming the fourth is never processed.NEWLINE """NEWLINENEWLINE def skopeo_test(args, proxy):NEWLINE try:NEWLINE skopeo_call = skopeo_calls.pop(0)NEWLINE assert args == skopeo_call["args"]NEWLINE assert proxy == {}NEWLINENEWLINE return skopeo_call["results"]NEWLINE except Exception as e:NEWLINE skopeo_calls.append(skopeo_call)NEWLINE raise eNEWLINENEWLINE run_skopeo_mock.side_effect = skopeo_testNEWLINE worker = RepoMirrorWorker()NEWLINENEWLINE mirror, repo = create_mirror_repo_robot(["7.1"])NEWLINENEWLINE # Call number 1NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 2 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 2NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 1 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 3NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert [] == skopeo_callsNEWLINE assert 3 == mirror.sync_retries_remainingNEWLINENEWLINE # Call number 4NEWLINE skopeo_calls = [NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:7.1",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest 7.1 in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE {NEWLINE "args": [NEWLINE "/usr/bin/skopeo",NEWLINE "inspect",NEWLINE "--tls-verify=True",NEWLINE "docker://registry.example.com/namespace/repository:latest",NEWLINE ],NEWLINE "results": SkopeoResults(NEWLINE False,NEWLINE [],NEWLINE "",NEWLINE 'time="2019-09-18T13:29:40Z" level=fatal msg="Error reading manifest latest in registry.example.com/namespace/repository: manifest unknown: manifest unknown"',NEWLINE ),NEWLINE },NEWLINE ]NEWLINE worker._process_mirrors()NEWLINE mirror = RepoMirrorConfig.get_by_id(mirror.id)NEWLINE assert 2 == len(skopeo_calls)NEWLINE assert 3 == mirror.sync_retries_remainingNEWLINE
import torchNEWLINEimport loggingNEWLINENEWLINEimport models.modules.UNet_arch as UNet_archNEWLINElogger = logging.getLogger('base')NEWLINENEWLINENEWLINE####################NEWLINE# define networkNEWLINE####################NEWLINE#### GeneratorNEWLINEdef define_G(opt):NEWLINE opt_net = opt['network_G']NEWLINE which_model = opt_net['which_model_G']NEWLINENEWLINE if which_model == 'HDRUNet':NEWLINE netG = UNet_arch.HDRUNet(in_nc=opt_net['in_nc'], out_nc=opt_net['out_nc'], nf=opt_net['nf'], act_type=opt_net['act_type'])NEWLINE else:NEWLINE raise NotImplementedError('Generator model [{:s}] not recognized'.format(which_model))NEWLINE return netG
# Project: hardInfoNEWLINE# Author: George Keith WatsonNEWLINE# Date Started: March 18, 2022NEWLINE# Copyright: (c) Copyright 2022 George Keith WatsonNEWLINE# Module: model/Installation.pyNEWLINE# Date Started: March 20, 2022NEWLINE# Purpose: Store installation location and other local details.NEWLINE# Development:NEWLINE# To run this program locally having decompressed the source archive without errors,NEWLINE# certain constants in this file must be changed.NEWLINE# INSTALLATION_FOLDER must be the folder that hardInfo.py is located in. This will be the rootNEWLINE# of the source tree.NEWLINE#NEWLINENEWLINEDATA_FOLDER = "/home/keithcollins/PycharmProjects/CommonData/"NEWLINEINSTALLATION_FOLDER = '/home/keithcollins/PycharmProjects/hardInfo/'NEWLINELSHW_JSON_FILE = 'lshw.json'NEWLINE
import numpy as np # linear algebraNEWLINEimport pandas as pd # data processingNEWLINEimport datetime as dt # date and time processing functionsNEWLINEimport matplotlib.pyplot as plt # basic plotting NEWLINEimport matplotlib.dates as mdates # date processing in matplotlibNEWLINEfrom matplotlib.offsetbox import AnchoredTextNEWLINEimport mpld3NEWLINEplt.style.use('ggplot') # use ggplot styleNEWLINENEWLINE# read in the data from the provided csv fileNEWLINEdf = pd.read_csv('./static/seaice.csv')NEWLINENEWLINE# drop the 'Source Data' column as it obscures more useful columns and doesn't tell us muchNEWLINEdf.drop('Source Data', axis = 1, inplace=True)NEWLINENEWLINE# convert the provided 3 column date format to datetime format and set it as the indexNEWLINEdf['Date'] = pd.to_datetime(df[['Year','Month','Day']])NEWLINEdf.index = df['Date'].valuesNEWLINENEWLINE# split according to hemisphere, as we are expecting different trends for eachNEWLINEnorth = df[df['hemisphere'] == 'north']NEWLINEsouth = df[df['hemisphere'] == 'south']NEWLINENEWLINEdef dailyExtent():NEWLINE fig = plt.figure(figsize=(9,6))NEWLINE plt.subplot(2, 1, 1)NEWLINE plt.plot(north.index,north['Extent'], label='Northern Hemisphere')NEWLINE plt.plot(south.index,south['Extent'], label='Southern Hemisphere')NEWLINENEWLINE # add plot legend and titlesNEWLINE plt.legend(bbox_to_anchor=(0., -.362, 1., .102), loc=3, ncol=2, NEWLINE mode="expand", borderaxespad=0.)NEWLINE plt.ylabel('Sea ice extent (10^6 sq km)')NEWLINE plt.xlabel('Date')NEWLINE plt.title('Daily sea-ice extent');NEWLINE # saving to htmlNEWLINE save_html("dailyextent", fig)NEWLINENEWLINEdef annualAverage():NEWLINE # resample raw data into annual averagesNEWLINE northyear = north.resample('12M').mean()NEWLINE southyear = south.resample('12M').mean()NEWLINENEWLINE # remove the initial and final item as they aer averaged incorrectly (also indexes seem bad)NEWLINE northyear = northyear[1:-1]NEWLINE southyear = southyear[1:-1]NEWLINENEWLINE fig = plt.figure(figsize=(9,6))NEWLINE plt.subplot(2, 1, 1)NEWLINE plt.plot(northyear.index,northyear['Extent'], marker = '.', label='Northern Hemisphere')NEWLINE plt.plot(southyear.index,southyear['Extent'], marker = '.', label='Southern Hemisphere')NEWLINENEWLINE # add plot legend and titlesNEWLINE plt.legend(bbox_to_anchor=(0., -.362, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)NEWLINE plt.ylabel('Sea ice extent (10^6 sq km)')NEWLINE plt.xlabel('Date')NEWLINE plt.title('Annual average sea-ice extent')NEWLINE # saving to htmlNEWLINE save_html("annualaverage", fig)NEWLINENEWLINEdef annualChange():NEWLINE # define date range to plot betweenNEWLINE start = 1978NEWLINE end = dt.datetime.now().year + 1NEWLINENEWLINE # define plotNEWLINE f, axarr = plt.subplots(2, sharex=True, figsize=(9,5))NEWLINENEWLINENEWLINE # organise plot axes (set x axis to months only and cycle colours according to gradient)NEWLINE month_fmt = mdates.DateFormatter('%b')NEWLINE axarr[0].xaxis.set_major_formatter(month_fmt)NEWLINE axarr[0].set_prop_cycle(plt.cycler('color', NEWLINE plt.cm.winter(np.linspace(0, 1, len(range(start, end))))))NEWLINE axarr[1].set_prop_cycle(plt.cycler('color', NEWLINE plt.cm.winter(np.linspace(0, 1, len(range(start, end))))))NEWLINENEWLINE # add plot legend and titlesNEWLINE axarr[0].set_ylabel('Sea ice extent (10^6 sq km)')NEWLINE axarr[1].set_ylabel('Sea ice extent (10^6 sq km)')NEWLINE axarr[0].set_xlabel('Month (NORTHERN HERMISPHERE)')NEWLINE axarr[1].set_xlabel('Month (SOUTHERN HERMISPHERE)')NEWLINE axarr[0].set_title('Annual change in sea-ice extent');NEWLINE axarr[0].add_artist(AnchoredText('Northern Hemisphere', loc=3))NEWLINE axarr[1].add_artist(AnchoredText('Southern Hemisphere', loc=2))NEWLINENEWLINE # loop for every year between the start year and currentNEWLINE for year in range(start, end):NEWLINE # create new dataframe for each year, NEWLINE # and set the year to 1972 so all are plotted on the same axisNEWLINE nyeardf = north[['Extent', 'Day', 'Month']][north['Year'] == year]NEWLINE nyeardf['Year'] = 1972NEWLINE nyeardf['Date'] = pd.to_datetime(nyeardf[['Year','Month','Day']])NEWLINE nyeardf.index = nyeardf['Date'].valuesNEWLINE NEWLINE syeardf = south[['Extent', 'Day', 'Month']][south['Year'] == year]NEWLINE syeardf['Year'] = 1972NEWLINE syeardf['Date'] = pd.to_datetime(syeardf[['Year','Month','Day']])NEWLINE syeardf.index = syeardf['Date'].valuesNEWLINE NEWLINE # plot each year individuallyNEWLINE axarr[0].plot(nyeardf.index,nyeardf['Extent'], label = year)NEWLINE axarr[1].plot(syeardf.index,syeardf['Extent'])NEWLINE save_html("annualchange", f)NEWLINENEWLINEdef save_html(filename, fig):NEWLINE # saving to htmlNEWLINE html_str = mpld3.fig_to_html(fig)NEWLINE Html_file= open("./templates/{}.html".format(filename),"w")NEWLINE Html_file.write(html_str)NEWLINE Html_file.close()
# uncompyle6 version 3.3.1NEWLINE# Python bytecode 3.6 (3379)NEWLINE# Decompiled from: Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) NEWLINE# [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]NEWLINE# Embedded file name: ../../shared/problems/CR/problem1050_CR.pyNEWLINE# Compiled at: 2019-03-12 17:52:21NEWLINE# Size of source mod 2**32: 1123 bytesNEWLINE__author__ = 'patras'NEWLINEfrom domain_chargeableRobot import *NEWLINEfrom timer import DURATIONNEWLINEfrom state import stateNEWLINEDURATION.TIME = {'put':5, NEWLINE 'take':5, NEWLINE 'perceive':3, NEWLINE 'charge':10, NEWLINE 'move':10, NEWLINE 'moveToEmergency':20, NEWLINE 'moveCharger':15, NEWLINE 'addressEmergency':20, NEWLINE 'wait':10}NEWLINEDURATION.COUNTER = {'put':5, NEWLINE 'take':5, NEWLINE 'perceive':3, NEWLINE 'charge':10, NEWLINE 'move':10, NEWLINE 'moveToEmergency':20, NEWLINE 'moveCharger':15, NEWLINE 'addressEmergency':20, NEWLINE 'wait':10}NEWLINErv.LOCATIONS = [NEWLINE 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]NEWLINErv.EDGES = {1:[2], 2:[1, 3], 3:[2, 4], 4:[5, 3, 6, 7], 5:[4, 9], 6:[4, 10], 7:[4, 8], 8:[7], 9:[5], 10:[6]}NEWLINErv.OBJECTS = ['o1']NEWLINErv.ROBOTS = [NEWLINE 'r1']NEWLINENEWLINEdef ResetState():NEWLINE state.loc = {'r1': 1}NEWLINE state.charge = {'r1': 3}NEWLINE state.load = {'r1': NIL}NEWLINE state.pos = {'c1':1, 'o1':9}NEWLINE state.containers = {1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:['o1'], 10:[]}NEWLINE state.emergencyHandling = {'r1':False, 'r2':False}NEWLINE state.view = {}NEWLINE for l in rv.LOCATIONS:NEWLINE state.view[l] = FalseNEWLINENEWLINENEWLINEtasks = {4: [['fetch', 'r1', 'o1']]}NEWLINEeventsEnv = {}NEWLINE# okay decompiling __pycache__/problem1050_CR.cpython-36.pycNEWLINE
from __future__ import annotationsNEWLINENEWLINEfrom typing import (NEWLINE TYPE_CHECKING,NEWLINE Callable,NEWLINE Dict,NEWLINE Hashable,NEWLINE List,NEWLINE Optional,NEWLINE Sequence,NEWLINE Set,NEWLINE Tuple,NEWLINE Union,NEWLINE cast,NEWLINE)NEWLINENEWLINEimport numpy as npNEWLINENEWLINEfrom pandas._typing import (NEWLINE AggFuncType,NEWLINE AggFuncTypeBase,NEWLINE AggFuncTypeDict,NEWLINE FrameOrSeriesUnion,NEWLINE IndexLabel,NEWLINE)NEWLINEfrom pandas.util._decorators import (NEWLINE Appender,NEWLINE Substitution,NEWLINE)NEWLINENEWLINEfrom pandas.core.dtypes.cast import maybe_downcast_to_dtypeNEWLINEfrom pandas.core.dtypes.common import (NEWLINE is_integer_dtype,NEWLINE is_list_like,NEWLINE is_scalar,NEWLINE)NEWLINEfrom pandas.core.dtypes.generic import (NEWLINE ABCDataFrame,NEWLINE ABCSeries,NEWLINE)NEWLINENEWLINEimport pandas.core.common as comNEWLINEfrom pandas.core.frame import _shared_docsNEWLINEfrom pandas.core.groupby import GrouperNEWLINEfrom pandas.core.indexes.api import (NEWLINE Index,NEWLINE MultiIndex,NEWLINE get_objs_combined_axis,NEWLINE)NEWLINEfrom pandas.core.reshape.concat import concatNEWLINEfrom pandas.core.reshape.util import cartesian_productNEWLINEfrom pandas.core.series import SeriesNEWLINENEWLINEif TYPE_CHECKING:NEWLINE from pandas import DataFrameNEWLINENEWLINENEWLINE# Note: We need to make sure `frame` is imported before `pivot`, otherwiseNEWLINE# _shared_docs['pivot_table'] will not yet exist. TODO: Fix this dependencyNEWLINE@Substitution("\ndata : DataFrame")NEWLINE@Appender(_shared_docs["pivot_table"], indents=1)NEWLINEdef pivot_table(NEWLINE data: DataFrame,NEWLINE values=None,NEWLINE index=None,NEWLINE columns=None,NEWLINE aggfunc: AggFuncType = "mean",NEWLINE fill_value=None,NEWLINE margins=False,NEWLINE dropna=True,NEWLINE margins_name="All",NEWLINE observed=False,NEWLINE) -> DataFrame:NEWLINE index = _convert_by(index)NEWLINE columns = _convert_by(columns)NEWLINENEWLINE if isinstance(aggfunc, list):NEWLINE pieces: List[DataFrame] = []NEWLINE keys = []NEWLINE for func in aggfunc:NEWLINE _table = __internal_pivot_table(NEWLINE data,NEWLINE values=values,NEWLINE index=index,NEWLINE columns=columns,NEWLINE fill_value=fill_value,NEWLINE aggfunc=func,NEWLINE margins=margins,NEWLINE dropna=dropna,NEWLINE margins_name=margins_name,NEWLINE observed=observed,NEWLINE )NEWLINE pieces.append(_table)NEWLINE keys.append(getattr(func, "__name__", func))NEWLINENEWLINE table = concat(pieces, keys=keys, axis=1)NEWLINE return table.__finalize__(data, method="pivot_table")NEWLINENEWLINE table = __internal_pivot_table(NEWLINE data,NEWLINE values,NEWLINE index,NEWLINE columns,NEWLINE aggfunc,NEWLINE fill_value,NEWLINE margins,NEWLINE dropna,NEWLINE margins_name,NEWLINE observed,NEWLINE )NEWLINE return table.__finalize__(data, method="pivot_table")NEWLINENEWLINENEWLINEdef __internal_pivot_table(NEWLINE data: DataFrame,NEWLINE values,NEWLINE index,NEWLINE columns,NEWLINE aggfunc: Union[AggFuncTypeBase, AggFuncTypeDict],NEWLINE fill_value,NEWLINE margins: bool,NEWLINE dropna: bool,NEWLINE margins_name: str,NEWLINE observed: bool,NEWLINE) -> DataFrame:NEWLINE """NEWLINE Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.NEWLINE """NEWLINE keys = index + columnsNEWLINENEWLINE values_passed = values is not NoneNEWLINE if values_passed:NEWLINE if is_list_like(values):NEWLINE values_multi = TrueNEWLINE values = list(values)NEWLINE else:NEWLINE values_multi = FalseNEWLINE values = [values]NEWLINENEWLINE # GH14938 Make sure value labels are in dataNEWLINE for i in values:NEWLINE if i not in data:NEWLINE raise KeyError(i)NEWLINENEWLINE to_filter = []NEWLINE for x in keys + values:NEWLINE if isinstance(x, Grouper):NEWLINE x = x.keyNEWLINE try:NEWLINE if x in data:NEWLINE to_filter.append(x)NEWLINE except TypeError:NEWLINE passNEWLINE if len(to_filter) < len(data.columns):NEWLINE data = data[to_filter]NEWLINENEWLINE else:NEWLINE values = data.columnsNEWLINE for key in keys:NEWLINE try:NEWLINE values = values.drop(key)NEWLINE except (TypeError, ValueError, KeyError):NEWLINE passNEWLINE values = list(values)NEWLINENEWLINE grouped = data.groupby(keys, observed=observed)NEWLINE agged = grouped.agg(aggfunc)NEWLINE if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):NEWLINE agged = agged.dropna(how="all")NEWLINENEWLINE # gh-21133NEWLINE # we want to down cast ifNEWLINE # the original values are intsNEWLINE # as we grouped with a NaN valueNEWLINE # and then dropped, coercing to floatsNEWLINE for v in values:NEWLINE if (NEWLINE v in dataNEWLINE and is_integer_dtype(data[v])NEWLINE and v in aggedNEWLINE and not is_integer_dtype(agged[v])NEWLINE ):NEWLINE agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)NEWLINENEWLINE table = aggedNEWLINENEWLINE # GH17038, this check should only happen if index is defined (not None)NEWLINE if table.index.nlevels > 1 and index:NEWLINE # Related GH #17123NEWLINE # If index_names are integers, determine whether the integers referNEWLINE # to the level position or name.NEWLINE index_names = agged.index.names[: len(index)]NEWLINE to_unstack = []NEWLINE for i in range(len(index), len(keys)):NEWLINE name = agged.index.names[i]NEWLINE if name is None or name in index_names:NEWLINE to_unstack.append(i)NEWLINE else:NEWLINE to_unstack.append(name)NEWLINE table = agged.unstack(to_unstack)NEWLINENEWLINE if not dropna:NEWLINE if isinstance(table.index, MultiIndex):NEWLINE m = MultiIndex.from_arrays(NEWLINE cartesian_product(table.index.levels), names=table.index.namesNEWLINE )NEWLINE table = table.reindex(m, axis=0)NEWLINENEWLINE if isinstance(table.columns, MultiIndex):NEWLINE m = MultiIndex.from_arrays(NEWLINE cartesian_product(table.columns.levels), names=table.columns.namesNEWLINE )NEWLINE table = table.reindex(m, axis=1)NEWLINENEWLINE if isinstance(table, ABCDataFrame):NEWLINE table = table.sort_index(axis=1)NEWLINENEWLINE if fill_value is not None:NEWLINE _table = table.fillna(fill_value, downcast="infer")NEWLINE assert _table is not None # needed for mypyNEWLINE table = _tableNEWLINENEWLINE if margins:NEWLINE if dropna:NEWLINE data = data[data.notna().all(axis=1)]NEWLINE table = _add_margins(NEWLINE table,NEWLINE data,NEWLINE values,NEWLINE rows=index,NEWLINE cols=columns,NEWLINE aggfunc=aggfunc,NEWLINE observed=dropna,NEWLINE margins_name=margins_name,NEWLINE fill_value=fill_value,NEWLINE )NEWLINENEWLINE # discard the top levelNEWLINE if values_passed and not values_multi and table.columns.nlevels > 1:NEWLINE table = table.droplevel(0, axis=1)NEWLINE if len(index) == 0 and len(columns) > 0:NEWLINE table = table.TNEWLINENEWLINE # GH 15193 Make sure empty columns are removed if dropna=TrueNEWLINE if isinstance(table, ABCDataFrame) and dropna:NEWLINE table = table.dropna(how="all", axis=1)NEWLINENEWLINE return tableNEWLINENEWLINENEWLINEdef _add_margins(NEWLINE table: FrameOrSeriesUnion,NEWLINE data,NEWLINE values,NEWLINE rows,NEWLINE cols,NEWLINE aggfunc,NEWLINE observed=None,NEWLINE margins_name: str = "All",NEWLINE fill_value=None,NEWLINE):NEWLINE if not isinstance(margins_name, str):NEWLINE raise ValueError("margins_name argument must be a string")NEWLINENEWLINE msg = f'Conflicting name "{margins_name}" in margins'NEWLINE for level in table.index.names:NEWLINE if margins_name in table.index.get_level_values(level):NEWLINE raise ValueError(msg)NEWLINENEWLINE grand_margin = _compute_grand_margin(data, values, aggfunc, margins_name)NEWLINENEWLINE if table.ndim == 2:NEWLINE # i.e. DataFrameNEWLINE for level in table.columns.names[1:]:NEWLINE if margins_name in table.columns.get_level_values(level):NEWLINE raise ValueError(msg)NEWLINENEWLINE key: Union[str, Tuple[str, ...]]NEWLINE if len(rows) > 1:NEWLINE key = (margins_name,) + ("",) * (len(rows) - 1)NEWLINE else:NEWLINE key = margins_nameNEWLINENEWLINE if not values and isinstance(table, ABCSeries):NEWLINE # If there are no values and the table is a series, then there is onlyNEWLINE # one column in the data. Compute grand margin and return it.NEWLINE return table.append(Series({key: grand_margin[margins_name]}))NEWLINENEWLINE elif values:NEWLINE marginal_result_set = _generate_marginal_results(NEWLINE table, data, values, rows, cols, aggfunc, observed, margins_nameNEWLINE )NEWLINE if not isinstance(marginal_result_set, tuple):NEWLINE return marginal_result_setNEWLINE result, margin_keys, row_margin = marginal_result_setNEWLINE else:NEWLINE # no values, and table is a DataFrameNEWLINE assert isinstance(table, ABCDataFrame)NEWLINE marginal_result_set = _generate_marginal_results_without_values(NEWLINE table, data, rows, cols, aggfunc, observed, margins_nameNEWLINE )NEWLINE if not isinstance(marginal_result_set, tuple):NEWLINE return marginal_result_setNEWLINE result, margin_keys, row_margin = marginal_result_setNEWLINENEWLINE row_margin = row_margin.reindex(result.columns, fill_value=fill_value)NEWLINE # populate grand marginNEWLINE for k in margin_keys:NEWLINE if isinstance(k, str):NEWLINE row_margin[k] = grand_margin[k]NEWLINE else:NEWLINE row_margin[k] = grand_margin[k[0]]NEWLINENEWLINE from pandas import DataFrameNEWLINENEWLINE margin_dummy = DataFrame(row_margin, columns=[key]).TNEWLINENEWLINE row_names = result.index.namesNEWLINE # check the result column and leave floatsNEWLINE for dtype in set(result.dtypes):NEWLINE cols = result.select_dtypes([dtype]).columnsNEWLINE margin_dummy[cols] = margin_dummy[cols].apply(NEWLINE maybe_downcast_to_dtype, args=(dtype,)NEWLINE )NEWLINE result = result.append(margin_dummy)NEWLINE result.index.names = row_namesNEWLINENEWLINE return resultNEWLINENEWLINENEWLINEdef _compute_grand_margin(data, values, aggfunc, margins_name: str = "All"):NEWLINENEWLINE if values:NEWLINE grand_margin = {}NEWLINE for k, v in data[values].items():NEWLINE try:NEWLINE if isinstance(aggfunc, str):NEWLINE grand_margin[k] = getattr(v, aggfunc)()NEWLINE elif isinstance(aggfunc, dict):NEWLINE if isinstance(aggfunc[k], str):NEWLINE grand_margin[k] = getattr(v, aggfunc[k])()NEWLINE else:NEWLINE grand_margin[k] = aggfunc[k](v)NEWLINE else:NEWLINE grand_margin[k] = aggfunc(v)NEWLINE except TypeError:NEWLINE passNEWLINE return grand_marginNEWLINE else:NEWLINE return {margins_name: aggfunc(data.index)}NEWLINENEWLINENEWLINEdef _generate_marginal_results(NEWLINE table, data, values, rows, cols, aggfunc, observed, margins_name: str = "All"NEWLINE):NEWLINE if len(cols) > 0:NEWLINE # need to "interleave" the marginsNEWLINE table_pieces = []NEWLINE margin_keys = []NEWLINENEWLINE def _all_key(key):NEWLINE return (key, margins_name) + ("",) * (len(cols) - 1)NEWLINENEWLINE if len(rows) > 0:NEWLINE margin = data[rows + values].groupby(rows, observed=observed).agg(aggfunc)NEWLINE cat_axis = 1NEWLINENEWLINE for key, piece in table.groupby(level=0, axis=cat_axis, observed=observed):NEWLINE all_key = _all_key(key)NEWLINENEWLINE # we are going to mutate this, so need to copy!NEWLINE piece = piece.copy()NEWLINE piece[all_key] = margin[key]NEWLINENEWLINE table_pieces.append(piece)NEWLINE margin_keys.append(all_key)NEWLINE else:NEWLINE from pandas import DataFrameNEWLINENEWLINE cat_axis = 0NEWLINE for key, piece in table.groupby(level=0, axis=cat_axis, observed=observed):NEWLINE if len(cols) > 1:NEWLINE all_key = _all_key(key)NEWLINE else:NEWLINE all_key = margins_nameNEWLINE table_pieces.append(piece)NEWLINE # GH31016 this is to calculate margin for each group, and assignNEWLINE # corresponded key as indexNEWLINE transformed_piece = DataFrame(piece.apply(aggfunc)).TNEWLINE transformed_piece.index = Index([all_key], name=piece.index.name)NEWLINENEWLINE # append piece for margin into table_pieceNEWLINE table_pieces.append(transformed_piece)NEWLINE margin_keys.append(all_key)NEWLINENEWLINE result = concat(table_pieces, axis=cat_axis)NEWLINENEWLINE if len(rows) == 0:NEWLINE return resultNEWLINE else:NEWLINE result = tableNEWLINE margin_keys = table.columnsNEWLINENEWLINE if len(cols) > 0:NEWLINE row_margin = data[cols + values].groupby(cols, observed=observed).agg(aggfunc)NEWLINE row_margin = row_margin.stack()NEWLINENEWLINE # slight hackNEWLINE new_order = [len(cols)] + list(range(len(cols)))NEWLINE row_margin.index = row_margin.index.reorder_levels(new_order)NEWLINE else:NEWLINE row_margin = Series(np.nan, index=result.columns)NEWLINENEWLINE return result, margin_keys, row_marginNEWLINENEWLINENEWLINEdef _generate_marginal_results_without_values(NEWLINE table: DataFrame, data, rows, cols, aggfunc, observed, margins_name: str = "All"NEWLINE):NEWLINE if len(cols) > 0:NEWLINE # need to "interleave" the marginsNEWLINE margin_keys: Union[List, Index] = []NEWLINENEWLINE def _all_key():NEWLINE if len(cols) == 1:NEWLINE return margins_nameNEWLINE return (margins_name,) + ("",) * (len(cols) - 1)NEWLINENEWLINE if len(rows) > 0:NEWLINE margin = data[rows].groupby(rows, observed=observed).apply(aggfunc)NEWLINE all_key = _all_key()NEWLINE table[all_key] = marginNEWLINE result = tableNEWLINE margin_keys.append(all_key)NEWLINENEWLINE else:NEWLINE margin = data.groupby(level=0, axis=0, observed=observed).apply(aggfunc)NEWLINE all_key = _all_key()NEWLINE table[all_key] = marginNEWLINE result = tableNEWLINE margin_keys.append(all_key)NEWLINE return resultNEWLINE else:NEWLINE result = tableNEWLINE margin_keys = table.columnsNEWLINENEWLINE if len(cols):NEWLINE row_margin = data[cols].groupby(cols, observed=observed).apply(aggfunc)NEWLINE else:NEWLINE row_margin = Series(np.nan, index=result.columns)NEWLINENEWLINE return result, margin_keys, row_marginNEWLINENEWLINENEWLINEdef _convert_by(by):NEWLINE if by is None:NEWLINE by = []NEWLINE elif (NEWLINE is_scalar(by)NEWLINE or isinstance(by, (np.ndarray, Index, ABCSeries, Grouper))NEWLINE or hasattr(by, "__call__")NEWLINE ):NEWLINE by = [by]NEWLINE else:NEWLINE by = list(by)NEWLINE return byNEWLINENEWLINENEWLINE@Substitution("\ndata : DataFrame")NEWLINE@Appender(_shared_docs["pivot"], indents=1)NEWLINEdef pivot(NEWLINE data: DataFrame,NEWLINE index: Optional[IndexLabel] = None,NEWLINE columns: Optional[IndexLabel] = None,NEWLINE values: Optional[IndexLabel] = None,NEWLINE) -> DataFrame:NEWLINE if columns is None:NEWLINE raise TypeError("pivot() missing 1 required argument: 'columns'")NEWLINENEWLINE columns = com.convert_to_list_like(columns)NEWLINENEWLINE if values is None:NEWLINE if index is not None:NEWLINE cols = com.convert_to_list_like(index)NEWLINE else:NEWLINE cols = []NEWLINENEWLINE append = index is NoneNEWLINE indexed = data.set_index(cols + columns, append=append)NEWLINE else:NEWLINE if index is None:NEWLINE index = [Series(data.index, name=data.index.name)]NEWLINE else:NEWLINE index = com.convert_to_list_like(index)NEWLINE index = [data[idx] for idx in index]NEWLINENEWLINE data_columns = [data[col] for col in columns]NEWLINE index.extend(data_columns)NEWLINE index = MultiIndex.from_arrays(index)NEWLINENEWLINE if is_list_like(values) and not isinstance(values, tuple):NEWLINE # Exclude tuple because it is seen as a single column nameNEWLINE values = cast(Sequence[Hashable], values)NEWLINE indexed = data._constructor(NEWLINE data[values]._values, index=index, columns=valuesNEWLINE )NEWLINE else:NEWLINE indexed = data._constructor_sliced(data[values]._values, index=index)NEWLINE return indexed.unstack(columns)NEWLINENEWLINENEWLINEdef crosstab(NEWLINE index,NEWLINE columns,NEWLINE values=None,NEWLINE rownames=None,NEWLINE colnames=None,NEWLINE aggfunc=None,NEWLINE margins=False,NEWLINE margins_name: str = "All",NEWLINE dropna: bool = True,NEWLINE normalize=False,NEWLINE) -> DataFrame:NEWLINE """NEWLINE Compute a simple cross tabulation of two (or more) factors. By defaultNEWLINE computes a frequency table of the factors unless an array of values and anNEWLINE aggregation function are passed.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE index : array-like, Series, or list of arrays/SeriesNEWLINE Values to group by in the rows.NEWLINE columns : array-like, Series, or list of arrays/SeriesNEWLINE Values to group by in the columns.NEWLINE values : array-like, optionalNEWLINE Array of values to aggregate according to the factors.NEWLINE Requires `aggfunc` be specified.NEWLINE rownames : sequence, default NoneNEWLINE If passed, must match number of row arrays passed.NEWLINE colnames : sequence, default NoneNEWLINE If passed, must match number of column arrays passed.NEWLINE aggfunc : function, optionalNEWLINE If specified, requires `values` be specified as well.NEWLINE margins : bool, default FalseNEWLINE Add row/column margins (subtotals).NEWLINE margins_name : str, default 'All'NEWLINE Name of the row/column that will contain the totalsNEWLINE when margins is True.NEWLINE dropna : bool, default TrueNEWLINE Do not include columns whose entries are all NaN.NEWLINE normalize : bool, {'all', 'index', 'columns'}, or {0,1}, default FalseNEWLINE Normalize by dividing all values by the sum of values.NEWLINENEWLINE - If passed 'all' or `True`, will normalize over all values.NEWLINE - If passed 'index' will normalize over each row.NEWLINE - If passed 'columns' will normalize over each column.NEWLINE - If margins is `True`, will also normalize margin values.NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE DataFrameNEWLINE Cross tabulation of the data.NEWLINENEWLINE See AlsoNEWLINE --------NEWLINE DataFrame.pivot : Reshape data based on column values.NEWLINE pivot_table : Create a pivot table as a DataFrame.NEWLINENEWLINE NotesNEWLINE -----NEWLINE Any Series passed will have their name attributes used unless row or columnNEWLINE names for the cross-tabulation are specified.NEWLINENEWLINE Any input passed containing Categorical data will have **all** of itsNEWLINE categories included in the cross-tabulation, even if the actual data doesNEWLINE not contain any instances of a particular category.NEWLINENEWLINE In the event that there aren't overlapping indexes an empty DataFrame willNEWLINE be returned.NEWLINENEWLINE ExamplesNEWLINE --------NEWLINE >>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar",NEWLINE ... "bar", "bar", "foo", "foo", "foo"], dtype=object)NEWLINE >>> b = np.array(["one", "one", "one", "two", "one", "one",NEWLINE ... "one", "two", "two", "two", "one"], dtype=object)NEWLINE >>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny",NEWLINE ... "shiny", "dull", "shiny", "shiny", "shiny"],NEWLINE ... dtype=object)NEWLINE >>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])NEWLINE b one twoNEWLINE c dull shiny dull shinyNEWLINE aNEWLINE bar 1 2 1 0NEWLINE foo 2 2 1 2NEWLINENEWLINE Here 'c' and 'f' are not represented in the data and will not beNEWLINE shown in the output because dropna is True by default. SetNEWLINE dropna=False to preserve categories with no data.NEWLINENEWLINE >>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])NEWLINE >>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])NEWLINE >>> pd.crosstab(foo, bar)NEWLINE col_0 d eNEWLINE row_0NEWLINE a 1 0NEWLINE b 0 1NEWLINE >>> pd.crosstab(foo, bar, dropna=False)NEWLINE col_0 d e fNEWLINE row_0NEWLINE a 1 0 0NEWLINE b 0 1 0NEWLINE c 0 0 0NEWLINE """NEWLINE if values is None and aggfunc is not None:NEWLINE raise ValueError("aggfunc cannot be used without values.")NEWLINENEWLINE if values is not None and aggfunc is None:NEWLINE raise ValueError("values cannot be used without an aggfunc.")NEWLINENEWLINE index = com.maybe_make_list(index)NEWLINE columns = com.maybe_make_list(columns)NEWLINENEWLINE common_idx = NoneNEWLINE pass_objs = [x for x in index + columns if isinstance(x, (ABCSeries, ABCDataFrame))]NEWLINE if pass_objs:NEWLINE common_idx = get_objs_combined_axis(pass_objs, intersect=True, sort=False)NEWLINENEWLINE rownames = _get_names(index, rownames, prefix="row")NEWLINE colnames = _get_names(columns, colnames, prefix="col")NEWLINENEWLINE # duplicate names mapped to unique names for pivot opNEWLINE (NEWLINE rownames_mapper,NEWLINE unique_rownames,NEWLINE colnames_mapper,NEWLINE unique_colnames,NEWLINE ) = _build_names_mapper(rownames, colnames)NEWLINENEWLINE from pandas import DataFrameNEWLINENEWLINE data = {NEWLINE **dict(zip(unique_rownames, index)),NEWLINE **dict(zip(unique_colnames, columns)),NEWLINE }NEWLINE df = DataFrame(data, index=common_idx)NEWLINENEWLINE if values is None:NEWLINE df["__dummy__"] = 0NEWLINE kwargs = {"aggfunc": len, "fill_value": 0}NEWLINE else:NEWLINE df["__dummy__"] = valuesNEWLINE kwargs = {"aggfunc": aggfunc}NEWLINENEWLINE table = df.pivot_table(NEWLINE "__dummy__",NEWLINE index=unique_rownames,NEWLINE columns=unique_colnames,NEWLINE margins=margins,NEWLINE margins_name=margins_name,NEWLINE dropna=dropna,NEWLINE **kwargs,NEWLINE )NEWLINENEWLINE # Post-processNEWLINE if normalize is not False:NEWLINE table = _normalize(NEWLINE table, normalize=normalize, margins=margins, margins_name=margins_nameNEWLINE )NEWLINENEWLINE table = table.rename_axis(index=rownames_mapper, axis=0)NEWLINE table = table.rename_axis(columns=colnames_mapper, axis=1)NEWLINENEWLINE return tableNEWLINENEWLINENEWLINEdef _normalize(table, normalize, margins: bool, margins_name="All"):NEWLINENEWLINE if not isinstance(normalize, (bool, str)):NEWLINE axis_subs = {0: "index", 1: "columns"}NEWLINE try:NEWLINE normalize = axis_subs[normalize]NEWLINE except KeyError as err:NEWLINE raise ValueError("Not a valid normalize argument") from errNEWLINENEWLINE if margins is False:NEWLINENEWLINE # Actual NormalizationsNEWLINE normalizers: Dict[Union[bool, str], Callable] = {NEWLINE "all": lambda x: x / x.sum(axis=1).sum(axis=0),NEWLINE "columns": lambda x: x / x.sum(),NEWLINE "index": lambda x: x.div(x.sum(axis=1), axis=0),NEWLINE }NEWLINENEWLINE normalizers[True] = normalizers["all"]NEWLINENEWLINE try:NEWLINE f = normalizers[normalize]NEWLINE except KeyError as err:NEWLINE raise ValueError("Not a valid normalize argument") from errNEWLINENEWLINE table = f(table)NEWLINE table = table.fillna(0)NEWLINENEWLINE elif margins is True:NEWLINE # keep index and column of pivoted tableNEWLINE table_index = table.indexNEWLINE table_columns = table.columnsNEWLINE last_ind_or_col = table.iloc[-1, :].nameNEWLINENEWLINE # check if margin name is not in (for MI cases) and not equal to lastNEWLINE # index/column and save the column and index marginNEWLINE if (margins_name not in last_ind_or_col) & (margins_name != last_ind_or_col):NEWLINE raise ValueError(f"{margins_name} not in pivoted DataFrame")NEWLINE column_margin = table.iloc[:-1, -1]NEWLINE index_margin = table.iloc[-1, :-1]NEWLINENEWLINE # keep the core tableNEWLINE table = table.iloc[:-1, :-1]NEWLINENEWLINE # Normalize coreNEWLINE table = _normalize(table, normalize=normalize, margins=False)NEWLINENEWLINE # Fix MarginsNEWLINE if normalize == "columns":NEWLINE column_margin = column_margin / column_margin.sum()NEWLINE table = concat([table, column_margin], axis=1)NEWLINE table = table.fillna(0)NEWLINE table.columns = table_columnsNEWLINENEWLINE elif normalize == "index":NEWLINE index_margin = index_margin / index_margin.sum()NEWLINE table = table.append(index_margin)NEWLINE table = table.fillna(0)NEWLINE table.index = table_indexNEWLINENEWLINE elif normalize == "all" or normalize is True:NEWLINE column_margin = column_margin / column_margin.sum()NEWLINE index_margin = index_margin / index_margin.sum()NEWLINE index_margin.loc[margins_name] = 1NEWLINE table = concat([table, column_margin], axis=1)NEWLINE table = table.append(index_margin)NEWLINENEWLINE table = table.fillna(0)NEWLINE table.index = table_indexNEWLINE table.columns = table_columnsNEWLINENEWLINE else:NEWLINE raise ValueError("Not a valid normalize argument")NEWLINENEWLINE else:NEWLINE raise ValueError("Not a valid margins argument")NEWLINENEWLINE return tableNEWLINENEWLINENEWLINEdef _get_names(arrs, names, prefix: str = "row"):NEWLINE if names is None:NEWLINE names = []NEWLINE for i, arr in enumerate(arrs):NEWLINE if isinstance(arr, ABCSeries) and arr.name is not None:NEWLINE names.append(arr.name)NEWLINE else:NEWLINE names.append(f"{prefix}_{i}")NEWLINE else:NEWLINE if len(names) != len(arrs):NEWLINE raise AssertionError("arrays and names must have the same length")NEWLINE if not isinstance(names, list):NEWLINE names = list(names)NEWLINENEWLINE return namesNEWLINENEWLINENEWLINEdef _build_names_mapper(NEWLINE rownames: List[str], colnames: List[str]NEWLINE) -> Tuple[Dict[str, str], List[str], Dict[str, str], List[str]]:NEWLINE """NEWLINE Given the names of a DataFrame's rows and columns, returns a set of unique rowNEWLINE and column names and mappers that convert to original names.NEWLINENEWLINE A row or column name is replaced if it is duplicate among the rows of the inputs,NEWLINE among the columns of the inputs or between the rows and the columns.NEWLINENEWLINE ParametersNEWLINE ----------NEWLINE rownames: list[str]NEWLINE colnames: list[str]NEWLINENEWLINE ReturnsNEWLINE -------NEWLINE Tuple(Dict[str, str], List[str], Dict[str, str], List[str])NEWLINENEWLINE rownames_mapper: dict[str, str]NEWLINE a dictionary with new row names as keys and original rownames as valuesNEWLINE unique_rownames: list[str]NEWLINE a list of rownames with duplicate names replaced by dummy namesNEWLINE colnames_mapper: dict[str, str]NEWLINE a dictionary with new column names as keys and original column names as valuesNEWLINE unique_colnames: list[str]NEWLINE a list of column names with duplicate names replaced by dummy namesNEWLINENEWLINE """NEWLINENEWLINE def get_duplicates(names):NEWLINE seen: Set = set()NEWLINE return {name for name in names if name not in seen}NEWLINENEWLINE shared_names = set(rownames).intersection(set(colnames))NEWLINE dup_names = get_duplicates(rownames) | get_duplicates(colnames) | shared_namesNEWLINENEWLINE rownames_mapper = {NEWLINE f"row_{i}": name for i, name in enumerate(rownames) if name in dup_namesNEWLINE }NEWLINE unique_rownames = [NEWLINE f"row_{i}" if name in dup_names else name for i, name in enumerate(rownames)NEWLINE ]NEWLINENEWLINE colnames_mapper = {NEWLINE f"col_{i}": name for i, name in enumerate(colnames) if name in dup_namesNEWLINE }NEWLINE unique_colnames = [NEWLINE f"col_{i}" if name in dup_names else name for i, name in enumerate(colnames)NEWLINE ]NEWLINENEWLINE return rownames_mapper, unique_rownames, colnames_mapper, unique_colnamesNEWLINE
import pytestNEWLINEfrom moto import mock_s3NEWLINENEWLINEimport loggingNEWLINEimport pandas as pdNEWLINEimport boto3NEWLINENEWLINEfrom great_expectations.datasource.generator.s3_generator import S3GlobReaderBatchKwargsGeneratorNEWLINEfrom great_expectations.exceptions import BatchKwargsErrorNEWLINENEWLINENEWLINE@pytest.fixture(scope="module")NEWLINEdef mock_s3_bucket():NEWLINE with mock_s3():NEWLINE bucket = 'test_bucket'NEWLINENEWLINE conn = boto3.resource('s3', region_name='us-east-1')NEWLINE conn.create_bucket(Bucket=bucket)NEWLINE client = boto3.client('s3', region_name='us-east-1')NEWLINENEWLINE df = pd.DataFrame({"c1": [1, 2, 3], "c2": ["a", "b", "c"]})NEWLINE keys = [NEWLINE "data/for/you.csv",NEWLINE "data/for/me.csv",NEWLINE "data/to/you.csv",NEWLINE "other/to/you.csv",NEWLINE "other/for/you.csv",NEWLINE "other/is/you.csv",NEWLINE "delta_files/blarg.parquet",NEWLINE "data/is/you.csv"NEWLINE ]NEWLINE for key in keys:NEWLINE client.put_object(NEWLINE Bucket=bucket,NEWLINE Body=df.to_csv(index=None).encode('utf-8'),NEWLINE Key=keyNEWLINE )NEWLINE yield bucketNEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef s3_generator(mock_s3_bucket, basic_sparkdf_datasource):NEWLINE # We configure a generator that will fetch from (mocked) my_bucketNEWLINE # and will use glob patterns to match returned assets into batches of the same assetNEWLINE generator = S3GlobReaderBatchKwargsGenerator("my_generator",NEWLINE datasource=basic_sparkdf_datasource,NEWLINE bucket=mock_s3_bucket,NEWLINE reader_options={NEWLINE "sep": ","NEWLINE },NEWLINE assets={NEWLINE "data": {NEWLINE "prefix": "data/",NEWLINE "delimiter": "",NEWLINE "regex_filter": r"data/for/.*\.csv"NEWLINE },NEWLINE "data_dirs": {NEWLINE "prefix": "data/",NEWLINE "directory_assets": TrueNEWLINE },NEWLINE "other": {NEWLINE "prefix": "other/",NEWLINE "regex_filter": r".*/you\.csv",NEWLINE "reader_options": {NEWLINE "sep": "\t"NEWLINE }NEWLINE },NEWLINE "delta_files": {NEWLINE "prefix": "delta_files/",NEWLINE "regex_filter": r".*/blarg\.parquet",NEWLINE "reader_method": "delta"NEWLINE },NEWLINE "other_empty_delimiter": {NEWLINE "prefix": "other/",NEWLINE "delimiter": "",NEWLINE "regex_filter": r".*/you\.csv",NEWLINE "reader_options": {NEWLINE "sep": "\t"NEWLINE },NEWLINE "max_keys": 1NEWLINE }NEWLINE }NEWLINE )NEWLINE yield generatorNEWLINENEWLINENEWLINEdef test_s3_generator_basic_operation(s3_generator):NEWLINE # S3 Generator sees *only* configured assetsNEWLINE assets = s3_generator.get_available_data_asset_names()NEWLINE assert set(assets["names"]) == set([('data', 'file'), ('data_dirs', 'file'), ('other', 'file'), ('delta_files', 'file'), ('other_empty_delimiter', 'file')])NEWLINENEWLINE # We should observe that glob, prefix, delimiter all work togetherNEWLINE # They can be defined in the generator or overridden by a particular assetNEWLINE # Under the hood, we use the S3 ContinuationToken options to lazily fetch dataNEWLINE batch_kwargs = [kwargs for kwargs in s3_generator.get_iterator("data")]NEWLINE assert len(batch_kwargs) == 2NEWLINE assert batch_kwargs[0]["reader_options"]["sep"] == ","NEWLINE assert batch_kwargs[0]["s3"] in ["s3a://test_bucket/data/for/you.csv", "s3a://test_bucket/data/for/me.csv"]NEWLINENEWLINE # When a prefix and delimiter do not yield objects, there are no objects returned; raise an errorNEWLINE with pytest.raises(BatchKwargsError) as err:NEWLINE batch_kwargs = [kwargs for kwargs in s3_generator.get_iterator("other")]NEWLINE # The error should show the common prefixesNEWLINE assert "common_prefixes" in err.value.batch_kwargsNEWLINENEWLINENEWLINEdef test_s3_generator_incremental_fetch(s3_generator, caplog):NEWLINE caplog.set_level(logging.DEBUG, logger="great_expectations.datasource.generator.s3_generator")NEWLINENEWLINE # When max_keys is not set, it defaults to 1000, so all items are returned in the first iterator batch,NEWLINE # causing only one fetch (and one log entry referencing the startup of the method)NEWLINE caplog.clear()NEWLINE batch_kwargs = [kwargs for kwargs in s3_generator.get_iterator("data")]NEWLINE assert len(caplog.records) == 2NEWLINE assert len(batch_kwargs) == 2NEWLINENEWLINE # When there are more items to return than the S3 API returns, we exhaust our iterator and refetchNEWLINE # The result is a new log record for each fetch (plus one for entering the method).NEWLINE # Since there are three assets matched by 'other_empty_delimiter' we create four additional log entries with threeNEWLINE # refetch operationsNEWLINE caplog.clear()NEWLINE batch_kwargs = [kwargs for kwargs in s3_generator.get_iterator("other_empty_delimiter")]NEWLINE assert len(caplog.records) == 4NEWLINE assert len(batch_kwargs) == 3NEWLINENEWLINENEWLINEdef test_s3_generator_get_directories(s3_generator):NEWLINE # Verify that an asset configured to return directories can do soNEWLINE batch_kwargs_list = [kwargs for kwargs in s3_generator.get_iterator("data_dirs")]NEWLINE assert 3 == len(batch_kwargs_list)NEWLINE paths = set([batch_kwargs["s3"] for batch_kwargs in batch_kwargs_list])NEWLINE assert {"s3a://test_bucket/data/for/", "s3a://test_bucket/data/to/", "s3a://test_bucket/data/is/"} == pathsNEWLINENEWLINENEWLINEdef test_s3_generator_limit(s3_generator):NEWLINE batch_kwargs_list = [kwargs for kwargs in s3_generator.get_iterator("data", limit=10)]NEWLINE assert all(["limit" in batch_kwargs for batch_kwargs in batch_kwargs_list])NEWLINENEWLINENEWLINEdef test_s3_generator_reader_method_configuration(s3_generator):NEWLINE batch_kwargs_list = [kwargs for kwargs in s3_generator.get_iterator("delta_files", limit=10)]NEWLINE assert batch_kwargs_list[0]["reader_method"] == "delta"NEWLINE
import unittestNEWLINENEWLINEfrom tag_bot.utils import read_config_with_yq, update_config_with_yqNEWLINENEWLINENEWLINEclass TestUtilityFunctions(unittest.TestCase):NEWLINE def test_read_config_with_yq_singleuser(self):NEWLINE var_path = ".singleuser.image"NEWLINE config = {"singleuser": {"image": {"name": "my_image", "tag": "my_tag"}}}NEWLINENEWLINE expected_value = {"name": "my_image", "tag": "my_tag"}NEWLINENEWLINE value = read_config_with_yq(config, var_path)NEWLINENEWLINE self.assertDictEqual(value, expected_value)NEWLINENEWLINE def test_read_config_with_yq_profileList(self):NEWLINE var_path = ".singleuser.profileList[0].kubespawner_override.image"NEWLINE config = {NEWLINE "singleuser": {NEWLINE "profileList": [{"kubespawner_override": {"image": "owner/name:tag"}}]NEWLINE }NEWLINE }NEWLINENEWLINE expected_value = "owner/name:tag"NEWLINENEWLINE value = read_config_with_yq(config, var_path)NEWLINENEWLINE self.assertEqual(value, expected_value)NEWLINENEWLINE def test_update_config_with_yq_singleuser(self):NEWLINE test_config = {NEWLINE "singleuser": {"image": {"name": "image_name", "tag": "old_tag"}}NEWLINE }NEWLINE test_image_tags = {NEWLINE "image_name": {NEWLINE "current": "old_tag",NEWLINE "latest": "new_tag",NEWLINE "path": ".singleuser.image.tag",NEWLINE }NEWLINE }NEWLINENEWLINE new_config = update_config_with_yq(NEWLINE test_config,NEWLINE test_image_tags["image_name"]["path"],NEWLINE test_image_tags["image_name"]["latest"],NEWLINE )NEWLINENEWLINE expected_output = {NEWLINE "singleuser": {"image": {"name": "image_name", "tag": "new_tag"}}NEWLINE }NEWLINENEWLINE self.assertDictEqual(new_config, expected_output)NEWLINENEWLINE def test_update_config_with_yq_profileList(self):NEWLINE test_config = {NEWLINE "singleuser": {NEWLINE "profileList": [NEWLINE {"kubespawner_override": {"image": "image_name:old_tag"}},NEWLINE ]NEWLINE }NEWLINE }NEWLINE test_image_tags = {NEWLINE "image_name": {NEWLINE "current": "old_tag",NEWLINE "latest": "new_tag",NEWLINE "path": ".singleuser.profileList[0].kubespawner_override.image",NEWLINE }NEWLINE }NEWLINENEWLINE new_tag = ":".join(["image_name", test_image_tags["image_name"]["latest"]])NEWLINE new_config = update_config_with_yq(NEWLINE test_config, test_image_tags["image_name"]["path"], new_tagNEWLINE )NEWLINENEWLINE expected_output = {NEWLINE "singleuser": {NEWLINE "profileList": [NEWLINE {"kubespawner_override": {"image": "image_name:new_tag"}},NEWLINE ]NEWLINE }NEWLINE }NEWLINENEWLINE self.assertDictEqual(new_config, expected_output)NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE unittest.main()NEWLINE
""""NEWLINEОсновной файл ботаNEWLINE"""NEWLINENEWLINEimport osNEWLINEimport platformNEWLINEimport randomNEWLINENEWLINEimport discordNEWLINEfrom discord.ext import commands, tasksNEWLINEfrom discord.ext.commands import BotNEWLINEfrom discord_slash import SlashCommand, SlashContext # Importing the newly installed library.NEWLINENEWLINEfrom scripts.config import read_configNEWLINENEWLINEconfig = read_config()NEWLINENEWLINETOKEN = config['app_token']NEWLINEAPP_ID = config['app_id']NEWLINENEWLINENEWLINE""" NEWLINESetup bot intents (events restrictions)NEWLINEFor more information about intents, please go to the following websites:NEWLINEhttps://discordpy.readthedocs.io/en/latest/intents.htmlNEWLINEhttps://discordpy.readthedocs.io/en/latest/intents.html#privileged-intentsNEWLINENEWLINENEWLINEDefault Intents:NEWLINEintents.messages = TrueNEWLINEintents.reactions = TrueNEWLINEintents.guilds = TrueNEWLINEintents.emojis = TrueNEWLINEintents.bans = TrueNEWLINEintents.guild_typing = FalseNEWLINEintents.typing = FalseNEWLINEintents.dm_messages = FalseNEWLINEintents.dm_reactions = FalseNEWLINEintents.dm_typing = FalseNEWLINEintents.guild_messages = TrueNEWLINEintents.guild_reactions = TrueNEWLINEintents.integrations = TrueNEWLINEintents.invites = TrueNEWLINEintents.voice_states = FalseNEWLINEintents.webhooks = FalseNEWLINENEWLINEPrivileged Intents (Needs to be enabled on dev page), please use them only if you need them:NEWLINEintents.presences = TrueNEWLINEintents.members = TrueNEWLINE"""NEWLINENEWLINENEWLINEintents = discord.Intents.default()NEWLINEintents.members = TrueNEWLINENEWLINEbot = Bot(command_prefix=config["bot_prefix"], intents=intents)NEWLINEslash = SlashCommand(bot, sync_commands=True)NEWLINENEWLINE# The code in this even is executed when the bot is readyNEWLINE@bot.eventNEWLINEasync def on_ready():NEWLINE print(f"Logged in as {bot.user.name}")NEWLINE print(f"Discord.py API version: {discord.__version__}")NEWLINE print(f"Python version: {platform.python_version()}")NEWLINE print(f"Running on: {platform.system()} {platform.release()} ({os.name})")NEWLINE print("-------------------")NEWLINE status_task.start()NEWLINENEWLINENEWLINE# Setup the game status task of the botNEWLINE@tasks.loop(minutes=1.0)NEWLINEasync def status_task():NEWLINE statuses = ["поиск картинок", ""]NEWLINE await bot.change_presence(activity=discord.Game(random.choice(statuses)))NEWLINENEWLINENEWLINEif __name__ == "__main__":NEWLINE for file in os.listdir("./cogs"):NEWLINE if file.endswith(".py"):NEWLINE extension = file[:-3]NEWLINE try:NEWLINE bot.load_extension(f"cogs.{extension}")NEWLINE print(f"Loaded extension '{extension}'")NEWLINE except Exception as e:NEWLINE exception = f"{type(e).__name__}: {e}"NEWLINE print(f"Failed to load extension {extension}\n{exception}")NEWLINENEWLINENEWLINE# The code in this event is executed every time someone sends a message, with or without the prefixNEWLINE@bot.eventNEWLINEasync def on_message(message):NEWLINE # Ignores if a command is being executed by a bot or by the bot itselfNEWLINE if message.author == bot.user or message.author.bot:NEWLINE returnNEWLINE await bot.process_commands(message)NEWLINENEWLINENEWLINE# The code in this event is executed every time a command has been *successfully* executedNEWLINE@bot.eventNEWLINEasync def on_slash_command(ctx: SlashContext):NEWLINE fullCommandName = ctx.nameNEWLINE split = fullCommandName.split(" ")NEWLINE executedCommand = str(split[0])NEWLINE print(NEWLINE f"Executed {executedCommand} command in {ctx.guild.name} (ID: {ctx.guild.id}) by {ctx.author} (ID: {ctx.author.id})")NEWLINENEWLINENEWLINE# The code in this event is executed every time a valid commands catches an errorNEWLINE@bot.eventNEWLINEasync def on_command_error(context, error):NEWLINE raise errorNEWLINENEWLINENEWLINE# Run the bot with the tokenNEWLINEbot.run(TOKEN)NEWLINE
NEWLINEimport reNEWLINENEWLINENEWLINEclass RegexValidator(object):NEWLINE def __init__(self, pattern, excludes):NEWLINE if not pattern or pattern == '':NEWLINE pattern = '.*' # match anythingNEWLINE if not excludes or excludes == '':NEWLINE excludes = 'a^' # match nothingNEWLINENEWLINE self._pattern = re.compile(pattern)NEWLINE self._excludes = re.compile(excludes)NEWLINENEWLINE def is_valid(self, string):NEWLINE return self._pattern.match(string) and not self._excludes.match(string)NEWLINENEWLINENEWLINEclass FilesPathValidator(RegexValidator):NEWLINE def __init__(self, excluded_paths, pattern_regex, excludes_regex):NEWLINE self._excluded_paths = excluded_pathsNEWLINENEWLINE super(FilesPathValidator, self).__init__(pattern_regex, excludes_regex)NEWLINENEWLINE def is_valid(self, string):NEWLINE if string not in self._excluded_paths:NEWLINE return super(FilesPathValidator, self).is_valid(string)NEWLINE return FalseNEWLINENEWLINE
from selenium import webdriverNEWLINEimport selenium.common.exceptionsNEWLINEfrom selenium.webdriver import FirefoxOptionsNEWLINEfrom selenium.webdriver.common.by import ByNEWLINEfrom selenium.webdriver.support.expected_conditions import (NEWLINE text_to_be_present_in_element,NEWLINE)NEWLINEfrom selenium.webdriver.support.ui import WebDriverWaitNEWLINENEWLINEopts = FirefoxOptions()NEWLINEopts.add_argument("--headless")NEWLINEwith webdriver.Firefox(options=opts) as driver:NEWLINE wait = WebDriverWait(driver, 30)NEWLINE driver.get("http://localhost/index.html")NEWLINE try:NEWLINE wait.until(NEWLINE text_to_be_present_in_element(NEWLINE (By.ID, "log"), "Start loading python... done"NEWLINE )NEWLINE )NEWLINE wait.until(NEWLINE text_to_be_present_in_element(NEWLINE (By.ID, "log"), "Loading package numpy... done"NEWLINE )NEWLINE )NEWLINE wait.until(NEWLINE text_to_be_present_in_element(NEWLINE (By.ID, "log"), "Loading package scipy... done"NEWLINE )NEWLINE )NEWLINE wait.until(NEWLINE text_to_be_present_in_element(NEWLINE (By.ID, "log"), "Loading python module angle... done"NEWLINE )NEWLINE )NEWLINE wait.until(NEWLINE text_to_be_present_in_element(NEWLINE (By.ID, "log"), "Loading python module compute... done"NEWLINE )NEWLINE )NEWLINE except selenium.common.exceptions.TimeoutException:NEWLINE print("fails")NEWLINE print("page source :", driver.page_source)NEWLINE raiseNEWLINE
from datetime import datetime, dateNEWLINEfrom marqeta.response_models.transaction_model import TransactionModelNEWLINEfrom marqeta.response_models import datetime_objectNEWLINEimport jsonNEWLINEimport reNEWLINENEWLINEclass AdvancedSimulationResponseModel(object):NEWLINENEWLINE def __init__(self, json_response):NEWLINE self.json_response = json_responseNEWLINENEWLINE def __str__(self):NEWLINE return json.dumps(self.json_response, default=self.json_serial)NEWLINENEWLINE @staticmethodNEWLINE def json_serial(o):NEWLINE if isinstance(o, datetime) or isinstance(o, date):NEWLINE return o.__str__()NEWLINENEWLINE @propertyNEWLINE def transaction(self):NEWLINE if 'transaction' in self.json_response:NEWLINE return TransactionModel(self.json_response['transaction'])NEWLINENEWLINE @propertyNEWLINE def raw_iso8583(self):NEWLINE return self.json_response.get('raw_iso8583', None)NEWLINENEWLINE def __repr__(self):NEWLINE return '<Marqeta.response_models.advanced_simulation_response_model.AdvancedSimulationResponseModel>' + self.__str__()NEWLINE
#!/usr/bin/python3NEWLINE# -*- coding: utf-8 -*-NEWLINE# #%LNEWLINE# %%NEWLINE# Copyright (C) 2021 BMW Car IT GmbHNEWLINE# %%NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE# #L%NEWLINENEWLINE'''NEWLINERemove unused dependencies from the generated.pomNEWLINEAdd missing dependencies to the generated.pom.NEWLINENote that this process does not update existing dependency versions.NEWLINEA manual check/update is required if new direct dependencies areNEWLINEadded to the projects or their versions are updated.NEWLINE'''NEWLINENEWLINEimport argparseNEWLINEimport collectionsNEWLINEimport filecmpNEWLINEimport loggingNEWLINEimport osNEWLINEimport shutilNEWLINEimport subprocessNEWLINEimport xml.etree.ElementTree as xmlETNEWLINENEWLINEDEPENDENCY_LOCK_DIR = os.path.abspath(os.path.dirname(__file__))NEWLINENEWLINE# Scope not relevant for dependency management.NEWLINEDependency = collections.namedtuple(NEWLINE 'Dependency', ['groupId', 'artifactId', 'type', 'version'])NEWLINENEWLINENEWLINEclass PomGenerator(object):NEWLINE DEFAULT_WORKING_DIR = os.path.dirname(__file__)NEWLINENEWLINE def __init__(self, lockDir=os.path.abspath(DEFAULT_WORKING_DIR)):NEWLINE object.__init__(self)NEWLINE self.__log = logging.getLogger('PomGenerator')NEWLINE self.__pomFile = os.path.join(lockDir, 'pom.xml')NEWLINE self.__backupFile = os.path.join(lockDir, "pom-backup.%s" % id(self))NEWLINE self.__pomHeader = []NEWLINE self.__pomFooter = []NEWLINE try:NEWLINE if not os.path.isfile(self.__pomFile):NEWLINE raise RuntimeError(NEWLINE "POM file '%s' does not exist." % self.__pomFile)NEWLINENEWLINE pomSection = self.__pomHeaderNEWLINE with open(self.__pomFile) as fp:NEWLINE for line in fp:NEWLINE if line.strip() == '</dependencies>':NEWLINE pomSection = self.__pomFooterNEWLINE pomSection.append(line)NEWLINE if line.strip() == '<dependencies>':NEWLINE pomSection = [] # Drop dependenciesNEWLINENEWLINE if 0 == len(self.__pomFooter):NEWLINE raise RuntimeError(NEWLINE "POM file '%s' does not contain 'dependencies' section." % self.__pomFile)NEWLINENEWLINE shutil.copyfile(self.__pomFile, self.__backupFile)NEWLINE except Exception as e:NEWLINE self.__log.error(NEWLINE "PomGenerator initialization arguments incorrect: %s" % e)NEWLINE raiseNEWLINENEWLINE def __del__(self):NEWLINE if os.path.isfile(self.__backupFile):NEWLINE os.remove(self.__backupFile)NEWLINENEWLINE def restore(self):NEWLINE shutil.copyfile(self.__backupFile, self.__pomFile)NEWLINENEWLINE def reset(self):NEWLINE self.write([])NEWLINENEWLINE def modified(self):NEWLINE return not filecmp.cmp(self.__backupFile, self.__pomFile, shallow=False)NEWLINENEWLINE def write(self, dependencies):NEWLINE with open(self.__pomFile, 'w', encoding='utf-8') as fp:NEWLINE for line in self.__pomHeader:NEWLINE fp.write(line)NEWLINE for dependency in dependencies:NEWLINE fp.write(self.__toXml(dependency))NEWLINE for line in self.__pomFooter:NEWLINE fp.write(line)NEWLINENEWLINE def __toXml(self, dependency):NEWLINE nodeName = 'dependency'NEWLINE node = xmlET.Element(nodeName)NEWLINE for name, value in dependency._asdict().items():NEWLINE child = xmlET.SubElement(node, name)NEWLINE child.text = valueNEWLINENEWLINE nodeStr = xmlET.tostring(node, encoding='unicode', method='xml')NEWLINE nodeStrTags = nodeStr.split('<',)NEWLINE nodeStr = ''NEWLINE for nodeStrTag in nodeStrTags:NEWLINE if nodeName in nodeStrTag:NEWLINE nodeStr += "\t\t\t<%s\n" % nodeStrTagNEWLINE elif nodeStrTag:NEWLINE if nodeStrTag.startswith('/'):NEWLINE nodeStr += "<%s\n" % nodeStrTagNEWLINE else:NEWLINE nodeStr += "\t\t\t\t<%s" % nodeStrTagNEWLINE return nodeStrNEWLINENEWLINENEWLINEclass ProjectDependency(object):NEWLINE DEFAULT_POM_DIR = os.path.abspath(os.path.join(NEWLINE os.path.dirname(__file__), os.path.normpath('../')))NEWLINE DEFAULT_POM_FILENAME = 'pom.xml'NEWLINE MVN_EXEC = 'mvn'NEWLINE MVN_SCOPES = ['compile', 'provided', 'runtime', 'test', 'system', 'import']NEWLINE ADDITIONAL_PROFILES = ['javascript', 'android']NEWLINENEWLINE def __init__(self, pomDir=DEFAULT_POM_DIR, pomFile=DEFAULT_POM_FILENAME):NEWLINE object.__init__(self)NEWLINE pomDir = os.path.abspath(pomDir)NEWLINE self.__log = logging.getLogger('ProjectDependency')NEWLINE try:NEWLINE if not os.path.isdir(pomDir):NEWLINE raise RuntimeError(NEWLINE "POM directory '%s' does not exist." % pomDir)NEWLINENEWLINE pomFile = os.path.join(pomDir, pomFile)NEWLINE if not os.path.isfile(pomFile):NEWLINE raise RuntimeError("POM file '%s' does not exist." % pomFile)NEWLINE mvnCall = subprocess.run(NEWLINE [ProjectDependency.MVN_EXEC, '-version'], capture_output=True, text=True)NEWLINE if mvnCall.returncode:NEWLINE raise RuntimeError("'%s' execution failed:\n%s\n%s" % (NEWLINE ProjectDependency.MVN_EXEC, mvnCall.stdout, mvnCall.stderr))NEWLINENEWLINE self.__cmd = [ProjectDependency.MVN_EXEC, '-f', pomFile,NEWLINE '-pl', '"-io.joynr.examples:radio-app"',NEWLINE '-P', ','.join(ProjectDependency.ADDITIONAL_PROFILES)]NEWLINE except Exception as e:NEWLINE self.__log.error(NEWLINE "ProjectDependency initialization arguments incorrect: %s" % e)NEWLINE raiseNEWLINENEWLINE def listTransitives(self):NEWLINE allDependencies = self.__set()NEWLINE self.__log.debug("Found %d dependencies." % len(allDependencies))NEWLINENEWLINE directDependencies = self.__set(['excludeTransitive'])NEWLINE self.__log.debug("Found %d direct dependencies." %NEWLINE len(directDependencies))NEWLINENEWLINE transitiveDependencies = allDependencies - directDependenciesNEWLINE return sorted(transitiveDependencies)NEWLINENEWLINE def listExternal(self, internalGroupsStartWith='io.joynr'):NEWLINE allDependencies = self.__set()NEWLINE self.__log.debug("Found %d dependencies." % len(allDependencies))NEWLINENEWLINE externalDependencies = sorted(filter(NEWLINE lambda d: not d.groupId.startswith(internalGroupsStartWith), allDependencies))NEWLINE self.__log.debug("Found %d external dependencies." %NEWLINE len(externalDependencies))NEWLINE return externalDependenciesNEWLINENEWLINE def __set(self, userProperties=[]):NEWLINE cmd = self.__cmd.copy()NEWLINE for userProperty in userProperties:NEWLINE cmd += ["-D%s" % userProperty]NEWLINE cmd += ['dependency:list']NEWLINE mvnCall = subprocess.run(cmd, capture_output=True, text=True)NEWLINE if mvnCall.returncode:NEWLINE raise RuntimeError("'%s' execution failed:\n%s\n%s" % (NEWLINE " ".join(cmd), mvnCall.stdout, mvnCall.stderr))NEWLINENEWLINE return self.__parseOutput(mvnCall.stdout)NEWLINENEWLINE def __parseOutput(self, output):NEWLINE dependencies = set()NEWLINE for line in output.split("\n"):NEWLINE if not line:NEWLINE continueNEWLINE line = line.strip()NEWLINE endOfInfo = line.find(' ')NEWLINE line = line[endOfInfo:]NEWLINE line = line.strip()NEWLINE parts = line.split(':')NEWLINE if 5 == len(parts) and parts[4] in ProjectDependency.MVN_SCOPES:NEWLINE del parts[-1]NEWLINE dependencies.add(Dependency(*parts))NEWLINE return dependenciesNEWLINENEWLINENEWLINEdef init(parser):NEWLINE parser.add_argument('--loglevel', '-l', dest='loglevel', required=False,NEWLINE default=logging.INFO, type=int, help="Log level, default is %d (info)" % logging.INFO)NEWLINE args = parser.parse_args()NEWLINE logging.basicConfig(level=args.loglevel)NEWLINENEWLINENEWLINE'''Entry point'''NEWLINEif __name__ == '__main__':NEWLINE init(argparse.ArgumentParser(description="Update dependency lock"))NEWLINE generator = PomGenerator()NEWLINE try:NEWLINE projectDependencies = ProjectDependency()NEWLINE externalDependencies = projectDependencies.listExternal()NEWLINE generator.write(externalDependencies)NEWLINE logging.getLogger("main").info(NEWLINE "Updated dependency lock. %d external dependencies found." % len(externalDependencies))NEWLINE except Exception:NEWLINE generator.restore()NEWLINE raiseNEWLINE
# Generated by Django 3.0.3 on 2020-03-11 12:12NEWLINENEWLINEfrom django.conf import settingsNEWLINEfrom django.db import migrations, modelsNEWLINEimport django.db.models.deletionNEWLINENEWLINENEWLINEclass Migration(migrations.Migration):NEWLINENEWLINE dependencies = [NEWLINE ('fedireads', '0014_status_remote_id'),NEWLINE ]NEWLINENEWLINE operations = [NEWLINE migrations.CreateModel(NEWLINE name='UserBlocks',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('created_date', models.DateTimeField(auto_now_add=True)),NEWLINE ('updated_date', models.DateTimeField(auto_now=True)),NEWLINE ('relationship_id', models.CharField(max_length=100)),NEWLINE ],NEWLINE options={NEWLINE 'abstract': False,NEWLINE },NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name='UserFollowRequest',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('created_date', models.DateTimeField(auto_now_add=True)),NEWLINE ('updated_date', models.DateTimeField(auto_now=True)),NEWLINE ('relationship_id', models.CharField(max_length=100)),NEWLINE ],NEWLINE options={NEWLINE 'abstract': False,NEWLINE },NEWLINE ),NEWLINE migrations.CreateModel(NEWLINE name='UserFollows',NEWLINE fields=[NEWLINE ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),NEWLINE ('created_date', models.DateTimeField(auto_now_add=True)),NEWLINE ('updated_date', models.DateTimeField(auto_now=True)),NEWLINE ('relationship_id', models.CharField(max_length=100)),NEWLINE ],NEWLINE options={NEWLINE 'abstract': False,NEWLINE },NEWLINE ),NEWLINE migrations.RemoveField(NEWLINE model_name='user',NEWLINE name='followers',NEWLINE ),NEWLINE migrations.DeleteModel(NEWLINE name='UserRelationship',NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userfollows',NEWLINE name='user_object',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userfollows_user_object', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userfollows',NEWLINE name='user_subject',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userfollows_user_subject', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userfollowrequest',NEWLINE name='user_object',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userfollowrequest_user_object', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userfollowrequest',NEWLINE name='user_subject',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userfollowrequest_user_subject', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userblocks',NEWLINE name='user_object',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userblocks_user_object', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='userblocks',NEWLINE name='user_subject',NEWLINE field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='userblocks_user_subject', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='user',NEWLINE name='blocks',NEWLINE field=models.ManyToManyField(related_name='blocked_by', through='fedireads.UserBlocks', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='user',NEWLINE name='follow_requests',NEWLINE field=models.ManyToManyField(related_name='follower_requests', through='fedireads.UserFollowRequest', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddField(NEWLINE model_name='user',NEWLINE name='following',NEWLINE field=models.ManyToManyField(related_name='followers', through='fedireads.UserFollows', to=settings.AUTH_USER_MODEL),NEWLINE ),NEWLINE migrations.AddConstraint(NEWLINE model_name='userfollows',NEWLINE constraint=models.UniqueConstraint(fields=('user_subject', 'user_object'), name='userfollows_unique'),NEWLINE ),NEWLINE migrations.AddConstraint(NEWLINE model_name='userfollowrequest',NEWLINE constraint=models.UniqueConstraint(fields=('user_subject', 'user_object'), name='userfollowrequest_unique'),NEWLINE ),NEWLINE migrations.AddConstraint(NEWLINE model_name='userblocks',NEWLINE constraint=models.UniqueConstraint(fields=('user_subject', 'user_object'), name='userblocks_unique'),NEWLINE ),NEWLINE ]NEWLINE
# coding=utf-8NEWLINE# *** WARNING: this file was generated by crd2pulumi. ***NEWLINE# *** Do not edit by hand unless you're certain you know what you are doing! ***NEWLINENEWLINESNAKE_TO_CAMEL_CASE_TABLE = {NEWLINE "active_directory": "activeDirectory",NEWLINE "api_version": "apiVersion",NEWLINE "augmented_active_directory": "augmentedActiveDirectory",NEWLINE "base_dn": "baseDN",NEWLINE "ca_secret": "caSecret",NEWLINE "credentials_secret": "credentialsSecret",NEWLINE "deref_aliases": "derefAliases",NEWLINE "group_membership_attributes": "groupMembershipAttributes",NEWLINE "group_name_attributes": "groupNameAttributes",NEWLINE "group_uid_attribute": "groupUIDAttribute",NEWLINE "group_uid_name_mapping": "groupUIDNameMapping",NEWLINE "groups_query": "groupsQuery",NEWLINE "last_sync_success_time": "lastSyncSuccessTime",NEWLINE "last_transition_time": "lastTransitionTime",NEWLINE "login_realm": "loginRealm",NEWLINE "page_size": "pageSize",NEWLINE "tolerate_member_not_found_errors": "tolerateMemberNotFoundErrors",NEWLINE "tolerate_member_out_of_scope_errors": "tolerateMemberOutOfScopeErrors",NEWLINE "user_name_attributes": "userNameAttributes",NEWLINE "user_uid_attribute": "userUIDAttribute",NEWLINE "users_query": "usersQuery",NEWLINE}NEWLINENEWLINECAMEL_TO_SNAKE_CASE_TABLE = {NEWLINE "activeDirectory": "active_directory",NEWLINE "apiVersion": "api_version",NEWLINE "augmentedActiveDirectory": "augmented_active_directory",NEWLINE "baseDN": "base_dn",NEWLINE "caSecret": "ca_secret",NEWLINE "credentialsSecret": "credentials_secret",NEWLINE "derefAliases": "deref_aliases",NEWLINE "groupMembershipAttributes": "group_membership_attributes",NEWLINE "groupNameAttributes": "group_name_attributes",NEWLINE "groupUIDAttribute": "group_uid_attribute",NEWLINE "groupUIDNameMapping": "group_uid_name_mapping",NEWLINE "groupsQuery": "groups_query",NEWLINE "lastSyncSuccessTime": "last_sync_success_time",NEWLINE "lastTransitionTime": "last_transition_time",NEWLINE "loginRealm": "login_realm",NEWLINE "pageSize": "page_size",NEWLINE "tolerateMemberNotFoundErrors": "tolerate_member_not_found_errors",NEWLINE "tolerateMemberOutOfScopeErrors": "tolerate_member_out_of_scope_errors",NEWLINE "userNameAttributes": "user_name_attributes",NEWLINE "userUIDAttribute": "user_uid_attribute",NEWLINE "usersQuery": "users_query",NEWLINE}NEWLINE
# -*- coding: utf-8 -*-NEWLINE# Copyright (c) 2012-2015, Philip Xu <pyx@xrefactor.com>NEWLINE# License: BSD New, see LICENSE for details.NEWLINEimport pytestNEWLINENEWLINEfrom monad.actions import firstNEWLINEfrom monad.decorators import maybeNEWLINEfrom monad.exceptions import ExtractErrorNEWLINEfrom monad.types import Maybe, Just, NothingNEWLINENEWLINEtest_range = range(-100, 100)NEWLINEunit = Maybe.unitNEWLINENEWLINENEWLINEdef add_1(n):NEWLINE if isinstance(n, int):NEWLINE return unit(n + 1)NEWLINE else:NEWLINE return NothingNEWLINENEWLINENEWLINEdef double(n):NEWLINE if isinstance(n, int):NEWLINE return unit(n * 2)NEWLINE else:NEWLINE return NothingNEWLINENEWLINENEWLINEdef fail(n):NEWLINE return NothingNEWLINENEWLINENEWLINEdef test_local_helper_function_add_one():NEWLINE for n in test_range:NEWLINE assert add_1(n) == unit(n + 1)NEWLINE assert add_1('1') is NothingNEWLINENEWLINENEWLINEdef test_local_helper_function_double():NEWLINE for n in test_range:NEWLINE assert double(n) == unit(n * 2)NEWLINE assert double('1') is NothingNEWLINENEWLINENEWLINEdef test_local_helper_function_fail():NEWLINE for n in test_range:NEWLINE assert fail(n) is NothingNEWLINENEWLINENEWLINEdef test_type():NEWLINE assert unit(1) == Just(1) == Maybe(1)NEWLINE assert Nothing != unit(1)NEWLINE assert type(unit(1)) == type(Just(1)) == type(Maybe(1)) == type(Nothing)NEWLINENEWLINENEWLINEdef test_compare():NEWLINE assert Nothing == NothingNEWLINE for n in test_range:NEWLINE assert unit(n) != NothingNEWLINE assert unit(n) is not NothingNEWLINENEWLINENEWLINEdef test_ordering():NEWLINE assert (Nothing < Nothing) is FalseNEWLINE assert (Nothing > Nothing) is FalseNEWLINE for n in test_range:NEWLINE assert (Nothing > unit(n)) is FalseNEWLINE assert (unit(n) < Nothing) is FalseNEWLINENEWLINENEWLINEdef test_as_context_manager():NEWLINE for n in test_range:NEWLINE with pytest.raises(ExtractError):NEWLINE with unit(n) >> double >> fail >> double as result:NEWLINE assert FalseNEWLINE assert resultNEWLINENEWLINE with pytest.raises(ExtractError):NEWLINE with Nothing as n:NEWLINE assert FalseNEWLINENEWLINE with pytest.raises(ExtractError):NEWLINE with double(n) as result:NEWLINE with Nothing as n:NEWLINE assert FalseNEWLINENEWLINE with pytest.raises(ExtractError):NEWLINE with double(n) as result, Nothing as n:NEWLINE assert FalseNEWLINENEWLINENEWLINEdef test_bool():NEWLINE assert bool(Nothing) is FalseNEWLINE for n in test_range:NEWLINE assert bool(unit(n)) is TrueNEWLINENEWLINENEWLINEdef test_from_value():NEWLINE false_v = [False, None, 0, 0.0, (), [], {}, '', set(), frozenset()]NEWLINE for v in false_v:NEWLINE assert Maybe.from_value(v) is NothingNEWLINENEWLINE true_v = [True, 1, 1.0, (0,), [0], {0: 0}, '0', set('0'), frozenset('0')]NEWLINE for v in true_v:NEWLINE assert Maybe.from_value(v) == unit(v)NEWLINENEWLINENEWLINEdef test_as_iterator():NEWLINE for n in test_range:NEWLINE for i in unit(n):NEWLINE assert i == nNEWLINENEWLINE assert list(unit(n)) == [n]NEWLINENEWLINENEWLINEdef test_bind():NEWLINE assert Nothing.bind(add_1) is NothingNEWLINE for n in test_range:NEWLINE m = unit(n)NEWLINE assert m.bind(fail) is NothingNEWLINENEWLINENEWLINEdef test_bind_operator():NEWLINE for n in test_range:NEWLINE m = unit(n)NEWLINE assert m >> fail is NothingNEWLINE assert fail(n) >> add_1 is NothingNEWLINENEWLINENEWLINEdef test_reversed_bind_operator():NEWLINE for n in test_range:NEWLINE m = unit(n)NEWLINE assert fail << m is NothingNEWLINE assert add_1 << fail(n) is NothingNEWLINENEWLINENEWLINEdef test_chain_bind_operator():NEWLINE for n in test_range:NEWLINE m = unit(n)NEWLINE assert m >> fail >> add_1 == NothingNEWLINE assert m >> add_1 >> fail == NothingNEWLINE assert m >> fail >> double == NothingNEWLINE assert m >> double >> fail == NothingNEWLINENEWLINENEWLINEdef test_monad_law_left_identity():NEWLINE for n in test_range:NEWLINE # unit n >>= f == f nNEWLINE f = failNEWLINE assert unit(n) >> f == f(n)NEWLINENEWLINENEWLINEdef test_monad_law_right_identity():NEWLINE for n in test_range:NEWLINE # m >>= unit == mNEWLINE assert Nothing >> unit == NothingNEWLINENEWLINENEWLINEdef test_monad_law_associativity():NEWLINE for n in test_range:NEWLINE # m >>= (\x -> k x >>= h) == (m >>= k) >>= hNEWLINE m = unit(n)NEWLINE k = add_1NEWLINE h = failNEWLINE assert m >> (lambda x: k(x) >> h) == (m >> k) >> hNEWLINE k = failNEWLINE h = doubleNEWLINE assert m >> (lambda x: k(x) >> h) == (m >> k) >> hNEWLINE k = failNEWLINE h = failNEWLINE assert m >> (lambda x: k(x) >> h) == (m >> k) >> hNEWLINENEWLINENEWLINEdef test_maybe_decorator():NEWLINE @maybeNEWLINE def div(a, b):NEWLINE return a / bNEWLINENEWLINE assert div(42, 21) == unit(2)NEWLINE assert div(42, 0) is NothingNEWLINENEWLINENEWLINEdef test_maybe_decorator_with_predicate():NEWLINE @maybe(predicate=bool)NEWLINE def truth(x):NEWLINE return xNEWLINENEWLINE assert truth(42) == unit(42)NEWLINE assert truth(None) is NothingNEWLINE assert add_1(0) >> truth == unit(1)NEWLINE assert add_1(-1) >> truth is NothingNEWLINE assert truth(False) >> double is NothingNEWLINE assert double([]) >> truth is NothingNEWLINENEWLINENEWLINEdef test_maybe_decorator_with_value():NEWLINE @maybe(nothing_on_value=None)NEWLINE def truth(x):NEWLINE return xNEWLINENEWLINE assert truth(42) is not NothingNEWLINE assert truth('') is not NothingNEWLINE assert truth(0) is not NothingNEWLINE assert truth(False) is not NothingNEWLINE assert truth(None) is NothingNEWLINENEWLINENEWLINEdef test_maybe_decorator_combined():NEWLINE @maybe(predicate=bool, nothing_on_value=42)NEWLINE def wrap(x):NEWLINE return xNEWLINENEWLINE assert wrap(True) == unit(True)NEWLINE assert wrap(False) is NothingNEWLINE assert wrap('something') == unit('something')NEWLINE assert wrap('') is NothingNEWLINE assert wrap([False]) == unit([False])NEWLINE assert wrap([]) is NothingNEWLINE assert wrap(1) == unit(1)NEWLINE assert wrap(0) is NothingNEWLINE assert wrap(None) is NothingNEWLINE assert wrap(42) is NothingNEWLINENEWLINENEWLINEdef test_maybe_decorator_none_exception():NEWLINE @maybe(nothing_on_exception=None)NEWLINE def div(a, b):NEWLINE return a / bNEWLINENEWLINE with pytest.raises(ZeroDivisionError):NEWLINE div(42, 0)NEWLINENEWLINENEWLINEdef test_maybe_decorator_empty_seq_exception():NEWLINE for empty in ([], tuple(), set()):NEWLINE @maybe(nothing_on_exception=empty)NEWLINE def div(a, b):NEWLINE return a / bNEWLINENEWLINE with pytest.raises(ZeroDivisionError):NEWLINE div(42, 0)NEWLINENEWLINENEWLINEdef test_maybe_decorator_specific_exception():NEWLINE @maybe(nothing_on_exception=ZeroDivisionError)NEWLINE def div(a, b):NEWLINE return a / bNEWLINENEWLINE assert div(42, 0) is NothingNEWLINENEWLINENEWLINEdef test_maybe_decorator_specific_exception_tuple():NEWLINE @maybe(nothing_on_exception=(IOError, ZeroDivisionError))NEWLINE def div(a, b):NEWLINE if a < 0:NEWLINE raise IOErrorNEWLINE return a / bNEWLINENEWLINE assert div(42, 0) is NothingNEWLINE assert div(-42, 2) is NothingNEWLINENEWLINENEWLINEdef test_first():NEWLINE assert first([Nothing, Just(42)]) == Just(42)NEWLINE assert first([Just(42), Just(43)]) == Just(42)NEWLINE assert first([Nothing, Nothing]) == NothingNEWLINE assert first([]) == NothingNEWLINENEWLINENEWLINEdef test_first_default():NEWLINE assert first([Nothing, Nothing], default=Just(42)) == Just(42)NEWLINENEWLINENEWLINEdef test_first_predicate():NEWLINE assert first([False, 0, 2, 1], predicate=bool) == Just(2)NEWLINE assert first([False, 0, ''], predicate=bool) == NothingNEWLINE assert first(range(100), predicate=lambda x: x > 50) == Just(51)NEWLINE assert first(range(100), predicate=lambda x: x > 100) == NothingNEWLINENEWLINENEWLINEdef test_first_wrap_just_only_if_not_already():NEWLINE assert first([False, True], predicate=bool) == Just(True)NEWLINE assert first([False, Just(True)], bool) != Just(Just(True))NEWLINE assert first([False, Just(True)], bool) == Just(True)NEWLINENEWLINENEWLINEdef test_first_is_lazy():NEWLINE def once():NEWLINE yield Just(42)NEWLINE raise ExceptionNEWLINENEWLINE assert first(once()) == Just(42)NEWLINE
#!/usr/bin/env pythonNEWLINENEWLINENEWLINEclass __pyndler__:NEWLINE import reNEWLINE from importlib.abc import SourceLoaderNEWLINENEWLINE py_re = re.compile('(\.py|/__init__\.py)$')NEWLINE finder = NoneNEWLINENEWLINE def __init__(self):NEWLINE import sysNEWLINE finder = __pyndler__.Finder()NEWLINE __pyndler__.finder = finderNEWLINE sys.meta_path.insert(2, finder)NEWLINENEWLINE class Finder:NEWLINE def __init__(self):NEWLINE self.modules = {}NEWLINE self.packages = set()NEWLINENEWLINE def find_module(self, module_name, package_path):NEWLINE if module_name in self.modules:NEWLINE return __pyndler__.Loader(self.modules, self.packages)NEWLINENEWLINE class Loader(SourceLoader):NEWLINE def __init__(self, modules, packages):NEWLINE self.modules = modulesNEWLINE self.packages = packagesNEWLINENEWLINE def get_filename(self, fullname):NEWLINE return fullnameNEWLINENEWLINE def module_repr(self, module):NEWLINE return repr(module)NEWLINENEWLINE def get_data(self, path):NEWLINE if path not in self.modules:NEWLINE raise IOErrorNEWLINENEWLINE return self.modules[path]NEWLINENEWLINE def is_package(self, fullname):NEWLINE return fullname in self.packagesNEWLINENEWLINE @staticmethodNEWLINE def write_module(path, contents):NEWLINE module_path = __pyndler__.py_re.sub('', path)NEWLINE module_path = module_path.replace('/', '.')NEWLINE __pyndler__.finder.modules[module_path] = contents.encode()NEWLINE if path.endswith('__init__.py'):NEWLINE __pyndler__.finder.packages.add(module_path)NEWLINENEWLINENEWLINE__pyndler__()NEWLINE
import numpy as npNEWLINEimport sysNEWLINEimport osNEWLINEimport timeNEWLINEimport copyNEWLINEimport datetimeNEWLINEimport pickleNEWLINEimport torch.nn as nnNEWLINEfrom torch.utils.data import DataLoaderNEWLINEimport torch.optim as optimNEWLINEimport torch.optim.lr_scheduler as lr_schedulerNEWLINEimport argparseNEWLINEimport platformNEWLINEimport subprocessNEWLINEfrom sklearn.metrics import roc_auc_score, average_precision_scoreNEWLINEfrom social_data_loader import SocialEvolutionDatasetNEWLINEfrom github_data_loader import GithubDatasetNEWLINEfrom example_data_loader import ExampleDatasetNEWLINEfrom utils import *NEWLINEfrom dyrep import DyRepNEWLINEfrom freq import FreqBaselineNEWLINENEWLINEdef load_checkpoint(file):NEWLINE # TODO: Loading the checkpoint stopped working, need to fix.NEWLINE print('loading the model')NEWLINE state = torch.load(file)NEWLINE pos1 = file.find('checkpoint_dygraphs')NEWLINE experiment_ID = str.join('_', file[pos1:].split('_')[2:-2])NEWLINE model.load_state_dict(state['state_dict'])NEWLINE optimizer.load_state_dict(state['optimizer'])NEWLINE scheduler.load_state_dict(state['scheduler'])NEWLINE model.Lambda_dict = state['Lambda_dict']NEWLINE model.time_keys = state['time_keys']NEWLINE print('loading from epoch %d, batch %d done' % (state['epoch'], state['batch_idx']))NEWLINE return state['epoch'], state['batch_idx'], state['time_bar'], state['node_degree_global'], experiment_IDNEWLINENEWLINENEWLINEdef save_checkpoint(batch_idx, epoch):NEWLINE try:NEWLINE fname = '%s/checkpoints/checkpoint_dygraphs_%s_epoch%d_batch%d.pth.tar' % (args.results, experiment_ID, epoch, batch_idx)NEWLINE state = {NEWLINE 'epoch': epoch,NEWLINE 'batch_idx': batch_idx,NEWLINE 'args': args,NEWLINE 'time_bar': time_bar,NEWLINE 'node_degree_global': node_degree_global,NEWLINE 'Lambda_dict': model.Lambda_dict,NEWLINE 'time_keys': model.time_keys,NEWLINE 'state_dict': model.state_dict(),NEWLINE 'scheduler': scheduler.state_dict(),NEWLINE 'optimizer': optimizer.state_dict(),NEWLINE }NEWLINE if os.path.isfile(fname):NEWLINE print('WARNING: file %s exists and will be overwritten' % fname)NEWLINE torch.save(state, fname)NEWLINE print('the model is saved to %s' % fname)NEWLINE except Exception as e:NEWLINE print('error saving the model', e)NEWLINENEWLINENEWLINEdef test(model, n_test_batches=10, epoch=0):NEWLINE model.eval()NEWLINE loss = 0NEWLINE losses =[ [np.Inf, 0], [np.Inf, 0] ]NEWLINE n_samples = 0NEWLINE # Time slots with 10 days intervals as in the DyRep paperNEWLINE timeslots = [t.toordinal() for t in test_loader.dataset.TEST_TIMESLOTS]NEWLINE event_types = list(test_loader.dataset.event_types_num.keys()) #['comm', 'assoc']NEWLINE # sort it by kNEWLINE for event_t in test_loader.dataset.event_types_num:NEWLINE event_types[test_loader.dataset.event_types_num[event_t]] = event_tNEWLINENEWLINE event_types += ['Com']NEWLINENEWLINE mar, hits_10 = {}, {}NEWLINE for event_t in event_types:NEWLINE mar[event_t] = []NEWLINE hits_10[event_t] = []NEWLINE for c, slot in enumerate(timeslots):NEWLINE mar[event_t].append([])NEWLINE hits_10[event_t].append([])NEWLINENEWLINENEWLINE start = time.time()NEWLINE with torch.no_grad():NEWLINE for batch_idx, data in enumerate(test_loader):NEWLINE data[2] = data[2].float().to(args.device)NEWLINE data[4] = data[4].double().to(args.device)NEWLINE data[5] = data[5].double()NEWLINE output = model(data)NEWLINE loss += (-torch.sum(torch.log(output[0]) + 1e-10) + torch.sum(output[1])).item()NEWLINE for i in range(len(losses)):NEWLINE m1 = output[i].min()NEWLINE m2 = output[i].max()NEWLINE if m1 < losses[i][0]:NEWLINE losses[i][0] = m1NEWLINE if m2 > losses[i][1]:NEWLINE losses[i][1] = m2NEWLINE n_samples += 1NEWLINE A_pred, Survival_term = output[2]NEWLINE u, v, k = data[0], data[1], data[3]NEWLINENEWLINE time_cur = data[5]NEWLINE m, h = MAR(A_pred, u, v, k, Survival_term=Survival_term, freq_prior=freq.H_train_norm if args.freq else None)NEWLINE assert len(time_cur) == len(m) == len(h) == len(k)NEWLINE for t, m, h, k_ in zip(time_cur, m, h, k):NEWLINE d = datetime.datetime.fromtimestamp(t.item()).toordinal()NEWLINE event_t = event_types[k_.item()]NEWLINE for c, slot in enumerate(timeslots):NEWLINE if d <= slot:NEWLINE mar[event_t][c].append(m)NEWLINE hits_10[event_t][c].append(h)NEWLINE if k_ > 0:NEWLINE mar['Com'][c].append(m)NEWLINE hits_10['Com'][c].append(h)NEWLINE if c > 0:NEWLINE assert slot > timeslots[c-1] and d > timeslots[c-1], (d, slot, timeslots[c-1])NEWLINE breakNEWLINENEWLINE if batch_idx % 10 == 0 and args.verbose:NEWLINE print('test', batch_idx)NEWLINENEWLINE if n_test_batches is not None and batch_idx >= n_test_batches - 1:NEWLINE breakNEWLINENEWLINE time_iter = time.time() - startNEWLINENEWLINE print('\nTEST batch={}/{}, loss={:.3f}, psi={}, loss1 min/max={:.4f}/{:.4f}, 'NEWLINE 'loss2 min/max={:.4f}/{:.4f}, integral time stamps={}, sec/iter={:.4f}'.NEWLINE format(batch_idx + 1, len(test_loader), (loss / n_samples),NEWLINE [model.psi[c].item() for c in range(len(model.psi))],NEWLINE losses[0][0], losses[0][1], losses[1][0], losses[1][1],NEWLINE len(model.Lambda_dict), time_iter / (batch_idx + 1)))NEWLINENEWLINE # Report results for different time slots in the test setNEWLINE if args.verbose:NEWLINE for c, slot in enumerate(timeslots):NEWLINE s = 'Slot {}: '.format(c)NEWLINE for event_t in event_types:NEWLINE sfx = '' if event_t == event_types[-1] else ', 'NEWLINE if len(mar[event_t][c]) > 0:NEWLINE s += '{} ({} events): MAR={:.2f}+-{:.2f}, HITS_10={:.3f}+-{:.3f}'.\NEWLINE format(event_t, len(mar[event_t][c]), np.mean(mar[event_t][c]), np.std(mar[event_t][c]),NEWLINE np.mean(hits_10[event_t][c]), np.std(hits_10[event_t][c]))NEWLINE else:NEWLINE s += '{} (no events)'.format(event_t)NEWLINE s += sfxNEWLINE print(s)NEWLINENEWLINE mar_all, hits_10_all = {}, {}NEWLINE for event_t in event_types:NEWLINE mar_all[event_t] = []NEWLINE hits_10_all[event_t] = []NEWLINE for c, slot in enumerate(timeslots):NEWLINE mar_all[event_t].extend(mar[event_t][c])NEWLINE hits_10_all[event_t].extend(hits_10[event_t][c])NEWLINENEWLINE s = 'Epoch {}: results per event type for all test time slots: \n'.format(epoch)NEWLINE print(''.join(['-']*100))NEWLINE for event_t in event_types:NEWLINE if len(mar_all[event_t]) > 0:NEWLINE s += '====== {:10s}\t ({:7s} events): \tMAR={:.2f}+-{:.2f}\t HITS_10={:.3f}+-{:.3f}'.\NEWLINE format(event_t, str(len(mar_all[event_t])), np.mean(mar_all[event_t]), np.std(mar_all[event_t]),NEWLINE np.mean(hits_10_all[event_t]), np.std(hits_10_all[event_t]))NEWLINE else:NEWLINE s += '====== {:10s}\t (no events)'.format(event_t)NEWLINE if event_t != event_types[-1]:NEWLINE s += '\n'NEWLINE print(s)NEWLINE print(''.join(['-'] * 100))NEWLINENEWLINE return mar_all, hits_10_all, loss / n_samplesNEWLINENEWLINENEWLINEdef get_temporal_variables():NEWLINE variables = {}NEWLINE variables['time_bar'] = copy.deepcopy(time_bar)NEWLINE variables['node_degree_global'] = copy.deepcopy(node_degree_global)NEWLINE variables['time_keys'] = copy.deepcopy(model.time_keys)NEWLINE variables['z'] = model.z.clone()NEWLINE variables['S'] = model.S.clone()NEWLINE variables['A'] = model.A.clone()NEWLINE variables['Lambda_dict'] = model.Lambda_dict.clone()NEWLINE return variablesNEWLINENEWLINENEWLINEdef set_temporal_variables(variables, model, train_loader, test_loader):NEWLINE time_bar = copy.deepcopy(variables['time_bar'])NEWLINE train_loader.dataset.time_bar = time_barNEWLINE test_loader.dataset.time_bar = time_barNEWLINE model.node_degree_global = copy.deepcopy(variables['node_degree_global'])NEWLINE model.time_keys = copy.deepcopy(variables['time_keys'])NEWLINE model.z = variables['z'].clone()NEWLINE model.S = variables['S'].clone()NEWLINE model.A = variables['A'].clone()NEWLINE model.Lambda_dict = variables['Lambda_dict'].clone()NEWLINE return time_barNEWLINENEWLINEif __name__ == '__main__':NEWLINENEWLINE parser = argparse.ArgumentParser(description='DyGraphs Training Parameters')NEWLINE parser.add_argument('--data_dir', type=str, default='./')NEWLINE parser.add_argument('--dataset', type=str, default='social', choices=['social', 'github', 'example'])NEWLINE parser.add_argument('--prob', default=0.8, help='filter events by this probability value in the Social Evolution data')NEWLINE parser.add_argument('--batch_size', type=int, default=200, help='batch size (sequence length)')NEWLINE parser.add_argument('--n_hid', type=int, default=32, help='hidden layer size')NEWLINE parser.add_argument('--epochs', type=int, default=5, help='number of epochs')NEWLINE parser.add_argument('--seed', type=int, default=1111, help='random seed')NEWLINE parser.add_argument('--lr', type=float, default=0.0002, help='Learning Rate')NEWLINE parser.add_argument('--lr_decay_step', type=str, default='10',NEWLINE help='number of epochs after which to reduce learning rate')NEWLINE parser.add_argument('--weight', type=float, default=1, help='weight for the second term in the loss')NEWLINE parser.add_argument('--wdecay', type=float, default=0, help='weight decay')NEWLINE parser.add_argument('--model', type=str, default='dyrep', help='trained model', choices=['dyrep', 'gcn', 'gat'])NEWLINE parser.add_argument('--bilinear', action='store_true', default=False, help='use bilinear intensity (omega) model')NEWLINE parser.add_argument('--bilinear_enc', action='store_true', default=False, help='use bilinear NRI')NEWLINE parser.add_argument('--encoder', type=str, default=None, choices=['linear', 'mlp', 'mlp1', 'rand'])NEWLINE parser.add_argument('--sparse', action='store_true', default=False,NEWLINE help='sparsity prior as in some tasks in Kipf et al., ICML 2018')NEWLINE parser.add_argument('--n_rel', type=int, default=2, help='number of edges for learned graphs')NEWLINE parser.add_argument('--device', type=str, default='cuda')NEWLINE parser.add_argument('--association', type=str, default='CloseFriend', help='The long term graph of the Social Evolution data used as long term edges')NEWLINE parser.add_argument('--resume', type=str, default='')NEWLINE parser.add_argument('--log_interval', type=int, default=20, help='print interval')NEWLINE parser.add_argument('--results', type=str, default='results', help='results file path')NEWLINE parser.add_argument('--soft_attn', action='store_true', default=False)NEWLINE parser.add_argument('--freq', action='store_true', default=False, help='use the Frequency bias')NEWLINE parser.add_argument('--verbose', action='store_true', default=False, help='print a lot of debugging stuff and results details')NEWLINENEWLINE args = parser.parse_args()NEWLINENEWLINE args.lr_decay_step = list(map(int, args.lr_decay_step.split(',')))NEWLINE args.torch = torch.__version__NEWLINE print('\n~~~~~ Script arguments ~~~~~')NEWLINE for arg in vars(args):NEWLINE print(arg, getattr(args, arg))NEWLINENEWLINE dt = datetime.datetime.now()NEWLINE print('start time:', dt)NEWLINE experiment_ID = '%s_%06d' % (platform.node(), dt.microsecond)NEWLINE print('experiment_ID: ', experiment_ID)NEWLINENEWLINE try:NEWLINE gitcommit = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()NEWLINE print('gitcommit', gitcommit, '\n')NEWLINE except Exception as e:NEWLINE print('gitcommit is not available', e)NEWLINENEWLINE # Set seedNEWLINE np.random.seed(args.seed)NEWLINE rnd = np.random.RandomState(args.seed)NEWLINE torch.backends.cudnn.deterministic = TrueNEWLINE torch.backends.cudnn.benchmark = TrueNEWLINE torch.manual_seed(args.seed)NEWLINE torch.cuda.manual_seed(args.seed)NEWLINE torch.cuda.manual_seed_all(args.seed)NEWLINENEWLINE if args.dataset == 'social':NEWLINE try:NEWLINE data = SocialEvolutionDataset.load_data(args.data_dir, args.prob)NEWLINE except FileNotFoundError as e:NEWLINE raise ValueError('Original nor preprocessed data not found. Please consult README.md to prepare data before running the code. Error:', e)NEWLINENEWLINE train_set = SocialEvolutionDataset(data['initial_embeddings'], data['train'], args.association, verbose=args.verbose)NEWLINE test_set = SocialEvolutionDataset(data['initial_embeddings'], data['test'], args.association,NEWLINE data_train=data['train'], verbose=args.verbose)NEWLINE initial_embeddings = data['initial_embeddings'].copy()NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE elif args.dataset == 'github':NEWLINE train_set = GithubDataset('train', data_dir=args.data_dir)NEWLINE test_set = GithubDataset('test', data_dir=args.data_dir)NEWLINE initial_embeddings = np.random.randn(train_set.N_nodes, args.n_hid)NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE elif args.dataset == 'example':NEWLINE train_set = ExampleDataset('train')NEWLINE test_set = ExampleDataset('test')NEWLINE initial_embeddings = np.random.randn(train_set.N_nodes, args.n_hid)NEWLINE A_initial = train_set.get_Adjacency()[0]NEWLINE else:NEWLINE raise NotImplementedError(args.dataset)NEWLINENEWLINE def initalize_state(dataset, keepS=False):NEWLINE '''Initializes node embeddings and the graph to the original state after every epoch'''NEWLINENEWLINE Adj_all = dataset.get_Adjacency()[0]NEWLINENEWLINE if not isinstance(Adj_all, list):NEWLINE Adj_all = [Adj_all]NEWLINENEWLINE node_degree_global = []NEWLINE for rel, A in enumerate(Adj_all):NEWLINE node_degree_global.append(np.zeros(A.shape[0]))NEWLINE for u in range(A.shape[0]):NEWLINE node_degree_global[rel][u] = np.sum(A[u])NEWLINENEWLINE Adj_all = Adj_all[0]NEWLINE if args.verbose:NEWLINE print('Adj_all', Adj_all.shape, len(node_degree_global), node_degree_global[0].min(), node_degree_global[0].max())NEWLINE time_bar = np.zeros((dataset.N_nodes, 1)) + dataset.FIRST_DATE.timestamp()NEWLINENEWLINE model.initialize(node_embeddings=initial_embeddings,NEWLINE A_initial=Adj_all, keepS=keepS) # train_loader.dataset.H_trainNEWLINENEWLINENEWLINE model.to(args.device)NEWLINE return time_bar, node_degree_globalNEWLINENEWLINE train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=False)NEWLINE test_loader = DataLoader(test_set, batch_size=args.batch_size, shuffle=False)NEWLINENEWLINE freq = FreqBaseline(train_set, test_set, verbose=args.verbose)NEWLINENEWLINE model = DyRep(node_embeddings=initial_embeddings,NEWLINE N_nodes=train_set.N_nodes,NEWLINE A_initial=A_initial,NEWLINE n_hidden=args.n_hid,NEWLINE bilinear=args.bilinear,NEWLINE bilinear_enc=args.bilinear_enc,NEWLINE sparse=args.sparse,NEWLINE encoder=args.encoder,NEWLINE n_rel=args.n_rel,NEWLINE rnd=rnd,NEWLINE device=args.device,NEWLINE model=args.model,NEWLINE soft_attn=args.soft_attn,NEWLINE freq=freq.H_train_norm if args.freq else None,NEWLINE verbose=args.verbose,NEWLINE node_degree_global=None).to(args.device)NEWLINENEWLINE print('') # new stringNEWLINE if args.verbose:NEWLINE print('model', model)NEWLINE print('number of training parameters: %d' %NEWLINE np.sum([np.prod(p.size()) if p.requires_grad else 0 for p in model.parameters()]))NEWLINENEWLINE params_main, params_enc = [], []NEWLINE for name, param in model.named_parameters():NEWLINE if name.find('encoder') >= 0 and param.requires_grad:NEWLINE params_enc.append(param)NEWLINE elif param.requires_grad:NEWLINE params_main.append(param)NEWLINENEWLINENEWLINE optimizer = optim.Adam([{"params": params_main, "weight_decay": args.wdecay},NEWLINE {"params": params_enc, "weight_decay": 1e-4}], lr=args.lr, betas=(0.5, 0.999))NEWLINE scheduler = lr_scheduler.MultiStepLR(optimizer, args.lr_decay_step, gamma=0.5)NEWLINENEWLINE if args.resume != '':NEWLINE epoch_start, batch_start, time_bar, node_degree_global, experiment_ID = load_checkpoint(args.resume)NEWLINE resume = TrueNEWLINE model.node_degree_global = node_degree_globalNEWLINE else:NEWLINE epoch_start = 1NEWLINE batch_start = 0NEWLINE resume = FalseNEWLINENEWLINENEWLINE losses_events, losses_nonevents, losses_KL, losses_sum = [], [], [], []NEWLINE test_MAR, test_HITS10, test_loss = [], [], []NEWLINE print('\nStarting training...')NEWLINE for epoch in range(epoch_start, args.epochs + 1):NEWLINENEWLINE if not (resume and epoch == epoch_start):NEWLINE # Reinitialize node embeddings and adjacency matrices, but keep the model parameters intactNEWLINE time_bar, node_degree_global = initalize_state(train_loader.dataset, keepS=epoch > 1)NEWLINE model.node_degree_global = node_degree_globalNEWLINENEWLINE train_loader.dataset.time_bar = time_barNEWLINE test_loader.dataset.time_bar = time_barNEWLINENEWLINE start = time.time()NEWLINENEWLINE for batch_idx, data_batch in enumerate(train_loader):NEWLINENEWLINE if resume and batch_idx <= batch_start:NEWLINE continueNEWLINE model.train()NEWLINENEWLINE optimizer.zero_grad()NEWLINE data_batch[2] = data_batch[2].float().to(args.device)NEWLINE data_batch[4] = data_batch[4].double().to(args.device)NEWLINE data_batch[5] = data_batch[5].double() # no need of GPUNEWLINE output = model(data_batch)NEWLINE losses = [-torch.sum(torch.log(output[0]) + 1e-10), args.weight * torch.sum(output[1])] #NEWLINENEWLINE # KL losses (one item per event)NEWLINE if len(output[-1]) > 0:NEWLINE losses.extend(output[-1])NEWLINE losses_KL.append(torch.stack(losses[2:]).sum().item())NEWLINENEWLINE loss = torch.sum(torch.stack(losses)) / args.batch_sizeNEWLINE loss.backward()NEWLINE nn.utils.clip_grad_value_(model.parameters(), 100)NEWLINENEWLINE optimizer.step()NEWLINENEWLINE losses_events.append(losses[0].item())NEWLINE losses_nonevents.append(losses[1].item())NEWLINE losses_sum.append(loss.item())NEWLINENEWLINE assert np.allclose(train_loader.dataset.time_bar, time_bar)NEWLINE assert np.allclose(test_loader.dataset.time_bar, time_bar)NEWLINENEWLINE model.psi.data = torch.clamp(model.psi.data, 1e-1, 1e+3) # to prevent overflow in computing LambdaNEWLINENEWLINE time_iter = time.time() - startNEWLINENEWLINE model.z = model.z.detach() # to reset the computational graph and avoid backpropagating second timeNEWLINE model.S = model.S.detach()NEWLINENEWLINE if (batch_idx + 1) % args.log_interval == 0 or batch_idx == len(train_loader) - 1:NEWLINE # Report (intermediate) resultsNEWLINENEWLINE print('\nTRAIN epoch={}/{}, batch={}/{}, sec/iter: {:.4f}, loss={:.3f}, loss components: {}'.format(epoch,NEWLINE args.epochs,NEWLINE batch_idx + 1,NEWLINE len(train_loader),NEWLINE time_iter / (batch_idx + 1),NEWLINE loss.item(), [l.item() for l in losses]))NEWLINENEWLINE if args.encoder is not None:NEWLINE S = model.S.data.cpu().numpy()NEWLINE S_batch = output[3].sum(axis=0)NEWLINE A_all_first, keys, A_all_last = train_loader.dataset.get_Adjacency(multirelations=True)NEWLINENEWLINE for survey, A_all in zip(['first', 'last'], [A_all_first, A_all_last]):NEWLINE for rel, key in enumerate(keys):NEWLINE if len(A_all.shape) == 2:NEWLINE A_all = A_all[:, :, None]NEWLINENEWLINE A = A_all[:, :, rel].flatten()NEWLINE for edge_type in range(S.shape[2]):NEWLINE prec = average_precision_score(y_true=A, y_score=S[:, :, edge_type].flatten())NEWLINE acc = np.mean(np.equal(A, (S[:, :, edge_type].flatten() > 0).astype(np.float)))NEWLINE auc = roc_auc_score(y_true=A, y_score=S[:, :, edge_type].flatten())NEWLINE c = np.corrcoef(A.flatten(), S[:, :, edge_type].flatten())[0, 1]NEWLINENEWLINE prec_batch = average_precision_score(y_true=A, y_score=S_batch[:, :, edge_type].flatten())NEWLINE acc_batch = np.mean(np.equal(A, (S_batch[:, :, edge_type].flatten() > 0).astype(np.float)))NEWLINE auc_batch = roc_auc_score(y_true=A, y_score=S_batch[:, :, edge_type].flatten())NEWLINE c_batch = np.corrcoef(A.flatten(), S_batch[:, :, edge_type].flatten())[0, 1]NEWLINENEWLINE print('{}: Edge {} with {}: acc={:.4f}, auc={:.4f}, prec={:.4f}, corr={:.4f}, 'NEWLINE 'acc_batch={:.4f}, auc_batch={:.4f}, prec_batch={:.4f}, corr_batch={:.4f}'.NEWLINE format(survey, edge_type, key, acc, auc, prec, c,NEWLINE acc_batch, auc_batch, prec_batch, c_batch))NEWLINENEWLINE for edge_type in range(S.shape[2]):NEWLINE c = np.corrcoef(freq.H_train.flatten(), S[:, :, edge_type].flatten())[0, 1]NEWLINE c_batch = np.corrcoef(freq.H_train.flatten(), S_batch[:, :, edge_type].flatten())[0, 1]NEWLINE print('Edge {} with H_train: corr={:.4f}, corr_batch={:.4f}'.format(edge_type, c, c_batch))NEWLINENEWLINENEWLINE # save node embeddings and other data before testing since these variables will be updated during testingNEWLINE variables = get_temporal_variables()NEWLINE if args.verbose:NEWLINE print('time', datetime.datetime.fromtimestamp(np.max(time_bar)))NEWLINE save_checkpoint(batch_idx + 1, epoch)NEWLINENEWLINE result = test(model, n_test_batches=None if batch_idx == len(train_loader) - 1 else 10, epoch=epoch)NEWLINE test_MAR.append(np.mean(result[0]['Com']))NEWLINE test_HITS10.append(np.mean(result[1]['Com']))NEWLINE test_loss.append(result[2])NEWLINENEWLINENEWLINE # restore node embeddings and other dataNEWLINE time_bar = set_temporal_variables(variables, model, train_loader, test_loader)NEWLINENEWLINE scheduler.step()NEWLINENEWLINENEWLINE print('end time:', datetime.datetime.now())NEWLINENEWLINE
#This file was created by Tate HaganNEWLINEimport tkinter as tkNEWLINEfrom InputGUISoloDebug import InputGUINEWLINENEWLINEroot = tk.Tk()NEWLINENEWLINEcontainer = tk.Frame(root)NEWLINEcontainer.pack(side="top", fill="both", expand=True)NEWLINEcontainer.grid_rowconfigure(0, weight=1)NEWLINEcontainer.grid_columnconfigure(0, weight=1)NEWLINEframes = {}NEWLINEF = InputGUINEWLINEpage_name = F.__name__NEWLINEframe = F(parent=container)NEWLINEframes[page_name] = frameNEWLINEframe.grid(row=0, column=0, sticky="nsew")NEWLINEshowframe = frames[page_name]NEWLINEshowframe.tkraise()NEWLINENEWLINEroot.mainloop()
#!/usr/bin/env pythonNEWLINE# -*- coding: utf-8 -*-NEWLINEimport jsonNEWLINENEWLINEfrom alipay.aop.api.constant.ParamConstants import *NEWLINENEWLINENEWLINEclass FengdieActivityCreatePageData(object):NEWLINENEWLINE def __init__(self):NEWLINE self._name = NoneNEWLINE self._schema_data = NoneNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE return self._nameNEWLINENEWLINE @name.setterNEWLINE def name(self, value):NEWLINE self._name = valueNEWLINE @propertyNEWLINE def schema_data(self):NEWLINE return self._schema_dataNEWLINENEWLINE @schema_data.setterNEWLINE def schema_data(self, value):NEWLINE self._schema_data = valueNEWLINENEWLINENEWLINE def to_alipay_dict(self):NEWLINE params = dict()NEWLINE if self.name:NEWLINE if hasattr(self.name, 'to_alipay_dict'):NEWLINE params['name'] = self.name.to_alipay_dict()NEWLINE else:NEWLINE params['name'] = self.nameNEWLINE if self.schema_data:NEWLINE if hasattr(self.schema_data, 'to_alipay_dict'):NEWLINE params['schema_data'] = self.schema_data.to_alipay_dict()NEWLINE else:NEWLINE params['schema_data'] = self.schema_dataNEWLINE return paramsNEWLINENEWLINE @staticmethodNEWLINE def from_alipay_dict(d):NEWLINE if not d:NEWLINE return NoneNEWLINE o = FengdieActivityCreatePageData()NEWLINE if 'name' in d:NEWLINE o.name = d['name']NEWLINE if 'schema_data' in d:NEWLINE o.schema_data = d['schema_data']NEWLINE return oNEWLINENEWLINENEWLINE
import pytestNEWLINEfrom numerous.engine.model.external_mappings import ExternalMappingElementNEWLINENEWLINEfrom numerous.utils.data_loader import InMemoryDataLoaderNEWLINEfrom pytest import approxNEWLINENEWLINEfrom numerous.engine.model.external_mappings.interpolation_type import InterpolationTypeNEWLINEfrom numerous.engine.model import ModelNEWLINEfrom numerous.engine.simulation import SimulationNEWLINENEWLINEfrom numerous.engine.system import Subsystem, ConnectorItem, Item, ConnectorTwoWayNEWLINEfrom numerous import EquationBase, EquationNEWLINEfrom numerous.engine.simulation.solvers.base_solver import solver_typesNEWLINEfrom tests.test_equations import TestEq_ground, Test_Eq, TestEq_inputNEWLINENEWLINENEWLINE@pytest.fixture(autouse=True)NEWLINEdef run_before_and_after_tests():NEWLINE import shutilNEWLINE shutil.rmtree('./tmp', ignore_errors=True)NEWLINE yieldNEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef test_eq1():NEWLINE class TestEq1(EquationBase):NEWLINE def __init__(self, P=10):NEWLINE super().__init__(tag='example_1')NEWLINE self.add_parameter('P', P)NEWLINE self.add_state('T1', 0)NEWLINE self.add_state('T2', 0)NEWLINE self.add_state('T3', 0)NEWLINE self.add_state('T4', 0)NEWLINE # self.add_parameter('T_4', 0)NEWLINE self.add_constant('TG', 10)NEWLINE self.add_constant('R1', 10)NEWLINE self.add_constant('R2', 5)NEWLINE self.add_constant('R3', 3)NEWLINE self.add_constant('RG', 2)NEWLINENEWLINE @Equation()NEWLINE def eval(self, scope):NEWLINE scope.T1_dot = scope.P - (scope.T1 - scope.T2) / scope.R1NEWLINE scope.T2_dot = (scope.T1 - scope.T2) / scope.R1 - (scope.T2 - scope.T3) / scope.R2NEWLINE scope.T3_dot = (scope.T2 - scope.T3) / scope.R2 - (scope.T3 - scope.T4) / scope.R3NEWLINE scope.T4_dot = (scope.T3 - scope.T4) / scope.R3 - (scope.T4 - scope.TG) / scope.RGNEWLINENEWLINE return TestEq1(P=100)NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef simple_item(test_eq1):NEWLINE class T1(Item):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINENEWLINE t1.add_equations([test_eq1])NEWLINENEWLINE return T1('test_item')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms1(simple_item):NEWLINE class S1(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINE self.register_items([simple_item])NEWLINENEWLINE return S1('S1')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms2():NEWLINE class I(Item):NEWLINE def __init__(self, tag, P, T, R):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_input(P=P, T=T, R=R)])NEWLINENEWLINE class T(Item):NEWLINE def __init__(self, tag, T, R):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([Test_Eq(T=T, R=R)])NEWLINENEWLINE class G(Item):NEWLINE def __init__(self, tag, TG, RG):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_ground(TG=TG, RG=RG)])NEWLINENEWLINE class S2(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE input = I('1', P=100, T=0, R=10)NEWLINE item1 = T('2', T=0, R=5)NEWLINE item2 = T('3', T=0, R=3)NEWLINE item3 = T('4', T=0, R=2)NEWLINE ## RG is redundant we use item3.R as a last value of R in a chainNEWLINE ground = G('5', TG=10, RG=2)NEWLINENEWLINE input.t1.T_o.add_mapping(item1.t1.T)NEWLINENEWLINE # item1.bind(input=input, output=item2)NEWLINENEWLINE item1.t1.R_i.add_mapping(input.t1.R)NEWLINE item1.t1.T_i.add_mapping(input.t1.T)NEWLINE item1.t1.T_o.add_mapping(item2.t1.T)NEWLINE # t_0 = item1.t1.T_oNEWLINE # item1.t1.T_o = item2.t1.TNEWLINENEWLINE item2.t1.R_i.add_mapping(item1.t1.R)NEWLINE item2.t1.T_i.add_mapping(item1.t1.T)NEWLINE item2.t1.T_o.add_mapping(item3.t1.T)NEWLINENEWLINE item3.t1.R_i.add_mapping(item2.t1.R)NEWLINE item3.t1.T_i.add_mapping(item2.t1.T)NEWLINE item3.t1.T_o.add_mapping(ground.t1.T)NEWLINENEWLINE self.register_items([input, item1, item2, item3, ground])NEWLINENEWLINE return S2('S2')NEWLINENEWLINENEWLINE@pytest.fixtureNEWLINEdef ms3():NEWLINE class I(ConnectorItem):NEWLINE def __init__(self, tag, P, T, R):NEWLINE super(I, self).__init__(tag)NEWLINENEWLINE self.create_binding('output')NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINENEWLINE t1.add_equations([TestEq_input(P=P, T=T, R=R)])NEWLINE ##this line has to be after t1.add_equations since t1 inside output is created thereNEWLINE self.output.t1.create_variable(name='T')NEWLINE t1.T_o = self.output.t1.TNEWLINENEWLINE class T(ConnectorTwoWay):NEWLINE def __init__(self, tag, T, R):NEWLINE super().__init__(tag, side1_name='input', side2_name='output')NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([Test_Eq(T=T, R=R)])NEWLINENEWLINE t1.R_i = self.input.t1.RNEWLINE t1.T_i = self.input.t1.TNEWLINENEWLINE ##we ask for variable TNEWLINE t1.T_o = self.output.t1.TNEWLINENEWLINE class G(Item):NEWLINE def __init__(self, tag, TG, RG):NEWLINE super().__init__(tag)NEWLINENEWLINE t1 = self.create_namespace('t1')NEWLINE t1.add_equations([TestEq_ground(TG=TG, RG=RG)])NEWLINENEWLINE # ##since we asked for variable T in binding we have to create variable T and map it to TGNEWLINE # t1.create_variable('T')NEWLINE # t1.T = t1.TGNEWLINENEWLINE class S3(Subsystem):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE input = I('1', P=100, T=0, R=10)NEWLINE item1 = T('2', T=0, R=5)NEWLINE item2 = T('3', T=0, R=3)NEWLINE item3 = T('4', T=0, R=2)NEWLINE ## RG is redundant we use item3.R as a last value of R in a chainNEWLINE ground = G('5', TG=10, RG=2)NEWLINENEWLINE input.bind(output=item1)NEWLINENEWLINE item1.bind(input=input, output=item2)NEWLINENEWLINE item2.bind(input=item1, output=item3)NEWLINE item3.bind(input=item2, output=ground)NEWLINENEWLINE self.register_items([input, item1, item2, item3, ground])NEWLINENEWLINE return S3('S3')NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_model_var_referencing(ms1, solver, use_llvm):NEWLINE m1 = Model(ms1, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(list(m1.states_as_vector[::-1]), rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.skip(reason="Functionality not implemented in current version")NEWLINEdef test_model_save_only_aliases(ms3, solver):NEWLINE of = OutputFilter(only_aliases=True)NEWLINE m1 = Model(ms3, historian_filter=of)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert m1.historian_df.emptyNEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.skip(reason="Functionality not implemented in current version")NEWLINEdef test_model_save_only_aliases2(ms3, solver):NEWLINE of = OutputFilter(only_aliases=True)NEWLINE m1 = Model(ms3, historian_filter=of)NEWLINE item = m1.search_items('2')[0]NEWLINE columns_number = 0NEWLINE for i, var in enumerate(item.get_variables()):NEWLINE var[0].alias = str(i)NEWLINE columns_number += 1NEWLINENEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert m1.historian_df.columns.size == columns_numberNEWLINENEWLINENEWLINEdef test_1_item_model(ms1):NEWLINE m1 = Model(ms1)NEWLINE item = m1.search_items('test_item')[0]NEWLINE assert item.t1.P.value == 100NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_callback_step_item_model(ms3, solver, use_llvm):NEWLINE def action(time, variables):NEWLINE if int(time) == 119:NEWLINE raise ValueError("Overflow of state. time:119")NEWLINENEWLINE def condition(time, states):NEWLINE return 500 - states['S3.3.t1.T']NEWLINENEWLINE def action2(time, variables):NEWLINE if int(time) == 118:NEWLINE raise ValueError("Overflow of state. time:119")NEWLINENEWLINE def condition2(time, states):NEWLINE return 500 - states['S3.3.t1.T']NEWLINENEWLINE m1 = Model(ms3, use_llvm=use_llvm)NEWLINE m1.add_event("simple", condition, action)NEWLINE m1.add_event("simple2", condition2, action2)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE with pytest.raises(ValueError, match=r".*time:119.*"):NEWLINE s1.solve()NEWLINENEWLINENEWLINEdef test_add_item_twice_with_same_tag(ms2):NEWLINE class Item_(Item):NEWLINE def __init__(self, tag):NEWLINE super().__init__(tag)NEWLINENEWLINE with pytest.raises(ValueError, match=r".*already registered in system.*"):NEWLINE ms2.register_items([Item_('1')])NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_model(ms2, solver, use_llvm):NEWLINE m1 = Model(ms2, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model_nested(ms3, solver, use_llvm):NEWLINE ms4 = Subsystem('new_s')NEWLINE ms4.register_item(ms3)NEWLINE m1 = Model(ms4, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=10, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model_nested2(ms3, solver, use_llvm):NEWLINE ms4 = Subsystem('new_s4')NEWLINE ms4.register_item(ms3)NEWLINE ms5 = Subsystem('new_s5')NEWLINE ms5.register_item(ms3)NEWLINE ms6 = Subsystem('new_s6')NEWLINE ms6.register_item(ms4)NEWLINE ms6.register_item(ms5)NEWLINE ms7 = Subsystem('new_s7')NEWLINE ms7.register_item(ms6)NEWLINE m1 = Model(ms7, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE s1.solve()NEWLINE assert len(m1.path_variables) == 50NEWLINE assert len(m1.variables) == 25NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_chain_item_binding_model(ms3, solver, use_llvm):NEWLINE m1 = Model(ms3, use_llvm=use_llvm)NEWLINE s1 = Simulation(m1, t_start=0, t_stop=1000, num=100, solver_type=solver)NEWLINE s1.solve()NEWLINE assert approx(m1.states_as_vector, rel=0.01) == [2010, 1010, 510, 210]NEWLINENEWLINENEWLINEclass StaticDataTest(EquationBase, Item):NEWLINE def __init__(self, tag="tm"):NEWLINE super(StaticDataTest, self).__init__(tag)NEWLINENEWLINE ##will map to variable with the same path in external dataframe/datasourceNEWLINE self.add_parameter('T1', 0)NEWLINE self.add_parameter('T2', 0)NEWLINE self.add_parameter('T_i1', 0)NEWLINE self.add_parameter('T_i2', 0)NEWLINE mechanics = self.create_namespace('test_nm')NEWLINE mechanics.add_equations([self])NEWLINENEWLINE @Equation()NEWLINE def eval(self, scope):NEWLINE scope.T_i1 = scope.T1NEWLINE scope.T_i2 = scope.T2NEWLINENEWLINENEWLINEclass StaticDataSystem(Subsystem):NEWLINE def __init__(self, tag, n=1):NEWLINE super().__init__(tag)NEWLINE o_s = []NEWLINE for i in range(n):NEWLINE o = StaticDataTest('tm' + str(i))NEWLINE o_s.append(o)NEWLINE # Register the items to the subsystem to make it recognize them.NEWLINE self.register_items(o_s)NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_external_data(solver, use_llvm):NEWLINE external_mappings = []NEWLINENEWLINE import pandas as pdNEWLINE import numpy as npNEWLINENEWLINE data = {'time': np.arange(100),NEWLINE 'Dew Point Temperature {C}': np.arange(100) + 1,NEWLINE 'Dry Bulb Temperature {C}': np.arange(100) + 2,NEWLINE }NEWLINENEWLINE df = pd.DataFrame(data, columns=['time', 'Dew Point Temperature {C}', 'Dry Bulb Temperature {C}'])NEWLINE index_to_timestep_mapping = 'time'NEWLINE index_to_timestep_mapping_start = 0NEWLINE dataframe_aliases = {NEWLINE 'system_external.tm0.test_nm.T1': ("Dew Point Temperature {C}", InterpolationType.PIESEWISE),NEWLINE 'system_external.tm0.test_nm.T2': ('Dry Bulb Temperature {C}', InterpolationType.PIESEWISE)NEWLINE }NEWLINE external_mappings.append(ExternalMappingElementNEWLINE ("inmemory", index_to_timestep_mapping, index_to_timestep_mapping_start, 1,NEWLINE dataframe_aliases))NEWLINE data_loader = InMemoryDataLoader(df)NEWLINE s = Simulation(NEWLINE Model(StaticDataSystem('system_external', n=1), use_llvm=use_llvm, external_mappings=external_mappings,NEWLINE data_loader=data_loader),NEWLINE t_start=0, t_stop=100.0, num=100, num_inner=100, max_step=.1, solver_type=solverNEWLINE )NEWLINE s.solve()NEWLINE assert approx(np.array(s.model.historian_df['system_external.tm0.test_nm.T_i1'])[1:]) == np.arange(101)[1:]NEWLINE assert approx(np.array(s.model.historian_df['system_external.tm0.test_nm.T_i2'])[1:]) == np.arange(101)[1:] + 1NEWLINENEWLINENEWLINE@pytest.mark.parametrize("solver", solver_types)NEWLINE@pytest.mark.parametrize("use_llvm", [True, False])NEWLINEdef test_static_system(solver, use_llvm):NEWLINE import numpy as npNEWLINE s = Simulation(NEWLINE Model(StaticDataSystem('system_static', n=1), use_llvm=use_llvm),NEWLINE t_start=0, t_stop=100.0, num=100, num_inner=100, max_step=.1, solver_type=solverNEWLINE )NEWLINE s.solve()NEWLINE assert approx(np.array(s.model.historian_df['system_static.tm0.test_nm.T_i1'])[1:]) == np.repeat(0, (100))NEWLINE assert approx(np.array(s.model.historian_df['system_static.tm0.test_nm.T_i2'])[1:]) == np.repeat(0, (100))NEWLINE
# Copyright 2015 The Chromium Authors. All rights reserved.NEWLINE# Use of this source code is governed by a BSD-style license that can beNEWLINE# found in the LICENSE file.NEWLINE"""NEWLINEGenerator that produces an externs file for the Closure Compiler.NEWLINENote: This is a work in progress, and generated externs may require tweaking.NEWLINENEWLINESee https://developers.google.com/closure/compiler/docs/api-tutorial3#externsNEWLINE"""NEWLINENEWLINEfrom code import CodeNEWLINEfrom js_util import JsUtilNEWLINEfrom model import *NEWLINEfrom schema_util import *NEWLINENEWLINEimport osNEWLINEimport sysNEWLINEimport reNEWLINENEWLINENOTE = """// NOTE: The format of types has changed. 'FooType' is nowNEWLINE// 'chrome.%s.FooType'.NEWLINE// Please run the closure compiler before committing changes.NEWLINE// See https://chromium.googlesource.com/chromium/src/+/master/docs/closure_compilation.mdNEWLINE"""NEWLINENEWLINEclass JsExternsGenerator(object):NEWLINE def Generate(self, namespace):NEWLINE return _Generator(namespace).Generate()NEWLINENEWLINEclass _Generator(object):NEWLINE def __init__(self, namespace):NEWLINE self._namespace = namespaceNEWLINE self._class_name = NoneNEWLINE self._js_util = JsUtil()NEWLINENEWLINE def Generate(self):NEWLINE """Generates a Code object with the schema for the entire namespace.NEWLINE """NEWLINE c = Code()NEWLINE # /abs/path/src/tools/json_schema_compiler/NEWLINE script_dir = os.path.dirname(os.path.abspath(__file__))NEWLINE # /abs/path/src/NEWLINE src_root = os.path.normpath(os.path.join(script_dir, '..', '..'))NEWLINE # tools/json_schema_compiler/NEWLINE src_to_script = os.path.relpath(script_dir, src_root)NEWLINE # tools/json_schema_compiler/compiler.pyNEWLINE compiler_path = os.path.join(src_to_script, 'compiler.py')NEWLINE (c.Append(self._GetHeader(compiler_path, self._namespace.name))NEWLINE .Append())NEWLINENEWLINE self._AppendNamespaceObject(c)NEWLINENEWLINE for js_type in self._namespace.types.values():NEWLINE self._AppendType(c, js_type)NEWLINENEWLINE for function in self._namespace.functions.values():NEWLINE self._AppendFunction(c, function)NEWLINENEWLINE for event in self._namespace.events.values():NEWLINE self._AppendEvent(c, event)NEWLINENEWLINE c.TrimTrailingNewlines()NEWLINENEWLINE return cNEWLINENEWLINE def _GetHeader(self, tool, namespace):NEWLINE """Returns the file header text.NEWLINE """NEWLINE return (self._js_util.GetLicense() + '\n' +NEWLINE self._js_util.GetInfo(tool) + (NOTE % namespace) + '\n' +NEWLINE ('/** @fileoverview Externs generated from namespace: %s */' %NEWLINE namespace))NEWLINENEWLINE def _AppendType(self, c, js_type):NEWLINE """Given a Type object, generates the Code for this type's definition.NEWLINE """NEWLINE if js_type.property_type is PropertyType.ENUM:NEWLINE self._AppendEnumJsDoc(c, js_type)NEWLINE else:NEWLINE self._AppendTypeJsDoc(c, js_type)NEWLINE c.Append()NEWLINENEWLINE def _AppendEnumJsDoc(self, c, js_type):NEWLINE """ Given an Enum Type object, generates the Code for the enum's definition.NEWLINE """NEWLINE (c.Sblock(line='/**', line_prefix=' * ')NEWLINE .Append('@enum {string}')NEWLINE .Append(self._js_util.GetSeeLink(self._namespace.name, 'type',NEWLINE js_type.simple_name))NEWLINE .Eblock(' */'))NEWLINE c.Append('%s.%s = {' % (self._GetNamespace(), js_type.name))NEWLINENEWLINE def get_property_name(e):NEWLINE # Enum properties are normified to be in ALL_CAPS_STYLE.NEWLINE # Assume enum '1ring-rulesThemAll'.NEWLINE # Transform to '1ring-rules_Them_All'.NEWLINE e = re.sub(r'([a-z])([A-Z])', r'\1_\2', e)NEWLINE # Transform to '1ring_rules_Them_All'.NEWLINE e = re.sub(r'\W', '_', e)NEWLINE # Transform to '_1ring_rules_Them_All'.NEWLINE e = re.sub(r'^(\d)', r'_\1', e)NEWLINE # Transform to '_1RING_RULES_THEM_ALL'.NEWLINE return e.upper()NEWLINENEWLINE c.Append('\n'.join(NEWLINE [" %s: '%s'," % (get_property_name(v.name), v.name)NEWLINE for v in js_type.enum_values]))NEWLINE c.Append('};')NEWLINENEWLINE def _IsTypeConstructor(self, js_type):NEWLINE """Returns true if the given type should be a @constructor. If this returnsNEWLINE false, the type is a typedef.NEWLINE """NEWLINE return any(prop.type_.property_type is PropertyType.FUNCTIONNEWLINE for prop in js_type.properties.values())NEWLINENEWLINE def _AppendTypeJsDoc(self, c, js_type, optional=False):NEWLINE """Appends the documentation for a type as a Code.NEWLINE """NEWLINE c.Sblock(line='/**', line_prefix=' * ')NEWLINENEWLINE if js_type.description:NEWLINE for line in js_type.description.splitlines():NEWLINE c.Append(line)NEWLINENEWLINE if js_type.jsexterns:NEWLINE for line in js_type.jsexterns.splitlines():NEWLINE c.Append(line)NEWLINENEWLINE is_constructor = self._IsTypeConstructor(js_type)NEWLINE if js_type.property_type is not PropertyType.OBJECT:NEWLINE self._js_util.AppendTypeJsDoc(c, self._namespace.name, js_type, optional)NEWLINE elif is_constructor:NEWLINE c.Comment('@constructor', comment_prefix = '', wrap_indent=4)NEWLINE c.Comment('@private', comment_prefix = '', wrap_indent=4)NEWLINE else:NEWLINE self._AppendTypedef(c, js_type.properties)NEWLINENEWLINE c.Append(self._js_util.GetSeeLink(self._namespace.name, 'type',NEWLINE js_type.simple_name))NEWLINE c.Eblock(' */')NEWLINENEWLINE var = '%s.%s' % (self._GetNamespace(), js_type.simple_name)NEWLINE if is_constructor: var += ' = function() {}'NEWLINE var += ';'NEWLINE c.Append(var)NEWLINENEWLINE if is_constructor:NEWLINE c.Append()NEWLINE self._class_name = js_type.nameNEWLINE for prop in js_type.properties.values():NEWLINE if prop.type_.property_type is PropertyType.FUNCTION:NEWLINE self._AppendFunction(c, prop.type_.function)NEWLINE else:NEWLINE self._AppendTypeJsDoc(c, prop.type_, prop.optional)NEWLINE c.Append()NEWLINE self._class_name = NoneNEWLINENEWLINE def _AppendTypedef(self, c, properties):NEWLINE """Given an OrderedDict of properties, Appends code containing a @typedef.NEWLINE """NEWLINE if not properties: returnNEWLINENEWLINE c.Append('@typedef {')NEWLINE self._js_util.AppendObjectDefinition(c, self._namespace.name, properties,NEWLINE new_line=False)NEWLINE c.Append('}', new_line=False)NEWLINENEWLINE def _AppendFunction(self, c, function):NEWLINE """Appends the code representing a function, including its documentation.NEWLINE For example:NEWLINENEWLINE /**NEWLINE * @param {string} title The new title.NEWLINE */NEWLINE chrome.window.setTitle = function(title) {};NEWLINE """NEWLINE self._js_util.AppendFunctionJsDoc(c, self._namespace.name, function)NEWLINE params = self._GetFunctionParams(function)NEWLINE c.Append('%s.%s = function(%s) {};' % (self._GetNamespace(),NEWLINE function.name, params))NEWLINE c.Append()NEWLINENEWLINE def _AppendEvent(self, c, event):NEWLINE """Appends the code representing an event.NEWLINE For example:NEWLINENEWLINE /** @type {!ChromeEvent} */NEWLINE chrome.bookmarks.onChildrenReordered;NEWLINE """NEWLINE c.Sblock(line='/**', line_prefix=' * ')NEWLINE if (event.description):NEWLINE c.Comment(event.description, comment_prefix='')NEWLINE c.Append('@type {!ChromeEvent}')NEWLINE c.Append(self._js_util.GetSeeLink(self._namespace.name, 'event',NEWLINE event.name))NEWLINE c.Eblock(' */')NEWLINE c.Append('%s.%s;' % (self._GetNamespace(), event.name))NEWLINE c.Append()NEWLINENEWLINE def _AppendNamespaceObject(self, c):NEWLINE """Appends the code creating namespace object.NEWLINE For example:NEWLINENEWLINE /**NEWLINE * @constNEWLINE */NEWLINE chrome.bookmarks = {};NEWLINE """NEWLINE c.Append("""/**NEWLINE * @constNEWLINE */""")NEWLINE c.Append('chrome.%s = {};' % self._namespace.name)NEWLINE c.Append()NEWLINENEWLINE def _GetFunctionParams(self, function):NEWLINE """Returns the function params string for function.NEWLINE """NEWLINE params = function.params[:]NEWLINE if function.callback:NEWLINE params.append(function.callback)NEWLINE return ', '.join(param.name for param in params)NEWLINENEWLINE def _GetNamespace(self):NEWLINE """Returns the namespace to be prepended to a top-level typedef.NEWLINENEWLINE For example, it might return "chrome.namespace".NEWLINENEWLINE Also optionally includes the class name if this is in the contextNEWLINE of outputting the members of a class.NEWLINENEWLINE For example, "chrome.namespace.ClassName.prototype"NEWLINE """NEWLINE if self._class_name:NEWLINE return 'chrome.%s.%s.prototype' % (self._namespace.name, self._class_name)NEWLINE return 'chrome.%s' % self._namespace.nameNEWLINE
"""NEWLINESpontaneous nuclear decay.NEWLINENEWLINEPackage:NEWLINE RoadNarrows elements package.NEWLINENEWLINEFile:NEWLINE nucleardecay.pyNEWLINENEWLINELink:NEWLINE https://github.com/roadnarrows-robotics/NEWLINENEWLINECopyright:NEWLINE (c) 2019. RoadNarrows LLCNEWLINE http://www.roadnarrows.comNEWLINE All Rights ReservedNEWLINENEWLINELicense:NEWLINE MITNEWLINE"""NEWLINENEWLINEimport mathNEWLINEfrom enum import EnumNEWLINEimport randomNEWLINENEWLINEfrom elemenpy.core.common import (enumfactory, isderivedinstance, enum_to_str)NEWLINEfrom elemenpy.core.format import (default_encoder, fInfNum)NEWLINEfrom elemenpy.core.prettyprint import (print2cols)NEWLINENEWLINEfrom elemenpy.sm.lepton import (Electron, Positron,NEWLINE ElectronNeutrino, ElectronAntiNeutrino)NEWLINEfrom elemenpy.sm.boson import (Photon)NEWLINEfrom elemenpy.sm.baryon import (Proton, Neutron)NEWLINENEWLINEfrom elemenpy.elem.atomicnucleus import (AtomicNucleus)NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# DecayMode EnumerationNEWLINE# -----------------------------------------------------------------------------NEWLINEclass DecayMode(Enum):NEWLINE """NEWLINE Spontaneous nuclear radioactive decay modes of a radionuclide.NEWLINENEWLINE See: https://en.wikipedia.org/wiki/Radioactive_decayNEWLINE https://en.wikipedia.org/Nuclear_fissionNEWLINE """NEWLINE UNKNOWN = 0 # unknownNEWLINE STABLE = 1 # stable isotopeNEWLINENEWLINE # decays with emission of nucleonsNEWLINE ALPHA_DECAY = 2 # alpha partical emittedNEWLINE PROTON_EMISSION = 3 # proton ejectedNEWLINE NEUTRON_EMISSION = 4 # neutron ejectedNEWLINE DOUBLE_PROTON_EMISSION = 5 # two protons simultaneously ejectedNEWLINE SPONTANEOUS_FISSION = 6 # Nucleus disintegrationNEWLINE CLUSTER_DECAY = 7 # Small nucleus larger than alph emittedNEWLINENEWLINE # beta decaysNEWLINE BETA_DECAY = 8 # electron and electron anitneutrino emittedNEWLINE POSITRON_DECAY = 9 # positron and electron neutrino emitted (beta+)NEWLINE ELECTRON_CAPTURE = 10 # nucleus captures electronNEWLINE BOUND_STATE_BETA_DECAY = 11 # beta decay with electron shell captureNEWLINE DOUBLE_BETA_DECAY = 12 # 2 electrons and 2 electron anitneutrinosNEWLINE DOUBLE_ELECTRON_CAPTURE = 13 # nucleus absorbs 2 electrons, emits 2 neutrinosNEWLINE ELECTRON_CAPUTRE_POSITRON_EMISSION = 14 # nucleus absorms electron, emits posNEWLINE DOUBLE_POSITRON_EMISSION = 15 # 2 positrons and 2 neutrions emittedNEWLINENEWLINE # transitionsNEWLINE ISOMERIC_TRANSITION = 16 # excited nucleus release high-energy photonNEWLINE INTERNAL_TRANSITION = 17 # excited nucleus transfers energy to ejected e NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# Beta- ClassNEWLINE# -----------------------------------------------------------------------------NEWLINEclass BetaN(Electron):NEWLINE Name = 'Beta-'NEWLINE Symbol = default_encoder('$greek(beta)$sup(-)')NEWLINENEWLINE def __init__(self):NEWLINE Electron.__init__(self)NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# Beta+ ClassNEWLINE# -----------------------------------------------------------------------------NEWLINEclass BetaP(Positron):NEWLINE Name = 'Beta+'NEWLINE Symbol = default_encoder('$greek(beta)$sup(+)')NEWLINENEWLINE def __init__(self):NEWLINE Positron.__init__(self)NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# Alpha ClassNEWLINE# -----------------------------------------------------------------------------NEWLINEclass Alpha(AtomicNucleus):NEWLINE def __init__(self):NEWLINE AtomicNucleus.__init__(self, 2, 4, name='alpha', symbol='$greek(alpha)')NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# Baked Pre-Computed Decay InformationNEWLINE# -----------------------------------------------------------------------------NEWLINEBakedInfo = {NEWLINE DecayMode.STABLE: {NEWLINE 'dAdZ': (0, 0), 'emission': [], 'capture': []NEWLINE },NEWLINE NEWLINE # decays with emission of nucleonsNEWLINE DecayMode.ALPHA_DECAY: {NEWLINE 'dAdZ': (-4, -2), 'emission': [Alpha], 'capture': []NEWLINE },NEWLINE DecayMode.PROTON_EMISSION: {NEWLINE 'dAdZ': (-1, -1), 'emission': [Proton], 'capture': []NEWLINE },NEWLINE DecayMode.NEUTRON_EMISSION: {NEWLINE 'dAdZ': (-1, 0), 'emission': [Neutron], 'capture': []NEWLINE },NEWLINE DecayMode.DOUBLE_PROTON_EMISSION: {NEWLINE 'dAdZ': (-2, -2), 'emission': [Proton] * 2, 'capture': []NEWLINE },NEWLINE DecayMode.SPONTANEOUS_FISSION: {NEWLINE 'dAdZ': (0, 0),NEWLINE 'emission': [], # calculated on required daughter nucleiNEWLINE 'capture': [],NEWLINE }, # calculatedNEWLINE DecayMode.CLUSTER_DECAY: {NEWLINE 'dAdZ': (0, 0),NEWLINE 'emission': [], # calculated on required daughter nucleiNEWLINE 'capture': [],NEWLINE },NEWLINE NEWLINE # beta decaysNEWLINE DecayMode.BETA_DECAY: {NEWLINE 'dAdZ': (0, 1), 'emission': [BetaN, ElectronAntiNeutrino], 'capture': []NEWLINE },NEWLINE DecayMode.POSITRON_DECAY: {NEWLINE 'dAdZ': (0, -1), 'emission': [BetaP, ElectronNeutrino], 'capture': []NEWLINE },NEWLINE DecayMode.ELECTRON_CAPTURE: {NEWLINE 'dAdZ': (0, -1), 'emission': [ElectronNeutrino], 'capture': [Electron]NEWLINE },NEWLINE DecayMode.BOUND_STATE_BETA_DECAY: {NEWLINE 'dAdZ': (0, 1),NEWLINE 'emission': [ElectronAntiNeutrino],NEWLINE 'capture': [Electron] # captured into empty K-shellNEWLINE },NEWLINE DecayMode.DOUBLE_BETA_DECAY: {NEWLINE 'dAdZ': (0, 2),NEWLINE 'emission': [Electron, ElectronAntiNeutrino] * 2,NEWLINE 'capture': []NEWLINE },NEWLINE DecayMode.DOUBLE_ELECTRON_CAPTURE: {NEWLINE 'dAdZ': (0, -2),NEWLINE 'emission': [ElectronNeutrino] * 2,NEWLINE 'capture': [Electron] * 2 # from orbital electronNEWLINE },NEWLINE DecayMode.ELECTRON_CAPUTRE_POSITRON_EMISSION: {NEWLINE 'dAdZ': (0, -2),NEWLINE 'emission': [Positron, ElectronNeutrino, ElectronNeutrino],NEWLINE 'capture': [Electron] # from orbital electronNEWLINE },NEWLINE DecayMode.DOUBLE_POSITRON_EMISSION: {NEWLINE 'dAdZ': (0, -2),NEWLINE 'emission': [Positron, ElectronNeutrino] * 2,NEWLINE 'capture': []NEWLINE },NEWLINE NEWLINE # transitionsNEWLINE DecayMode.ISOMERIC_TRANSITION: {NEWLINE 'dAdZ': (0, 0), 'emission': [Photon], 'capture': []NEWLINE },NEWLINE DecayMode.INTERNAL_TRANSITION: {NEWLINE 'dAdZ': (0, 0), 'emission': [Electron], 'capture': []NEWLINE },NEWLINE}NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# NuclearDecay ClassNEWLINE# -----------------------------------------------------------------------------NEWLINEclass NuclearDecay:NEWLINE """ Spontaneous nuclear radioactive decay class. """NEWLINENEWLINE # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NEWLINE # Class MethodsNEWLINE # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NEWLINE NEWLINE @classmethodNEWLINE def emission_notation(klass, emission):NEWLINE sep = ' ' + default_encoder('$math(+)') + ' 'NEWLINE return sep.join([p.symbol for p in emission])NEWLINENEWLINE @classmethodNEWLINE def capture_notation(klass, capture):NEWLINE sep = ' ' + default_encoder('$math(+)') + ' 'NEWLINE return sep.join([p.symbol for p in capture])NEWLINENEWLINE # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NEWLINE # Class Instance MethodsNEWLINE # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NEWLINE NEWLINE def __init__(self, mode=DecayMode.STABLE,NEWLINE halflife=math.inf,NEWLINE emission=[],NEWLINE capture=[],NEWLINE energy=0.0,NEWLINE name=None):NEWLINE """NEWLINE Initializer.NEWLINENEWLINE Parameters:NEWLINE mode Decay mode. See DecayMode enumeration. May also beNEWLINE string or integer enum equivalent.NEWLINE halflife Halflife of embedding nucleus in seconds.NEWLINE emission Decay emssions of subatomic and atomic particles. NEWLINE capture Captured subatomic particles.NEWLINE energy Disintegraion engergy.NEWLINE name Assigned name to decay. If None, then mode's name.NEWLINE """NEWLINE self._mode = enumfactory(DecayMode, mode)NEWLINE self._halflife = halflifeNEWLINE self._emission = emissionNEWLINE self._capture = captureNEWLINE self._energy = energyNEWLINE if name is None:NEWLINE self._name = enum_to_str(self._mode, sep='-')NEWLINE else:NEWLINE self._name = default_encoder(name)NEWLINE self.check_and_set()NEWLINENEWLINE def check_and_set(self):NEWLINE """NEWLINE Check and set decay data.NEWLINENEWLINE Raises ValueError or TypeError exception on error.NEWLINE """NEWLINE info = BakedInfo[self.mode]NEWLINENEWLINE self._dAdZ = info['dAdZ']NEWLINENEWLINE # special decay casesNEWLINE if self.mode in [DecayMode.SPONTANEOUS_FISSION, DecayMode.CLUSTER_DECAY]:NEWLINE if len(self._emission) != 1:NEWLINE raise ValueError(f"{self.mode.name} requires an emitted "\NEWLINE "isotope or nucleus to be specfied")NEWLINE p = self._emission[0]NEWLINE if not isderivedinstance(p, AtomicNucleus):NEWLINE raise TypeError(f"{self.p} is not a nucleus nor an isotope")NEWLINE lspec = len(self._capture)NEWLINE lexpt = len(info['capture'])NEWLINE if lspec != lexpt:NEWLINE raise ValueError(f"{self.mode.name} expected capture of "\NEWLINE f"{lexpt} particle(s), {lspec} specified")NEWLINE self._dAdZ = (-p.A, -p.Z)NEWLINENEWLINE else:NEWLINE # defaultingNEWLINE if len(self._emission) == 0: # create emmision defaults from baked infoNEWLINE self._emission = []NEWLINE for p in info['emission']:NEWLINE self._emission.append(p())NEWLINE if len(self._capture) == 0: # create capture defaults from baked infoNEWLINE self._capture = []NEWLINE for p in info['capture']:NEWLINE self._capture.append(p())NEWLINENEWLINE # cross-check specifed against expectedNEWLINE self.check_particle_list('emission', info['emission'], self._emission)NEWLINE self.check_particle_list('capture', info['capture'], self._capture)NEWLINENEWLINE def check_particle_list(self, what, expected, specified):NEWLINE """NEWLINE Check specified particle list against expect.NEWLINENEWLINE Raises ValueError or TypeError exception on error.NEWLINENEWLINE Parameters:NEWLINE what What is being checked string.NEWLINE expected Expected particles.NEWLINE specified Specified particles.NEWLINE """NEWLINE expt = expected.copy()NEWLINE lexpt = len(expt)NEWLINE lspec = len(specified)NEWLINENEWLINE if lspec != lexpt:NEWLINE raise ValueError( f"{self.mode.name} expected {what} of "\NEWLINE f"{lexpt} particle(s), {lspec} specified" )NEWLINE for p in specified:NEWLINE good = FalseNEWLINE for i in range(len(expt)):NEWLINE if isderivedinstance(p, expt[i]):NEWLINE del expt[i]NEWLINE good = TrueNEWLINE breakNEWLINE if not good:NEWLINE raise TypeError(f"invalid {self.mode.name} {what} particle type {p}")NEWLINENEWLINE def __repr__(self):NEWLINE return f"{self.__module__}.{self.__class__.__name__}"\NEWLINE f"(mode={self._mode.name!r}, halflife={self._halflife}, "\NEWLINE f"name={self._name!r})"NEWLINENEWLINE def __str__(self):NEWLINE return self.nameNEWLINENEWLINE @propertyNEWLINE def mode(self):NEWLINE """ Return decay mode enum. """NEWLINE return self._modeNEWLINENEWLINE @propertyNEWLINE def halflife(self):NEWLINE """ Return decay halflife in seconds. """NEWLINE return self._halflifeNEWLINENEWLINE @propertyNEWLINE def emission(self):NEWLINE """ Return list of decay emission particles. """NEWLINE return self._emissionNEWLINENEWLINE @propertyNEWLINE def capture(self):NEWLINE """ Return list of decay capture particles. """NEWLINE return self._captureNEWLINENEWLINE @propertyNEWLINE def energy(self):NEWLINE """ Return decay TBD energy. """NEWLINE return self._energyNEWLINENEWLINE @propertyNEWLINE def name(self):NEWLINE """ Return assigned name of this decay. """NEWLINE return self._nameNEWLINENEWLINE @propertyNEWLINE def dAdZ(self):NEWLINE """ Return the delta nuclide for decay daughter nucleus. """ NEWLINE return self._dAdZNEWLINENEWLINE # fission: N << nNEWLINE # fusion: F = M * NNEWLINE # chemical: MN2 = M + 2 * NNEWLINE def decay(self, parent):NEWLINE """NEWLINE Decay parent nucleus using this decay properties.NEWLINENEWLINE TODO: RDK this needs serious work. No captured particlesNEWLINE or energies calculated, etc.NEWLINENEWLINE Parameters:NEWLINE parent Parent nucleus (AtomicNucleus (derived) instance).NEWLINENEWLINE Returns:NEWLINE Tuple of any emitted particles plus daughter nucleusNEWLINE (emitted),daughter.NEWLINE """NEWLINE out = []NEWLINE for p in self.emission:NEWLINE out.append(p.copy())NEWLINE daughter = AtomicNucleus(parent.Z+self.dAdZ[1], parent.A+self.dAdZ[0]) NEWLINE return tuple(out),daughterNEWLINENEWLINE def print_properties(self, indent=0, **print_kwargs):NEWLINE """NEWLINE Print nucleus properties.NEWLINENEWLINE Paramters:NEWLINE print_kwargs Python3 print() keyword arguments.NEWLINE """NEWLINE emi = self.emission_notation(self.emission)NEWLINE cap = self.capture_notation(self.capture)NEWLINENEWLINE print2cols([NEWLINE ('Name', self.name),NEWLINE ('Mode', self.mode.name),NEWLINE ('Halflife', fInfNum(self.halflife) + ' seconds'),NEWLINE ('Emission', emi),NEWLINE ('Capture', cap),NEWLINE ('dAdZ', self.dAdZ),NEWLINE ('Energy', self.energy),],NEWLINE indent=indent, **print_kwargs)NEWLINENEWLINE# -----------------------------------------------------------------------------NEWLINE# Unit testsNEWLINE# -----------------------------------------------------------------------------NEWLINEif __name__ == "__main__":NEWLINE import sysNEWLINE import tests.utnucleardecay as utNEWLINENEWLINE sys.exit(ut.utmain())NEWLINE
def test_fixture(postgresql_instance):NEWLINE assert hasattr(postgresql_instance, 'port')NEWLINE
# -*- coding: utf-8 -*-NEWLINE# Copyright 2020-2021 CERNNEWLINE#NEWLINE# Licensed under the Apache License, Version 2.0 (the "License");NEWLINE# you may not use this file except in compliance with the License.NEWLINE# You may obtain a copy of the License atNEWLINE#NEWLINE# http://www.apache.org/licenses/LICENSE-2.0NEWLINE#NEWLINE# Unless required by applicable law or agreed to in writing, softwareNEWLINE# distributed under the License is distributed on an "AS IS" BASIS,NEWLINE# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.NEWLINE# See the License for the specific language governing permissions andNEWLINE# limitations under the License.NEWLINE#NEWLINE# Authors:NEWLINE# - Cedric Serfon <cedric.serfon@cern.ch>, 2020NEWLINE# - Eli Chadwick <eli.chadwick@stfc.ac.uk>, 2020NEWLINE# - Martin Barisits <martin.barisits@cern.ch>, 2020-2021NEWLINE# - Benedikt Ziemons <benedikt.ziemons@cern.ch>, 2020NEWLINENEWLINEfrom __future__ import print_functionNEWLINENEWLINEfrom rucio.api.permission import has_permissionNEWLINEfrom rucio.api.scope import list_scopesNEWLINENEWLINEfrom rucio.core.rse import get_rse_idNEWLINEfrom rucio.core import diracNEWLINEfrom rucio.common.exception import AccessDeniedNEWLINEfrom rucio.common.utils import extract_scopeNEWLINENEWLINENEWLINEdef add_files(lfns, issuer, ignore_availability):NEWLINE """NEWLINE Bulk add files :NEWLINE - Create the file and replica.NEWLINE - If doesn't exist create the dataset containing the file as well as a rule on the dataset on ANY sites.NEWLINE - Create all the ascendants of the dataset if they do not existNEWLINENEWLINE :param lfns: List of lfn (dictionary {'lfn': <lfn>, 'rse': <rse>, 'bytes': <bytes>, 'adler32': <adler32>, 'guid': <guid>, 'pfn': <pfn>}NEWLINE :param issuer: The issuer account.NEWLINE :param ignore_availability: A boolean to ignore blocked sites.NEWLINE """NEWLINE scopes = list_scopes()NEWLINE dids = []NEWLINE rses = {}NEWLINE for lfn in lfns:NEWLINE scope, name = extract_scope(lfn['lfn'], scopes)NEWLINE dids.append({'scope': scope, 'name': name})NEWLINE rse = lfn['rse']NEWLINE if rse not in rses:NEWLINE rse_id = get_rse_id(rse=rse)NEWLINE rses[rse] = rse_idNEWLINE lfn['rse_id'] = rses[rse]NEWLINENEWLINE # Check if the issuer can add dids and use skip_availabitlityNEWLINE for rse in rses:NEWLINE rse_id = rses[rse]NEWLINE kwargs = {'rse': rse, 'rse_id': rse_id}NEWLINE if not has_permission(issuer=issuer, action='add_replicas', kwargs=kwargs):NEWLINE raise AccessDenied('Account %s can not add file replicas on %s' % (issuer, rse))NEWLINE if not has_permission(issuer=issuer, action='skip_availability_check', kwargs=kwargs):NEWLINE ignore_availability = FalseNEWLINENEWLINE # Check if the issuer can add the filesNEWLINE kwargs = {'issuer': issuer, 'dids': dids}NEWLINE if not has_permission(issuer=issuer, action='add_dids', kwargs=kwargs):NEWLINE raise AccessDenied('Account %s can not bulk add data identifier' % (issuer))NEWLINENEWLINE dirac.add_files(lfns=lfns, account=issuer, ignore_availability=ignore_availability, session=None)NEWLINE