content stringlengths 7 1.05M |
|---|
#!/usr/bin/python
# height2.py
print ('Height: %.2f %s' % (172.3, 'cm'))
print ('Height: {0:.2f} {1:s}'.format(172.3, 'cm'))
|
"""
Crie um programa que Simule o funcionamento de um caixa eletrônico. No inicio, pergunte ao usuario qual será o valor a
ser sacado (numero inteiro) e o programa vai verificar quantas cédulas de cada valor serão entregues. Considere
que o caixa possui cédulas de 50, 20, 10 e 1.
"""
print('=' * 40)
print('BANCO FSR'.center(40))
print('=' * 40)
valor = int(input('Que valor você gostaria de Sacar? R$'))
inc50 = inc20 = inc10 = inc1 = 0
while True:
if valor % 50 == 0 and valor > 0:
inc50 += 1
valor -= 50
elif valor % 20 == 0 and valor > 0:
inc20 += 1
valor -= 20
elif valor % 10 == 0 and valor > 0:
inc10 += 1
valor -= 10
elif valor % 1 == 0 and valor > 0:
inc1 += 1
valor -= 1
else:
break
print(f'Total de {inc50} Cédulas de R$50')
print(f'Total de {inc20} Cédulas de R$20')
print(f'Total de {inc10} Cédulas de R$10')
print(f'Total de {inc1} Cédulas de R$1')
print('=' * 40)
print('Volte sempre ao BANCO FSR, tenha um bom dia!!')
|
#
# PySNMP MIB module EFM-CU-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/EFM-CU-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:11:39 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( OctetString, ObjectIdentifier, Integer, ) = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint")
( ifIndex, ifSpeed, ) = mibBuilder.importSymbols("IF-MIB", "ifIndex", "ifSpeed")
( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
( ObjectGroup, NotificationGroup, ModuleCompliance, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
( Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, mib_2, IpAddress, Integer32, NotificationType, Unsigned32, ObjectIdentity, Counter64, TimeTicks, Gauge32, iso, Counter32, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "mib-2", "IpAddress", "Integer32", "NotificationType", "Unsigned32", "ObjectIdentity", "Counter64", "TimeTicks", "Gauge32", "iso", "Counter32")
( TextualConvention, DisplayString, TruthValue, PhysAddress, RowStatus, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue", "PhysAddress", "RowStatus")
efmCuMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 167)).setRevisions(("2007-11-14 00:00",))
if mibBuilder.loadTexts: efmCuMIB.setLastUpdated('200711140000Z')
if mibBuilder.loadTexts: efmCuMIB.setOrganization('IETF Ethernet Interfaces and Hub MIB Working Group')
if mibBuilder.loadTexts: efmCuMIB.setContactInfo('WG charter:\n http://www.ietf.org/html.charters/OLD/hubmib-charter.html\n\n\n\n Mailing Lists:\n General Discussion: hubmib@ietf.org\n To Subscribe: hubmib-request@ietf.org\n In Body: subscribe your_email_address\n\n Chair: Bert Wijnen\n Postal: Alcatel-Lucent\n Schagen 33\n 3461 GL Linschoten\n Netherlands\n Phone: +31-348-407-775\n EMail: bwijnen@alcatel-lucent.com\n\n Editor: Edward Beili\n Postal: Actelis Networks Inc.\n 25 Bazel St., P.O.B. 10173\n Petach-Tikva 10173\n Israel\n Phone: +972-3-924-3491\n Email: edward.beili@actelis.com')
if mibBuilder.loadTexts: efmCuMIB.setDescription("The objects in this MIB module are used to manage\n the Ethernet in the First Mile (EFM) Copper (EFMCu) Interfaces\n 2BASE-TL and 10PASS-TS, defined in IEEE Std. 802.3ah-2004,\n which is now a part of IEEE Std. 802.3-2005.\n\n The following references are used throughout this MIB module:\n\n [802.3ah] refers to:\n IEEE Std 802.3ah-2004: 'IEEE Standard for Information\n technology - Telecommunications and information exchange\n between systems - Local and metropolitan area networks -\n Specific requirements -\n Part 3: Carrier Sense Multiple Access with Collision\n Detection (CSMA/CD) Access Method and Physical Layer\n Specifications -\n Amendment: Media Access Control Parameters, Physical\n Layers and Management Parameters for Subscriber Access\n Networks', 07 September 2004.\n\n Of particular interest are Clause 61, 'Physical Coding\n Sublayer (PCS) and common specifications, type 10PASS-TS and\n type 2BASE-TL', Clause 30, 'Management', Clause 45,\n 'Management Data Input/Output (MDIO) Interface', Annex 62A,\n 'PMD profiles for 10PASS-TS' and Annex 63A, 'PMD profiles for\n 2BASE-TL'.\n\n\n\n\n [G.991.2] refers to:\n ITU-T Recommendation G.991.2: 'Single-pair High-speed Digital\n Subscriber Line (SHDSL) transceivers', December 2003.\n\n [ANFP] refers to:\n NICC Document ND1602:2005/08: 'Specification of the Access\n Network Frequency Plan (ANFP) applicable to transmission\n systems used on the BT Access Network,' August 2005.\n\n The following normative documents are quoted by the DESCRIPTION\n clauses in this MIB module:\n\n [G.993.1] refers to:\n ITU-T Recommendation G.993.1: 'Very High speed Digital\n Subscriber Line transceivers', June 2004.\n\n [T1.424] refers to:\n ANSI T1.424-2004: 'Interface Between Networks and Customer\n Installation Very-high-bit-rate Digital Subscriber Lines\n (VDSL) Metallic Interface (DMT Based)', June 2004.\n\n [TS 101 270-1] refers to:\n ETSI TS 101 270-1: 'Transmission and Multiplexing (TM);\n Access transmission systems on metallic access cables;\n Very high speed Digital Subscriber Line (VDSL); Part 1:\n Functional requirements', October 2005.\n\n Naming Conventions:\n Atn - Attenuation\n CO - Central Office\n CPE - Customer Premises Equipment\n EFM - Ethernet in the First Mile\n EFMCu - EFM Copper\n MDIO - Management Data Input/Output\n Mgn - Margin\n PAF - PME Aggregation Function\n PBO - Power Back-Off\n PCS - Physical Coding Sublayer\n PMD - Physical Medium Dependent\n PME - Physical Medium Entity\n PSD - Power Spectral Density\n SNR - Signal to Noise Ratio\n TCPAM - Trellis Coded Pulse Amplitude Modulation\n\n Copyright (C) The IETF Trust (2007). This version\n of this MIB module is part of RFC 5066; see the RFC\n itself for full legal notices.")
efmCuObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1))
efmCuConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 2))
efmCuPort = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 1))
efmCuPme = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 2))
class EfmProfileIndex(Unsigned32, TextualConvention):
displayHint = 'd'
subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(1,255)
class EfmProfileIndexOrZero(Unsigned32, TextualConvention):
displayHint = 'd'
subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(0,255)
class EfmProfileIndexList(OctetString, TextualConvention):
displayHint = '1d:'
subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,6)
class EfmTruthValueOrUnknown(Integer32, TextualConvention):
subtypeSpec = Integer32.subtypeSpec+ConstraintsUnion(SingleValueConstraint(0, 1, 2,))
namedValues = NamedValues(("unknown", 0), ("true", 1), ("false", 2),)
efmCuPortNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 1, 0))
efmCuLowRateCrossing = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 1, 0, 1)).setObjects(*(("EFM-CU-MIB", "ifSpeed"), ("EFM-CU-MIB", "efmCuThreshLowRate"),))
if mibBuilder.loadTexts: efmCuLowRateCrossing.setDescription("This notification indicates that the EFMCu port's data rate\n has reached/dropped below or exceeded the low rate threshold,\n specified by efmCuThreshLowRate.\n\n This notification MAY be sent for the -O subtype ports\n (2BaseTL-O/10PassTS-O) while the port is Up, on the crossing\n event in both directions: from normal (rate is above the\n threshold) to low (rate equals the threshold or below it) and\n\n\n\n from low to normal. This notification is not applicable to\n the -R subtypes.\n\n It is RECOMMENDED that a small debouncing period of 2.5 sec,\n between the detection of the condition and the notification,\n is implemented to prevent simultaneous LinkUp/LinkDown and\n efmCuLowRateCrossing notifications to be sent.\n\n The adaptive nature of the EFMCu technology allows the port to\n adapt itself to the changes in the copper environment, e.g.,\n an impulse noise, alien crosstalk, or a micro-interruption may\n temporarily drop one or more PMEs in the aggregation group,\n causing a rate degradation of the aggregated EFMCu link.\n The dropped PMEs would then try to re-initialize, possibly at\n a lower rate than before, adjusting the rate to provide\n required target SNR margin.\n\n Generation of this notification is controlled by the\n efmCuLowRateCrossingEnable object.")
efmCuPortConfTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 1, 1), )
if mibBuilder.loadTexts: efmCuPortConfTable.setDescription('Table for Configuration of EFMCu 2BASE-TL/10PASS-TS (PCS)\n Ports. Entries in this table MUST be maintained in a\n persistent manner.')
efmCuPortConfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPortConfEntry.setDescription('An entry in the EFMCu Port Configuration table.\n Each entry represents an EFMCu port indexed by the ifIndex.\n Note that an EFMCu PCS port runs on top of a single\n or multiple PME port(s), which are also indexed by ifIndex.')
efmCuPAFAdminState = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPAFAdminState.setDescription("Administrative (desired) state of the PAF of the EFMCu port\n (PCS).\n When 'disabled', PME aggregation will not be performed by the\n PCS. No more than a single PME can be assigned to this PCS in\n this case.\n When 'enabled', PAF will be performed by the PCS when the link\n is Up, even on a single attached PME, if PAF is supported.\n\n PCS ports incapable of supporting PAF SHALL return a value of\n 'disabled'. Attempts to 'enable' such ports SHALL be\n rejected.\n\n A PAF 'enabled' port with multiple PMEs assigned cannot be\n 'disabled'. Attempts to 'disable' such port SHALL be\n rejected, until at most one PME is left assigned.\n\n Changing PAFAdminState is a traffic-disruptive operation and\n as such SHALL be done when the link is Down. Attempts to\n change this object SHALL be rejected if the link is Up or\n Initializing.\n\n This object maps to the Clause 30 attribute aPAFAdminState.\n\n If a Clause 45 MDIO Interface to the PCS is present, then this\n object maps to the PAF enable bit in the 10P/2B PCS control\n register.\n\n This object MUST be maintained in a persistent manner.")
efmCuPAFDiscoveryCode = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 2), PhysAddress().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0,0),ValueSizeConstraint(6,6),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPAFDiscoveryCode.setDescription('PAF Discovery Code of the EFMCu port (PCS).\n A unique 6-octet code used by the Discovery function,\n when PAF is supported.\n PCS ports incapable of supporting PAF SHALL return a\n zero-length octet string on an attempt to read this object.\n An attempt to write to this object SHALL be rejected for such\n ports.\n This object MUST be instantiated for the -O subtype PCS before\n writing operations on the efmCuPAFRemoteDiscoveryCode\n (Set_if_Clear and Clear_if_Same) are performed by PMEs\n associated with the PCS.\n The initial value of this object for -R subtype ports after\n reset is all zeroes. For -R subtype ports, the value of this\n object cannot be changed directly. This value may be changed\n as a result of writing operation on the\n efmCuPAFRemoteDiscoveryCode object of remote PME of -O\n subtype, connected to one of the local PMEs associated with\n the PCS.\n\n Discovery MUST be performed when the link is Down.\n Attempts to change this object MUST be rejected (in case of\n SNMP with the error inconsistentValue), if the link is Up or\n Initializing.\n\n The PAF Discovery Code maps to the local Discovery code\n variable in PAF (note that it does not have a corresponding\n Clause 45 register).')
efmCuAdminProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 3), EfmProfileIndexList().clone(hexValue="01")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuAdminProfile.setDescription('Desired configuration profile(s), common for all PMEs in the\n EFMCu port. This object is a list of pointers to entries in\n either efmCuPme2BProfileTable or\n efmCuPme10PProfileTable, depending on the current\n operating SubType of the EFMCu port as indicated by\n efmCuPortSide.\n\n\n\n The value of this object is a list of up to 6 indices of\n profiles. If this list consists of a single profile index,\n then all PMEs assigned to this EFMCu port SHALL be configured\n according to the profile referenced by that index, unless it\n is overwritten by a corresponding non-zero\n efmCuPmeAdminProfile instance, which takes precedence over\n efmCuAdminProfile.\n A list consisting of more than one index allows each PME\n in the port to be configured according to any profile\n specified in the list.\n By default, this object has a value of 0x01, referencing the\n 1st entry in efmCuPme2BProfileTable or\n efmCuPme10PProfileTable.\n\n This object is writable and readable for the -O subtype\n (2BaseTL-O or 10PassTS-O) EFMCu ports. It is irrelevant for\n the -R subtype (2BaseTL-R or 10PassTS-R) ports -- a\n zero-length octet string SHALL be returned on an attempt to\n read this object and an attempt to change this object MUST be\n rejected in this case.\n\n Note that the current operational profile value is available\n via the efmCuPmeOperProfile object.\n\n Any modification of this object MUST be performed when the\n link is Down. Attempts to change this object MUST be\n rejected, if the link is Up or Initializing.\n Attempts to set this object to a list with a member value that\n is not the value of the index for an active entry in the\n corresponding profile table MUST be rejected.\n\n This object maps to the Clause 30 attribute aProfileSelect.\n\n This object MUST be maintained in a persistent manner.')
efmCuTargetDataRate = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 4), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(1,100000),ValueRangeConstraint(999999,999999),))).setUnits('Kbps').setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuTargetDataRate.setDescription("Desired EFMCu port 'net' (as seen across MII) Data Rate in\n Kbps, to be achieved during initialization, under spectral\n restrictions placed on each PME via efmCuAdminProfile or\n\n\n\n efmCuPmeAdminProfile, with the desired SNR margin specified by\n efmCuTargetSnrMgn.\n In case of PAF, this object represents a sum of individual PME\n data rates, modified to compensate for fragmentation and\n 64/65-octet encapsulation overhead (e.g., target data rate of\n 10 Mbps SHALL allow lossless transmission of a full-duplex\n 10 Mbps Ethernet frame stream with minimal inter-frame gap).\n\n The value is limited above by 100 Mbps as this is the max\n burst rate across MII for EFMCu ports.\n\n The value between 1 and 100000 indicates that the total data\n rate (ifSpeed) of the EFMCu port after initialization SHALL be\n equal to the target data rate or less, if the target data rate\n cannot be achieved under spectral restrictions specified by\n efmCuAdminProfile/efmCuPmeAdminProfile and with the desired\n SNR margin. In case the copper environment allows a higher\n total data rate to be achieved than that specified by the\n target, the excess capability SHALL be either converted to\n additional SNR margin or reclaimed by minimizing transmit\n power as controlled by efmCuAdaptiveSpectra.\n\n The value of 999999 means that the target data rate is not\n fixed and SHALL be set to the maximum attainable rate during\n initialization (Best Effort), under specified spectral\n restrictions and with the desired SNR margin.\n\n This object is read-write for the -O subtype EFMCu ports\n (2BaseTL-O/10PassTS-O) and not available for the -R subtypes.\n\n Changing of the Target Data Rate MUST be performed when the\n link is Down. Attempts to change this object MUST be rejected\n (in case of SNMP with the error inconsistentValue), if the\n link is Up or Initializing.\n\n Note that the current Data Rate of the EFMCu port is\n represented by the ifSpeed object of IF-MIB.\n\n This object MUST be maintained in a persistent manner.")
efmCuTargetSnrMgn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,21))).setUnits('dB').setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuTargetSnrMgn.setDescription('Desired EFMCu port SNR margin to be achieved on all PMEs\n\n\n\n assigned to the port, during initialization. (The SNR margin\n is the difference between the desired SNR and the actual SNR).\n\n Note that 802.3ah recommends using a default target SNR margin\n of 5 dB for 2BASE-TL ports and 6 dB for 10PASS-TS ports in\n order to achieve a mean Bit Error Rate (BER) of 10^-7 at the\n PMA service interface.\n\n This object is read-write for the -O subtype EFMCu ports\n (2BaseTL-O/10PassTS-O) and not available for the -R subtypes.\n\n Changing of the target SNR margin MUST be performed when the\n link is Down. Attempts to change this object MUST be rejected\n (in case of SNMP with the error inconsistentValue), if the\n link is Up or Initializing.\n\n Note that the current SNR margin of the PMEs comprising the\n EFMCu port is represented by efmCuPmeSnrMgn.\n\n This object MUST be maintained in a persistent manner.')
efmCuAdaptiveSpectra = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 6), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuAdaptiveSpectra.setDescription('Indicates how to utilize excess capacity when the copper\n environment allows a higher total data rate to be achieved\n than that specified by the efmCuTargetDataRate.\n\n A value of true(1) indicates that the excess capability SHALL\n be reclaimed by minimizing transmit power, e.g., using higher\n constellations and Power Back-Off, in order to reduce\n interference to other copper pairs in the binder and the\n adverse impact to link/system performance.\n\n A value of false(2) indicates that the excess capability SHALL\n be converted to additional SNR margin and spread evenly across\n all active PMEs assigned to the (PCS) port, to increase link\n robustness.\n\n This object is read-write for the -O subtype EFMCu ports\n (2BaseTL-O/10PassTS-O) and not available for the -R subtypes.\n\n Changing of this object MUST be performed when the link is\n\n\n\n Down. Attempts to change this object MUST be rejected (in\n case of SNMP with the error inconsistentValue), if the link\n is Up or Initializing.\n\n This object MUST be maintained in a persistent manner.')
efmCuThreshLowRate = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 7), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1,100000))).setUnits('Kbps').setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuThreshLowRate.setDescription('This object configures the EFMCu port low-rate crossing alarm\n threshold. When the current value of ifSpeed for this port\n reaches/drops below or exceeds this threshold, an\n efmCuLowRateCrossing notification MAY be generated if enabled\n by efmCuLowRateCrossingEnable.\n\n This object is read-write for the -O subtype EFMCu ports\n (2BaseTL-O/10PassTS-O) and not available for the -R subtypes.\n\n This object MUST be maintained in a persistent manner.')
efmCuLowRateCrossingEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 1, 1, 8), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuLowRateCrossingEnable.setDescription('Indicates whether efmCuLowRateCrossing notifications should\n be generated for this interface.\n\n A value of true(1) indicates that efmCuLowRateCrossing\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.\n\n This object is read-write for the -O subtype EFMCu ports\n (2BaseTL-O/10PassTS-O) and not available for the -R subtypes.\n\n This object MUST be maintained in a persistent manner.')
efmCuPortCapabilityTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 1, 2), )
if mibBuilder.loadTexts: efmCuPortCapabilityTable.setDescription('Table for Capabilities of EFMCu 2BASE-TL/10PASS-TS (PCS)\n Ports. Entries in this table MUST be maintained in a\n persistent manner')
efmCuPortCapabilityEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPortCapabilityEntry.setDescription('An entry in the EFMCu Port Capability table.\n Each entry represents an EFMCu port indexed by the ifIndex.\n Note that an EFMCu PCS port runs on top of a single\n or multiple PME port(s), which are also indexed by ifIndex.')
efmCuPAFSupported = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 2, 1, 1), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFSupported.setDescription('PME Aggregation Function (PAF) capability of the EFMCu port\n (PCS).\n This object has a value of true(1) when the PCS can perform\n PME aggregation on the available PMEs.\n Ports incapable of PAF SHALL return a value of false(2).\n\n This object maps to the Clause 30 attribute aPAFSupported.\n\n If a Clause 45 MDIO Interface to the PCS is present,\n then this object maps to the PAF available bit in the\n 10P/2B capability register.')
efmCuPeerPAFSupported = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 2, 1, 2), EfmTruthValueOrUnknown()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPeerPAFSupported.setDescription('PME Aggregation Function (PAF) capability of the EFMCu port\n (PCS) link partner.\n This object has a value of true(1) when the remote PCS can\n perform PME aggregation on its available PMEs.\n Ports whose peers are incapable of PAF SHALL return a value\n of false(2).\n Ports whose peers cannot be reached because of the link\n state SHALL return a value of unknown(0).\n\n This object maps to the Clause 30 attribute\n aRemotePAFSupported.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the Remote PAF supported bit in the\n 10P/2B capability register.')
efmCuPAFCapacity = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 2, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1,32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFCapacity.setDescription('Number of PMEs that can be aggregated by the local PAF.\n The number of PMEs currently assigned to a particular\n EFMCu port (efmCuNumPMEs) is never greater than\n efmCuPAFCapacity.\n\n This object maps to the Clause 30 attribute\n aLocalPAFCapacity.')
efmCuPeerPAFCapacity = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 2, 1, 4), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,0),ValueRangeConstraint(1,32),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPeerPAFCapacity.setDescription('Number of PMEs that can be aggregated by the PAF of the peer\n PHY (PCS port).\n A value of 0 is returned when peer PAF capacity is unknown\n (peer cannot be reached).\n\n\n\n\n This object maps to the Clause 30 attribute\n aRemotePAFCapacity.')
efmCuPortStatusTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 1, 3), )
if mibBuilder.loadTexts: efmCuPortStatusTable.setDescription('This table provides overall status information of EFMCu\n 2BASE-TL/10PASS-TS ports, complementing the generic status\n information from the ifTable of IF-MIB and ifMauTable of\n MAU-MIB. Additional status information about connected PMEs\n is available from the efmCuPmeStatusTable.\n\n This table contains live data from the equipment. As such,\n it is NOT persistent.')
efmCuPortStatusEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPortStatusEntry.setDescription('An entry in the EFMCu Port Status table.\n Each entry represents an EFMCu port indexed by the ifIndex.\n Note that an EFMCu PCS port runs on top of a single\n or multiple PME port(s), which are also indexed by ifIndex.')
efmCuFltStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 1), Bits().clone(namedValues=NamedValues(("noPeer", 0), ("peerPowerLoss", 1), ("pmeSubTypeMismatch", 2), ("lowRate", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuFltStatus.setDescription("EFMCu (PCS) port Fault Status. This is a bitmap of possible\n conditions. The various bit positions are:\n noPeer - the peer PHY cannot be reached (e.g.,\n no PMEs attached, all PMEs are Down,\n etc.). More info is available in\n efmCuPmeFltStatus.\n peerPowerLoss - the peer PHY has indicated impending\n unit failure due to loss of local\n power ('Dying Gasp').\n pmeSubTypeMismatch - local PMEs in the aggregation group\n are not of the same subtype, e.g.,\n some PMEs in the local device are -O\n while others are -R subtype.\n lowRate - ifSpeed of the port reached or dropped\n below efmCuThreshLowRate.\n\n This object is intended to supplement the ifOperStatus object\n in IF-MIB and ifMauMediaAvailable in MAU-MIB.\n\n Additional information is available via the efmCuPmeFltStatus\n object for each PME in the aggregation group (single PME if\n PAF is disabled).")
efmCuPortSide = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("subscriber", 1), ("office", 2), ("unknown", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPortSide.setDescription("EFM port mode of operation (subtype).\n The value of 'subscriber' indicates that the port is\n\n\n\n designated as '-R' subtype (all PMEs assigned to this port are\n of subtype '-R').\n The value of the 'office' indicates that the port is\n designated as '-O' subtype (all PMEs assigned to this port are\n of subtype '-O').\n The value of 'unknown' indicates that the port has no assigned\n PMEs yet or that the assigned PMEs are not of the same side\n (subTypePMEMismatch).\n\n This object partially maps to the Clause 30 attribute\n aPhyEnd.")
efmCuNumPMEs = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuNumPMEs.setDescription('The number of PMEs that is currently aggregated by the local\n PAF (assigned to the EFMCu port using the ifStackTable).\n This number is never greater than efmCuPAFCapacity.\n\n This object SHALL be automatically incremented or decremented\n when a PME is added or deleted to/from the EFMCu port using\n the ifStackTable.')
efmCuPAFInErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInErrors.setDescription('The number of fragments that have been received across the\n gamma interface with RxErr asserted and discarded.\n This read-only counter is inactive (not incremented) when the\n PAF is unsupported or disabled. Upon disabling the PAF, the\n counter retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF RX error register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n\n\n\n defined in IF-MIB.')
efmCuPAFInSmallFragments = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInSmallFragments.setDescription('The number of fragments smaller than minFragmentSize\n (64 bytes) that have been received across the gamma interface\n and discarded.\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF small fragments register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInLargeFragments = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInLargeFragments.setDescription('The number of fragments larger than maxFragmentSize\n (512 bytes) that have been received across the gamma interface\n and discarded.\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF large fragments register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInBadFragments = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInBadFragments.setDescription('The number of fragments that do not fit into the sequence\n expected by the frame assembly function and that have been\n received across the gamma interface and discarded (the\n frame buffer is flushed to the next valid frame start).\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF bad fragments register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInLostFragments = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInLostFragments.setDescription('The number of gaps in the sequence of fragments that have\n been received across the gamma interface (the frame buffer is\n flushed to the next valid frame start, when fragment/fragments\n expected by the frame assembly function is/are not received).\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF lost fragment register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInLostStarts = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInLostStarts.setDescription('The number of missing StartOfPacket indicators expected by\n the frame assembly function.\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF lost start of fragment\n register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInLostEnds = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInLostEnds.setDescription('The number of missing EndOfPacket indicators expected by the\n frame assembly function.\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF lost start of fragment\n register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPAFInOverflows = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 1, 3, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPAFInOverflows.setDescription('The number of fragments, received across the gamma interface\n and discarded, which would have caused the frame assembly\n buffer to overflow.\n This read-only counter is inactive when the PAF is\n unsupported or disabled. Upon disabling the PAF, the counter\n retains its previous value.\n\n If a Clause 45 MDIO Interface to the PCS is present, then\n this object maps to the 10P/2B PAF overflow register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPmeNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 2, 0))
efmCuPmeLineAtnCrossing = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 2, 0, 1)).setObjects(*(("EFM-CU-MIB", "efmCuPmeLineAtn"), ("EFM-CU-MIB", "efmCuPmeThreshLineAtn"),))
if mibBuilder.loadTexts: efmCuPmeLineAtnCrossing.setDescription('This notification indicates that the loop attenuation\n threshold (as per the efmCuPmeThreshLineAtn\n value) has been reached/exceeded for the 2BASE-TL/10PASS-TS\n PME. This notification MAY be sent on the crossing event in\n both directions: from normal to exceeded and from exceeded\n to normal.\n\n It is RECOMMENDED that a small debouncing period of 2.5 sec,\n between the detection of the condition and the notification,\n is implemented to prevent intermittent notifications from\n being sent.\n\n Generation of this notification is controlled by the\n efmCuPmeLineAtnCrossingEnable object.')
efmCuPmeSnrMgnCrossing = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 2, 0, 2)).setObjects(*(("EFM-CU-MIB", "efmCuPmeSnrMgn"), ("EFM-CU-MIB", "efmCuPmeThreshSnrMgn"),))
if mibBuilder.loadTexts: efmCuPmeSnrMgnCrossing.setDescription('This notification indicates that the SNR margin threshold\n (as per the efmCuPmeThreshSnrMgn value) has been\n reached/exceeded for the 2BASE-TL/10PASS-TS PME.\n This notification MAY be sent on the crossing event in\n both directions: from normal to exceeded and from exceeded\n to normal.\n\n It is RECOMMENDED that a small debouncing period of 2.5 sec,\n between the detection of the condition and the notification,\n is implemented to prevent intermittent notifications from\n being sent.\n\n Generation of this notification is controlled by the\n efmCuPmeSnrMgnCrossingEnable object.')
efmCuPmeDeviceFault = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 2, 0, 3)).setObjects(*(("EFM-CU-MIB", "efmCuPmeFltStatus"),))
if mibBuilder.loadTexts: efmCuPmeDeviceFault.setDescription('This notification indicates that a fault in the PME has been\n detected by a vendor-specific diagnostic or a self-test.\n\n Generation of this notification is controlled by the\n efmCuPmeDeviceFaultEnable object.')
efmCuPmeConfigInitFailure = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 2, 0, 4)).setObjects(*(("EFM-CU-MIB", "efmCuPmeFltStatus"), ("EFM-CU-MIB", "efmCuAdminProfile"), ("EFM-CU-MIB", "efmCuPmeAdminProfile"),))
if mibBuilder.loadTexts: efmCuPmeConfigInitFailure.setDescription('This notification indicates that PME initialization has\n failed, due to inability of the PME link to achieve the\n\n\n\n requested configuration profile.\n\n Generation of this notification is controlled by the\n efmCuPmeConfigInitFailEnable object.')
efmCuPmeProtocolInitFailure = NotificationType((1, 3, 6, 1, 2, 1, 167, 1, 2, 0, 5)).setObjects(*(("EFM-CU-MIB", "efmCuPmeFltStatus"), ("EFM-CU-MIB", "efmCuPmeOperSubType"),))
if mibBuilder.loadTexts: efmCuPmeProtocolInitFailure.setDescription('This notification indicates that the peer PME was using\n an incompatible protocol during initialization.\n\n Generation of this notification is controlled by the\n efmCuPmeProtocolInitFailEnable object.')
efmCuPmeConfTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 1), )
if mibBuilder.loadTexts: efmCuPmeConfTable.setDescription('Table for Configuration of common aspects for EFMCu\n 2BASE-TL/10PASS-TS PME ports (modems). Configuration of\n aspects specific to 2BASE-TL or 10PASS-TS PME types is\n represented in efmCuPme2BConfTable and efmCuPme10PConfTable,\n respectively.\n\n Entries in this table MUST be maintained in a persistent\n manner.')
efmCuPmeConfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPmeConfEntry.setDescription('An entry in the EFMCu PME Configuration table.\n Each entry represents common aspects of an EFMCu PME port\n indexed by the ifIndex. Note that an EFMCu PME port can be\n stacked below a single PCS port, also indexed by ifIndex,\n possibly together with other PME ports if PAF is enabled.')
efmCuPmeAdminSubType = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7,))).clone(namedValues=NamedValues(("ieee2BaseTLO", 1), ("ieee2BaseTLR", 2), ("ieee10PassTSO", 3), ("ieee10PassTSR", 4), ("ieee2BaseTLor10PassTSR", 5), ("ieee2BaseTLor10PassTSO", 6), ("ieee10PassTSor2BaseTLO", 7),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeAdminSubType.setDescription('Administrative (desired) subtype of the PME.\n Possible values are:\n ieee2BaseTLO - PME SHALL operate as 2BaseTL-O\n ieee2BaseTLR - PME SHALL operate as 2BaseTL-R\n ieee10PassTSO - PME SHALL operate as 10PassTS-O\n ieee10PassTSR - PME SHALL operate as 10PassTS-R\n ieee2BaseTLor10PassTSR - PME SHALL operate as 2BaseTL-R or\n 10PassTS-R. The actual value will\n be set by the -O link partner\n during initialization (handshake).\n ieee2BaseTLor10PassTSO - PME SHALL operate as 2BaseTL-O\n (preferred) or 10PassTS-O. The\n actual value will be set during\n initialization depending on the -R\n link partner capability (i.e., if\n -R is incapable of the preferred\n 2BaseTL mode, 10PassTS will be\n used).\n ieee10PassTSor2BaseTLO - PME SHALL operate as 10PassTS-O\n\n\n\n (preferred) or 2BaseTL-O. The\n actual value will be set during\n initialization depending on the -R\n link partner capability (i.e., if\n -R is incapable of the preferred\n 10PassTS mode, 2BaseTL will be\n used).\n\n Changing efmCuPmeAdminSubType is a traffic-disruptive\n operation and as such SHALL be done when the link is Down.\n Attempts to change this object SHALL be rejected if the link\n is Up or Initializing.\n Attempts to change this object to an unsupported subtype\n (see efmCuPmeSubTypesSupported) SHALL be rejected.\n\n The current operational subtype is indicated by the\n efmCuPmeOperSubType variable.\n\n If a Clause 45 MDIO Interface to the PMA/PMD is present, then\n this object combines values of the Port subtype select bits\n and the PMA/PMD type selection bits in the 10P/2B PMA/PMD\n control register.')
efmCuPmeAdminProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 2), EfmProfileIndexOrZero()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeAdminProfile.setDescription('Desired PME configuration profile. This object is a pointer\n to an entry in either the efmCuPme2BProfileTable or the\n efmCuPme10PProfileTable, depending on the current operating\n SubType of the PME. The value of this object is the index of\n the referenced profile.\n The value of zero (default) indicates that the PME is\n configured via the efmCuAdminProfile object for the PCS port\n to which this PME is assigned. That is, the profile\n referenced by efmCuPmeAdminProfile takes precedence\n over the profile(s) referenced by efmCuAdminProfile.\n\n This object is writable and readable for the CO subtype PMEs\n (2BaseTL-O or 10PassTS-O). It is irrelevant for the CPE\n subtype (2BaseTL-R or 10PassTS-R) -- a zero value SHALL be\n returned on an attempt to read this object and any attempt\n to change this object MUST be rejected in this case.\n\n\n\n\n Note that the current operational profile value is available\n via efmCuPmeOperProfile object.\n\n Any modification of this object MUST be performed when the\n link is Down. Attempts to change this object MUST be\n rejected, if the link is Up or Initializing.\n\n Attempts to set this object to a value that is not the value\n of the index for an active entry in the corresponding profile\n table MUST be rejected.\n\n This object maps to the Clause 30 attribute aProfileSelect.\n\n This object MUST be maintained in a persistent manner.')
efmCuPAFRemoteDiscoveryCode = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 3), PhysAddress().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0,0),ValueSizeConstraint(6,6),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPAFRemoteDiscoveryCode.setDescription('PAF Remote Discovery Code of the PME port at the CO.\n The 6-octet Discovery Code of the peer PCS connected via\n the PME.\n Reading this object results in a Discovery Get operation.\n Setting this object to all zeroes results in a Discovery\n Clear_if_Same operation (the value of efmCuPAFDiscoveryCode\n at the peer PCS SHALL be the same as efmCuPAFDiscoveryCode of\n the local PCS associated with the PME for the operation to\n succeed).\n Writing a non-zero value to this object results in a\n Discovery Set_if_Clear operation.\n A zero-length octet string SHALL be returned on an attempt to\n read this object when PAF aggregation is not enabled.\n\n This object is irrelevant in CPE port (-R) subtypes: in this\n case, a zero-length octet string SHALL be returned on an\n attempt to read this object; writing to this object SHALL\n be rejected.\n\n Discovery MUST be performed when the link is Down.\n Attempts to change this object MUST be rejected (in case of\n SNMP with the error inconsistentValue), if the link is Up or\n Initializing.\n\n\n\n\n If a Clause 45 MDIO Interface to the PMA/PMD is present, then\n this object is a function of 10P/2B aggregation discovery\n control register, Discovery operation result bits in 10P/2B\n aggregation and discovery status register and\n 10P/2B aggregation discovery code register.')
efmCuPmeThreshLineAtn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-127,128))).setUnits('dB').setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeThreshLineAtn.setDescription('Desired Line Attenuation threshold for the 2B/10P PME.\n This object configures the line attenuation alarm threshold.\n When the current value of Line Attenuation reaches or\n exceeds this threshold, an efmCuPmeLineAtnCrossing\n notification MAY be generated, if enabled by\n efmCuPmeLineAtnCrossingEnable.\n\n This object is writable for the CO subtype PMEs (-O).\n It is read-only for the CPE subtype (-R).\n\n Changing of the Line Attenuation threshold MUST be performed\n when the link is Down. Attempts to change this object MUST be\n rejected (in case of SNMP with the error inconsistentValue),\n if the link is Up or Initializing.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the loop attenuation threshold bits in\n the 2B PMD line quality thresholds register.')
efmCuPmeThreshSnrMgn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-127,128))).setUnits('dB').setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeThreshSnrMgn.setDescription('Desired SNR margin threshold for the 2B/10P PME.\n This object configures the SNR margin alarm threshold.\n When the current value of SNR margin reaches or exceeds this\n threshold, an efmCuPmeSnrMgnCrossing notification MAY be\n generated, if enabled by efmCuPmeSnrMgnCrossingEnable.\n\n\n\n This object is writable for the CO subtype PMEs\n (2BaseTL-O/10PassTS-O). It is read-only for the CPE subtype\n (2BaseTL-R/10PassTS-R).\n\n Changing of the SNR margin threshold MUST be performed when\n the link is Down. Attempts to change this object MUST be\n rejected (in case of SNMP with the error inconsistentValue),\n if the link is Up or Initializing.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the SNR margin threshold bits in the 2B PMD\n line quality thresholds register.')
efmCuPmeLineAtnCrossingEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 6), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeLineAtnCrossingEnable.setDescription('Indicates whether efmCuPmeLineAtnCrossing notifications\n should be generated for this interface.\n\n A value of true(1) indicates that efmCuPmeLineAtnCrossing\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.')
efmCuPmeSnrMgnCrossingEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 7), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeSnrMgnCrossingEnable.setDescription('Indicates whether efmCuPmeSnrMgnCrossing notifications\n should be generated for this interface.\n\n A value of true(1) indicates that efmCuPmeSnrMgnCrossing\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.')
efmCuPmeDeviceFaultEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 8), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeDeviceFaultEnable.setDescription('Indicates whether efmCuPmeDeviceFault notifications\n\n\n\n should be generated for this interface.\n\n A value of true(1) indicates that efmCuPmeDeviceFault\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.')
efmCuPmeConfigInitFailEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 9), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeConfigInitFailEnable.setDescription('Indicates whether efmCuPmeConfigInitFailure notifications\n should be generated for this interface.\n\n A value of true(1) indicates that efmCuPmeConfigInitFailure\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.')
efmCuPmeProtocolInitFailEnable = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 1, 1, 10), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: efmCuPmeProtocolInitFailEnable.setDescription('Indicates whether efmCuPmeProtocolInitFailure notifications\n should be generated for this interface.\n\n A value of true(1) indicates that efmCuPmeProtocolInitFailure\n notification is enabled. A value of false(2) indicates that\n the notification is disabled.')
efmCuPmeCapabilityTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 2), )
if mibBuilder.loadTexts: efmCuPmeCapabilityTable.setDescription('Table for the configuration of common aspects for EFMCu\n 2BASE-TL/10PASS-TS PME ports (modems). The configuration of\n aspects specific to 2BASE-TL or 10PASS-TS PME types is\n represented in the efmCuPme2BConfTable and the\n efmCuPme10PConfTable, respectively.\n\n Entries in this table MUST be maintained in a persistent\n manner.')
efmCuPmeCapabilityEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPmeCapabilityEntry.setDescription('An entry in the EFMCu PME Capability table.\n Each entry represents common aspects of an EFMCu PME port\n indexed by the ifIndex. Note that an EFMCu PME port can be\n stacked below a single PCS port, also indexed by ifIndex,\n possibly together with other PME ports if PAF is enabled.')
efmCuPmeSubTypesSupported = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 2, 1, 1), Bits().clone(namedValues=NamedValues(("ieee2BaseTLO", 0), ("ieee2BaseTLR", 1), ("ieee10PassTSO", 2), ("ieee10PassTSR", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeSubTypesSupported.setDescription('PME supported subtypes. This is a bitmap of possible\n subtypes. The various bit positions are:\n ieee2BaseTLO - PME is capable of operating as 2BaseTL-O\n ieee2BaseTLR - PME is capable of operating as 2BaseTL-R\n ieee10PassTSO - PME is capable of operating as 10PassTS-O\n ieee10PassTSR - PME is capable of operating as 10PassTS-R\n\n The desired mode of operation is determined by\n efmCuPmeAdminSubType, while efmCuPmeOperSubType reflects the\n current operating mode.\n\n If a Clause 45 MDIO Interface to the PCS is present, then this\n object combines the 10PASS-TS capable and 2BASE-TL capable\n bits in the 10P/2B PMA/PMD speed ability register and the\n CO supported and CPE supported bits in the 10P/2B PMA/PMD\n status register.')
efmCuPmeStatusTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 3), )
if mibBuilder.loadTexts: efmCuPmeStatusTable.setDescription('This table provides common status information of EFMCu\n 2BASE-TL/10PASS-TS PME ports. Status information specific\n to 10PASS-TS PME is represented in efmCuPme10PStatusTable.\n\n This table contains live data from the equipment. As such,\n it is NOT persistent.')
efmCuPmeStatusEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPmeStatusEntry.setDescription('An entry in the EFMCu PME Status table.\n Each entry represents common aspects of an EFMCu PME port\n indexed by the ifIndex. Note that an EFMCu PME port can be\n stacked below a single PCS port, also indexed by ifIndex,\n possibly together with other PME ports if PAF is enabled.')
efmCuPmeOperStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("up", 1), ("downNotReady", 2), ("downReady", 3), ("init", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeOperStatus.setDescription("Current PME link Operational Status. Possible values are:\n up(1) - The link is Up and ready to pass\n 64/65-octet encoded frames or fragments.\n downNotReady(2) - The link is Down and the PME does not\n detect Handshake tones from its peer.\n This value may indicate a possible\n problem with the peer PME.\n downReady(3) - The link is Down and the PME detects\n Handshake tones from its peer.\n init(4) - The link is Initializing, as a result of\n ifAdminStatus being set to 'up' for a\n particular PME or a PCS to which the PME\n is connected.\n\n This object is intended to supplement the Down(2) state of\n ifOperStatus.\n\n This object partially maps to the Clause 30 attribute\n aPMEStatus.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object partially maps to PMA/PMD link status bits in 10P/2B\n PMA/PMD status register.")
efmCuPmeFltStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 2), Bits().clone(namedValues=NamedValues(("lossOfFraming", 0), ("snrMgnDefect", 1), ("lineAtnDefect", 2), ("deviceFault", 3), ("configInitFailure", 4), ("protocolInitFailure", 5),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeFltStatus.setDescription('Current/Last PME link Fault Status. This is a bitmap of\n possible conditions. The various bit positions are:\n\n lossOfFraming - Loss of Framing for 10P or\n Loss of Sync word for 2B PMD or\n Loss of 64/65-octet framing.\n\n\n\n snrMgnDefect - SNR margin dropped below the\n threshold.\n lineAtnDefect - Line Attenuation exceeds the\n threshold.\n deviceFault - Indicates a vendor-dependent\n diagnostic or self-test fault\n has been detected.\n configInitFailure - Configuration initialization failure,\n due to inability of the PME link to\n support the configuration profile,\n requested during initialization.\n protocolInitFailure - Protocol initialization failure, due\n to an incompatible protocol used by\n the peer PME during init (that could\n happen if a peer PMD is a regular\n G.SDHSL/VDSL modem instead of a\n 2BASE-TL/10PASS-TS PME).\n\n This object is intended to supplement ifOperStatus in IF-MIB.\n\n This object holds information about the last fault.\n efmCuPmeFltStatus is cleared by the device restart.\n In addition, lossOfFraming, configInitFailure, and\n protocolInitFailure are cleared by PME init;\n deviceFault is cleared by successful diagnostics/test;\n snrMgnDefect and lineAtnDefect are cleared by SNR margin\n and Line attenuation, respectively, returning to norm and by\n PME init.\n\n This object partially maps to the Clause 30 attribute\n aPMEStatus.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object consolidates information from various PMA/PMD\n registers, namely: Fault bit in PMA/PMD status 1 register,\n 10P/2B PMA/PMD link loss register,\n 10P outgoing indicator bits status register,\n 10P incoming indicator bits status register,\n 2B state defects register.')
efmCuPmeOperSubType = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("ieee2BaseTLO", 1), ("ieee2BaseTLR", 2), ("ieee10PassTSO", 3), ("ieee10PassTSR", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeOperSubType.setDescription('Current operational subtype of the PME.\n Possible values are:\n ieee2BaseTLO - PME operates as 2BaseTL-O\n ieee2BaseTLR - PME operates as 2BaseTL-R\n ieee10PassTSO - PME operates as 10PassTS-O\n ieee10PassTSR - PME operates as 10PassTS-R\n\n The desired operational subtype of the PME can be configured\n via the efmCuPmeAdminSubType variable.\n\n If a Clause 45 MDIO Interface to the PMA/PMD is present, then\n this object combines values of the Port subtype select\n bits, the PMA/PMD type selection bits in the 10P/2B\n PMA/PMD control register, and the PMA/PMD link status bits in\n the 10P/2B PMA/PMD status register.')
efmCuPmeOperProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 4), EfmProfileIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeOperProfile.setDescription('PME current operating profile. This object is a pointer to\n an entry in either the efmCuPme2BProfileTable or the\n efmCuPme10PProfileTable, depending on the current operating\n SubType of the PME as indicated by efmCuPmeOperSubType.\n Note that a profile entry to which efmCuPmeOperProfile is\n pointing can be created automatically to reflect achieved\n parameters in adaptive (not fixed) initialization,\n i.e., values of efmCuPmeOperProfile and efmCuAdminProfile or\n efmCuPmeAdminProfile may differ.\n The value of zero indicates that the PME is Down or\n Initializing.\n\n This object partially maps to the aOperatingProfile attribute\n in Clause 30.')
efmCuPmeSnrMgn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-127,128),ValueRangeConstraint(65535,65535),))).setUnits('dB').setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeSnrMgn.setDescription('The current Signal to Noise Ratio (SNR) margin with respect\n to the received signal as perceived by the local PME.\n The value of 65535 is returned when the PME is Down or\n Initializing.\n\n This object maps to the aPMESNRMgn attribute in Clause 30.\n\n If a Clause 45 MDIO Interface is present, then this\n object maps to the 10P/2B RX SNR margin register.')
efmCuPmePeerSnrMgn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-127,128),ValueRangeConstraint(65535,65535),))).setUnits('dB').setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmePeerSnrMgn.setDescription('The current SNR margin in dB with respect to the received\n signal, as perceived by the remote (link partner) PME.\n The value of 65535 is returned when the PME is Down or\n Initializing.\n\n This object is irrelevant for the -R PME subtypes. The value\n of 65535 SHALL be returned in this case.\n\n If a Clause 45 MDIO Interface is present, then this\n object maps to the 10P/2B link partner RX SNR margin\n register.')
efmCuPmeLineAtn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-127,128),ValueRangeConstraint(65535,65535),))).setUnits('dB').setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeLineAtn.setDescription('The current Line Attenuation in dB as perceived by the local\n PME.\n\n\n\n The value of 65535 is returned when the PME is Down or\n Initializing.\n\n If a Clause 45 MDIO Interface is present, then this\n object maps to the Line Attenuation register.')
efmCuPmePeerLineAtn = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-127,128),ValueRangeConstraint(65535,65535),))).setUnits('dB').setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmePeerLineAtn.setDescription('The current Line Attenuation in dB as perceived by the remote\n (link partner) PME.\n The value of 65535 is returned when the PME is Down or\n Initializing.\n\n This object is irrelevant for the -R PME subtypes. The value\n of 65535 SHALL be returned in this case.\n\n If a Clause 45 MDIO Interface is present, then this\n object maps to the 20P/2B link partner Line Attenuation\n register.')
efmCuPmeEquivalentLength = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 9), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,8192),ValueRangeConstraint(65535,65535),))).setUnits('m').setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeEquivalentLength.setDescription("An estimate of the equivalent loop's physical length in\n meters, as perceived by the PME after the link is established.\n An equivalent loop is a hypothetical 26AWG (0.4mm) loop with a\n perfect square root attenuation characteristic, without any\n bridged taps.\n The value of 65535 is returned if the link is Down or\n Initializing or the PME is unable to estimate the equivalent\n length.\n\n For a 10BASE-TL PME, if a Clause 45 MDIO Interface to the PME\n is present, then this object maps to the 10P Electrical Length\n register.")
efmCuPmeTCCodingErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeTCCodingErrors.setDescription('The number of 64/65-octet encapsulation errors. This counter\n is incremented for each 64/65-octet encapsulation error\n detected by the 64/65-octet receive function.\n\n This object maps to aTCCodingViolations attribute in\n Clause 30.\n\n If a Clause 45 MDIO Interface to the PME TC is present, then\n this object maps to the TC coding violations register\n (see 45.2.6.12).\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPmeTCCrcErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 3, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPmeTCCrcErrors.setDescription('The number of TC-CRC errors. This counter is incremented for\n each TC-CRC error detected by the 64/65-octet receive function\n (see 61.3.3.3 and Figure 61-19).\n\n This object maps to aTCCRCErrors attribute in\n Clause 30.\n\n If a Clause 45 MDIO Interface to the PME TC is present, then\n this object maps to the TC CRC error register\n (see 45.2.6.11).\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPme2B = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 2, 5))
efmCuPme2BProfileTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2), )
if mibBuilder.loadTexts: efmCuPme2BProfileTable.setDescription('This table supports definitions of administrative and\n operating profiles for 2BASE-TL PMEs.\n The first 14 entries in this table SHALL always be defined as\n follows (see 802.3ah Annex 63A):\n -------+-------+-------+-----+------+-------------+-----------\n Profile MinRate MaxRate Power Region Constellation Comment\n index (Kbps) (Kbps) (dBm)\n -------+-------+-------+-----+------+-------------+-----------\n 1 5696 5696 13.5 1 32-TCPAM default\n 2 3072 3072 13.5 1 32-TCPAM\n 3 2048 2048 13.5 1 16-TCPAM\n 4 1024 1024 13.5 1 16-TCPAM\n 5 704 704 13.5 1 16-TCPAM\n 6 512 512 13.5 1 16-TCPAM\n 7 5696 5696 14.5 2 32-TCPAM\n 8 3072 3072 14.5 2 32-TCPAM\n 9 2048 2048 14.5 2 16-TCPAM\n 10 1024 1024 13.5 2 16-TCPAM\n 11 704 704 13.5 2 16-TCPAM\n 12 512 512 13.5 2 16-TCPAM\n 13 192 5696 0 1 0 best effort\n 14 192 5696 0 2 0 best effort\n -------+-------+-------+-----+------+-------------+-----------\n\n These default entries SHALL be created during agent\n initialization and MUST NOT be deleted.\n\n Entries following the first 14 can be dynamically created and\n deleted to provide custom administrative (configuration)\n profiles and automatic operating profiles.\n\n This table MUST be maintained in a persistent manner.')
efmCuPme2BProfileEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1), ).setIndexNames((0, "EFM-CU-MIB", "efmCuPme2BProfileIndex"))
if mibBuilder.loadTexts: efmCuPme2BProfileEntry.setDescription("Each entry corresponds to a single 2BASE-TL PME profile.\n Each profile contains a set of parameters, used either for\n configuration or representation of a 2BASE-TL PME.\n In case a particular profile is referenced via the\n efmCuPmeAdminProfile object (or efmCuAdminProfile if\n efmCuPmeAdminProfile is zero), it represents the desired\n parameters for the 2BaseTL-O PME initialization.\n If a profile is referenced via an efmCuPmeOperProfile object,\n it represents the current operating parameters of an\n operational PME.\n\n Profiles may be created/deleted using the row creation/\n deletion mechanism via efmCuPme2BProfileRowStatus. If an\n active entry is referenced, the entry MUST remain 'active'\n until all references are removed.\n Default entries MUST NOT be removed.")
efmCuPme2BProfileIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 1), EfmProfileIndex())
if mibBuilder.loadTexts: efmCuPme2BProfileIndex.setDescription('2BASE-TL PME profile index.\n This object is the unique index associated with this profile.\n Entries in this table are referenced via efmCuAdminProfile or\n efmCuPmeAdminProfile objects.')
efmCuPme2BProfileDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 2), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BProfileDescr.setDescription('A textual string containing information about a 2BASE-TL PME\n profile. The string may include information about the data\n rate and spectral limitations of this particular profile.')
efmCuPme2BRegion = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("region1", 1), ("region2", 2),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BRegion.setDescription('Regional settings for a 2BASE-TL PME, as specified in the\n relevant Regional Annex of [G.991.2].\n Regional settings specify the Power Spectral Density (PSD)\n mask and the Power Back-Off (PBO) values, and place\n limitations on the max allowed data rate, power, and\n constellation.\n\n Possible values for this object are:\n region1 - Annexes A and F (e.g., North America)\n region2 - Annexes B and G (e.g., Europe)\n\n Annex A/B specify regional settings for data rates 192-2304\n Kbps using 16-TCPAM encoding.\n Annex F/G specify regional settings for rates 2320-3840 Kbps\n using 16-TCPAM encoding and 768-5696 Kbps using 32-TCPAM\n encoding.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object partially maps to the Region bits in the 2B general\n parameter register.')
efmCuPme2BsMode = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 4), EfmProfileIndexOrZero()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BsMode.setDescription('Desired custom Spectral Mode for a 2BASE-TL PME. This object\n\n\n\n is a pointer to an entry in efmCuPme2BsModeTable and a block\n of entries in efmCuPme2BRateReachTable, which together define\n (country-specific) reach-dependent rate limitations in\n addition to those defined by efmCuPme2BRegion.\n\n The value of this object is the index of the referenced\n spectral mode.\n The value of zero (default) indicates that no specific\n spectral mode is applicable.\n\n Attempts to set this object to a value that is not the value\n of the index for an active entry in the corresponding spectral\n mode table MUST be rejected.')
efmCuPme2BMinDataRate = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(192,5696))).setUnits('Kbps').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BMinDataRate.setDescription("Minimum Data Rate for the 2BASE-TL PME.\n This object can take values of (n x 64)Kbps,\n where n=3..60 for 16-TCPAM and n=12..89 for 32-TCPAM encoding.\n\n The data rate of the 2BASE-TL PME is considered 'fixed' when\n the value of this object equals that of efmCuPme2BMaxDataRate.\n If efmCuPme2BMinDataRate is less than efmCuPme2BMaxDataRate in\n the administrative profile, the data rate is considered\n 'adaptive', and SHALL be set to the maximum attainable rate\n not exceeding efmCuPme2BMaxDataRate, under the spectral\n limitations placed by the efmCuPme2BRegion and\n efmCuPme2BsMode.\n\n Note that the current operational data rate of the PME is\n represented by the ifSpeed object of IF-MIB.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the Min Data Rate1 bits in the 2B PMD\n parameters register.\n\n This object MUST be maintained in a persistent manner.")
efmCuPme2BMaxDataRate = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(192,5696))).setUnits('Kbps').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BMaxDataRate.setDescription("Maximum Data Rate for the 2BASE-TL PME.\n This object can take values of (n x 64)Kbps,\n where n=3..60 for 16-TCPAM and n=12..89 for 32-TCPAM encoding.\n\n The data rate of the 2BASE-TL PME is considered 'fixed' when\n the value of this object equals that of efmCuPme2BMinDataRate.\n If efmCuPme2BMinDataRate is less than efmCuPme2BMaxDataRate in\n the administrative profile, the data rate is considered\n 'adaptive', and SHALL be set to the maximum attainable rate\n not exceeding efmCuPme2BMaxDataRate, under the spectral\n limitations placed by the efmCuPme2BRegion and\n efmCuPme2BsMode.\n\n Note that the current operational data rate of the PME is\n represented by the ifSpeed object of IF-MIB.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the Max Data Rate1 bits in the 2B PMD\n parameters register.\n\n This object MUST be maintained in a persistent manner.")
efmCuPme2BPower = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 7), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,0),ValueRangeConstraint(10,42),))).setUnits('0.5 dBm').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BPower.setDescription('Signal Transmit Power. Multiple of 0.5 dBm.\n The value of 0 in the administrative profile means that the\n signal transmit power is not fixed and SHALL be set to\n maximize the attainable rate, under the spectral limitations\n placed by the efmCuPme2BRegion and efmCuPme2BsMode.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the Power1 bits in the 2B PMD parameters\n register.')
efmCuPme2BConstellation = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2,))).clone(namedValues=NamedValues(("adaptive", 0), ("tcpam16", 1), ("tcpam32", 2),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BConstellation.setDescription('TCPAM Constellation of the 2BASE-TL PME.\n The possible values are:\n adaptive(0) - either 16- or 32-TCPAM\n tcpam16(1) - 16-TCPAM\n tcpam32(2) - 32-TCPAM\n\n The value of adaptive(0) in the administrative profile means\n that the constellation is not fixed and SHALL be set to\n maximize the attainable rate, under the spectral limitations\n placed by the efmCuPme2BRegion and efmCuPme2BsMode.\n\n If a Clause 45 MDIO Interface to the PME is present, then this\n object maps to the Constellation1 bits in the 2B general\n parameter register.')
efmCuPme2BProfileRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 2, 1, 9), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BProfileRowStatus.setDescription("This object controls the creation, modification, or deletion\n of the associated entry in the efmCuPme2BProfileTable per the\n semantics of RowStatus.\n\n If an 'active' entry is referenced via efmCuAdminProfile or\n efmCuPmeAdminProfile instance(s), the entry MUST remain\n 'active'.\n\n An 'active' entry SHALL NOT be modified. In order to modify\n an existing entry, it MUST be taken out of service (by setting\n this object to 'notInService'), modified, and set 'active'\n again.")
efmCuPme2BsModeTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 3), )
if mibBuilder.loadTexts: efmCuPme2BsModeTable.setDescription('This table, together with efmCu2BReachRateTable, supports\n definition of administrative custom spectral modes for\n 2BASE-TL PMEs, describing spectral limitations in addition to\n those specified by efmCuPme2BRegion.\n\n In some countries, spectral regulations (e.g., UK ANFP) limit\n the length of the loops for certain data rates. This table\n allows these country-specific limitations to be specified.\n\n Entries in this table referenced by the efmCuPme2BsMode\n MUST NOT be deleted until all the active references are\n removed.\n\n This table MUST be maintained in a persistent manner.')
efmCuPme2BsModeEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 3, 1), ).setIndexNames((0, "EFM-CU-MIB", "efmCuPme2BsModeIndex"))
if mibBuilder.loadTexts: efmCuPme2BsModeEntry.setDescription('Each entry specifies a spectral mode description and its\n index, which is used to reference corresponding entries in the\n efmCu2BReachRateTable.\n\n Entries may be created/deleted using the row creation/\n deletion mechanism via efmCuPme2BsModeRowStatus.')
efmCuPme2BsModeIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 3, 1, 1), EfmProfileIndex())
if mibBuilder.loadTexts: efmCuPme2BsModeIndex.setDescription('2BASE-TL PME Spectral Mode index.\n This object is the unique index associated with this spectral\n mode.\n Entries in this table are referenced via the efmCuPme2BsMode\n object.')
efmCuPme2BsModeDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 3, 1, 2), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BsModeDescr.setDescription('A textual string containing information about a 2BASE-TL PME\n spectral mode. The string may include information about\n corresponding (country-specific) spectral regulations\n and rate/reach limitations of this particular spectral mode.')
efmCuPme2BsModeRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 3, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BsModeRowStatus.setDescription("This object controls creation, modification, or deletion of\n the associated entry in efmCuPme2BsModeTable per the semantics\n of RowStatus.\n\n If an 'active' entry is referenced via efmCuPme2BsMode\n instance(s), the entry MUST remain 'active'.\n\n An 'active' entry SHALL NOT be modified. In order to modify\n an existing entry, it MUST be taken out of service (by setting\n this object to 'notInService'), modified, and set 'active'\n again.")
efmCuPme2BReachRateTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4), )
if mibBuilder.loadTexts: efmCuPme2BReachRateTable.setDescription('This table supports the definition of administrative custom\n spectral modes for 2BASE-TL PMEs, providing spectral\n limitations in addition to those specified by\n efmCuPme2BRegion.\n\n\n\n\n The spectral regulations in some countries (e.g., UK ANFP)\n limit the length of the loops for certain data rates.\n This table allows these country-specific limitations to be\n specified.\n\n Below is an example of this table for [ANFP]:\n ----------+-------+-------\n Equivalent MaxRate MaxRate\n Length PAM16 PAM32\n (m) (Kbps) (Kbps)\n ----------+-------+-------\n 975 2304 5696\n 1125 2304 5504\n 1275 2304 5120\n 1350 2304 4864\n 1425 2304 4544\n 1500 2304 4288\n 1575 2304 3968\n 1650 2304 3776\n 1725 2304 3520\n 1800 2304 3264\n 1875 2304 3072\n 1950 2048 2688\n 2100 1792 2368\n 2250 1536 0\n 2400 1408 0\n 2550 1280 0\n 2775 1152 0\n 2925 1152 0\n 3150 1088 0\n 3375 1024 0\n ----------+-------+-------\n\n Entries in this table referenced by an efmCuPme2BsMode\n instance MUST NOT be deleted.\n\n This table MUST be maintained in a persistent manner.')
efmCuPme2BReachRateEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1), ).setIndexNames((0, "EFM-CU-MIB", "efmCuPme2BsModeIndex"), (0, "EFM-CU-MIB", "efmCuPme2BReachRateIndex"))
if mibBuilder.loadTexts: efmCuPme2BReachRateEntry.setDescription('Each entry specifies maximum 2BASE-TL PME data rates\n allowed for a certain equivalent loop length, when using\n\n\n\n 16-TCPAM or 32-TCPAM encoding.\n\n When a 2BASE-TL PME is initialized, its data rate MUST NOT\n exceed one of the following limitations:\n - the value of efmCuPme2BMaxDataRate\n - maximum data rate allowed by efmCuPme2BRegion and\n efmCuPme2BPower\n - maximum data rate for a given encoding specified in the\n efmCuPme2BsModeEntry, corresponding to the equivalent loop\n length, estimated by the PME\n\n It is RECOMMENDED that the efmCuPme2BEquivalentLength values\n are assigned in increasing order, starting from the minimum\n value.\n\n Entries may be created/deleted using the row creation/\n deletion mechanism via efmCuPme2ReachRateRowStatus.')
efmCuPme2BReachRateIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1, 1), EfmProfileIndex())
if mibBuilder.loadTexts: efmCuPme2BReachRateIndex.setDescription('2BASE-TL custom spectral mode Reach-Rate table index.\n This object is the unique index associated with each entry.')
efmCuPme2BEquivalentLength = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,8192))).setUnits('m').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BEquivalentLength.setDescription("Maximum allowed equivalent loop's physical length in meters\n for the specified data rates.\n An equivalent loop is a hypothetical 26AWG (0.4mm) loop with a\n perfect square root attenuation characteristic, without any\n\n\n\n bridged taps.")
efmCuPme2BMaxDataRatePam16 = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1, 3), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,0),ValueRangeConstraint(192,5696),))).setUnits('Kbps').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BMaxDataRatePam16.setDescription("Maximum data rate for a 2BASE-TL PME at the specified\n equivalent loop's length using TC-PAM16 encoding.\n The value of zero means that TC-PAM16 encoding should not be\n used at this distance.")
efmCuPme2BMaxDataRatePam32 = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1, 4), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,0),ValueRangeConstraint(192,5696),))).setUnits('Kbps').setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BMaxDataRatePam32.setDescription("Maximum data rate for a 2BASE-TL PME at the specified\n equivalent loop's length using TC-PAM32 encoding.\n The value of zero means that TC-PAM32 encoding should not be\n used at this distance.")
efmCuPme2BReachRateRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 5, 4, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme2BReachRateRowStatus.setDescription("This object controls the creation, modification, or deletion\n of the associated entry in the efmCuPme2BReachRateTable per\n the semantics of RowStatus.\n\n If an 'active' entry is referenced via efmCuPme2BsMode\n instance(s), the entry MUST remain 'active'.\n\n An 'active' entry SHALL NOT be modified. In order to modify\n an existing entry, it MUST be taken out of service (by setting\n this object to 'notInService'), modified, and set 'active'\n again.")
efmCuPme10P = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 1, 2, 6))
efmCuPme10PProfileTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1), )
if mibBuilder.loadTexts: efmCuPme10PProfileTable.setDescription('This table supports definitions of configuration profiles for\n 10PASS-TS PMEs.\n The first 22 entries in this table SHALL always be defined as\n follows (see 802.3ah Annex 62B.3, table 62B-1):\n -------+--------+----+---------+-----+-----+---------------\n Profile Bandplan UPBO BandNotch DRate URate Comment\n Index PSDMask# p# p# p# p#\n -------+--------+----+---------+-----+-----+---------------\n 1 1 3 2,6,10,11 20 20 default profile\n 2 13 5 0 20 20\n 3 1 1 0 20 20\n 4 16 0 0 100 100\n 5 16 0 0 70 50\n 6 6 0 0 50 10\n 7 17 0 0 30 30\n 8 8 0 0 30 5\n 9 4 0 0 25 25\n 10 4 0 0 15 15\n 11 23 0 0 10 10\n 12 23 0 0 5 5\n 13 16 0 2,5,9,11 100 100\n 14 16 0 2,5,9,11 70 50\n 15 6 0 2,6,10,11 50 10\n 16 17 0 2,5,9,11 30 30\n 17 8 0 2,6,10,11 30 5\n 18 4 0 2,6,10,11 25 25\n 19 4 0 2,6,10,11 15 15\n 20 23 0 2,5,9,11 10 10\n 21 23 0 2,5,9,11 5 5\n 22 30 0 0 200 50\n -------+--------+----+---------+-----+-----+---------------\n\n These default entries SHALL be created during agent\n initialization and MUST NOT be deleted.\n\n Entries following the first 22 can be dynamically created and\n deleted to provide custom administrative (configuration)\n profiles and automatic operating profiles.\n\n This table MUST be maintained in a persistent manner.')
efmCuPme10PProfileEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1), ).setIndexNames((0, "EFM-CU-MIB", "efmCuPme10PProfileIndex"))
if mibBuilder.loadTexts: efmCuPme10PProfileEntry.setDescription("Each entry corresponds to a single 10PASS-TS PME profile.\n\n Each profile contains a set of parameters, used either for\n configuration or representation of a 10PASS-TS PME.\n In case a particular profile is referenced via the\n efmCuPmeAdminProfile object (or efmCuAdminProfile if\n efmCuPmeAdminProfile is zero), it represents the desired\n parameters for the 10PassTS-O PME initialization.\n If a profile is referenced via an efmCuPmeOperProfile object,\n it represents the current operating parameters of the PME.\n\n Profiles may be created/deleted using the row creation/\n deletion mechanism via efmCuPme10PProfileRowStatus. If an\n 'active' entry is referenced, the entry MUST remain 'active'\n until all references are removed.\n Default entries MUST NOT be removed.")
efmCuPme10PProfileIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 1), EfmProfileIndex())
if mibBuilder.loadTexts: efmCuPme10PProfileIndex.setDescription('10PASS-TS PME profile index.\n This object is the unique index associated with this profile.\n Entries in this table are referenced via efmCuAdminProfile or\n efmCuPmeAdminProfile.')
efmCuPme10PProfileDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 2), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PProfileDescr.setDescription('A textual string containing information about a 10PASS-TS PME\n profile. The string may include information about data rate\n and spectral limitations of this particular profile.')
efmCuPme10PBandplanPSDMskProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,))).clone(namedValues=NamedValues(("profile1", 1), ("profile2", 2), ("profile3", 3), ("profile4", 4), ("profile5", 5), ("profile6", 6), ("profile7", 7), ("profile8", 8), ("profile9", 9), ("profile10", 10), ("profile11", 11), ("profile12", 12), ("profile13", 13), ("profile14", 14), ("profile15", 15), ("profile16", 16), ("profile17", 17), ("profile18", 18), ("profile19", 19), ("profile20", 20), ("profile21", 21), ("profile22", 22), ("profile23", 23), ("profile24", 24), ("profile25", 25), ("profile26", 26), ("profile27", 27), ("profile28", 28), ("profile29", 29), ("profile30", 30),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PBandplanPSDMskProfile.setDescription('The 10PASS-TS PME Bandplan and PSD Mask Profile, as specified\n in 802.3ah Annex 62A, table 62A-1. Possible values are:\n --------------+------------------------+------------+--------\n Profile Name PSD Mask Bands G.993.1\n 0/1/2/3/4/5 Bandplan\n --------------+------------------------+------------+--------\n profile1(1) T1.424 FTTCab.M1 x/D/U/D/U A\n profile2(2) T1.424 FTTEx.M1 x/D/U/D/U A\n profile3(3) T1.424 FTTCab.M2 x/D/U/D/U A\n profile4(4) T1.424 FTTEx.M2 x/D/U/D/U A\n profile5(5) T1.424 FTTCab.M1 D/D/U/D/U A\n profile6(6) T1.424 FTTEx.M1 D/D/U/D/U A\n profile7(7) T1.424 FTTCab.M2 D/D/U/D/U A\n profile8(8) T1.424 FTTEx.M2 D/D/U/D/U A\n profile9(9) T1.424 FTTCab.M1 U/D/U/D/x A\n profile10(10) T1.424 FTTEx.M1 U/D/U/D/x A\n profile11(11) T1.424 FTTCab.M2 U/D/U/D/x A\n profile12(12) T1.424 FTTEx.M2 U/D/U/D/x A\n profile13(13) TS 101 270-1 Pcab.M1.A x/D/U/D/U B\n profile14(14) TS 101 270-1 Pcab.M1.B x/D/U/D/U B\n profile15(15) TS 101 270-1 Pex.P1.M1 x/D/U/D/U B\n profile16(16) TS 101 270-1 Pex.P2.M1 x/D/U/D/U B\n profile17(17) TS 101 270-1 Pcab.M2 x/D/U/D/U B\n profile18(18) TS 101 270-1 Pex.P1.M2 x/D/U/D/U B\n profile19(19) TS 101 270-1 Pex.P2.M2 x/D/U/D/U B\n profile20(20) TS 101 270-1 Pcab.M1.A U/D/U/D/x B\n profile21(21) TS 101 270-1 Pcab.M1.B U/D/U/D/x B\n profile22(22) TS 101 270-1 Pex.P1.M1 U/D/U/D/x B\n profile23(23) TS 101 270-1 Pex.P2.M1 U/D/U/D/x B\n profile24(24) TS 101 270-1 Pcab.M2 U/D/U/D/x B\n profile25(25) TS 101 270-1 Pex.P1.M2 U/D/U/D/x B\n profile26(26) TS 101 270-1 Pex.P2.M2 U/D/U/D/x B\n profile27(27) G.993.1 F.1.2.1 x/D/U/D/U Annex F\n profile28(28) G.993.1 F.1.2.2 x/D/U/D/U Annex F\n profile29(29) G.993.1 F.1.2.3 x/D/U/D/U Annex F\n profile30(30) T1.424 FTTCab.M1 (ext.) x/D/U/D/U/D Annex A\n --------------+------------------------+------------+--------\n ')
efmCuPme10PUPBOReferenceProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,))).clone(namedValues=NamedValues(("profile0", 0), ("profile1", 1), ("profile2", 2), ("profile3", 3), ("profile4", 4), ("profile5", 5), ("profile6", 6), ("profile7", 7), ("profile8", 8), ("profile9", 9),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PUPBOReferenceProfile.setDescription('The 10PASS-TS PME Upstream Power Back-Off (UPBO) Reference\n PSD Profile, as specified in 802.3 Annex 62A, table 62A-3.\n Possible values are:\n ------------+-----------------------------\n Profile Name Reference PSD\n ------------+-----------------------------\n profile0(0) no profile\n profile1(1) T1.424 Noise A M1\n profile2(2) T1.424 Noise A M2\n profile3(3) T1.424 Noise F M1\n profile4(4) T1.424 Noise F M2\n profile5(5) TS 101 270-1 Noise A&B\n profile6(6) TS 101 270-1 Noise C\n profile7(7) TS 101 270-1 Noise D\n profile8(8) TS 101 270-1 Noise E\n profile9(9) TS 101 270-1 Noise F\n ------------+-----------------------------\n ')
efmCuPme10PBandNotchProfiles = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 5), Bits().clone(namedValues=NamedValues(("profile0", 0), ("profile1", 1), ("profile2", 2), ("profile3", 3), ("profile4", 4), ("profile5", 5), ("profile6", 6), ("profile7", 7), ("profile8", 8), ("profile9", 9), ("profile10", 10), ("profile11", 11),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PBandNotchProfiles.setDescription('The 10PASS-TS PME Egress Control Band Notch Profile bitmap,\n as specified in 802.3 Annex 62A, table 62A-4. Possible values\n are:\n --------------+--------+------+------------+------+------\n Profile Name G.991.3 T1.424 TS 101 270-1 StartF EndF\n table table table (MHz) (MHz)\n --------------+--------+------+------------+------+------\n profile0(0) no profile\n profile1(1) F-5 #01 - - 1.810 1.825\n profile2(2) 6-2 15-1 17 1.810 2.000\n profile3(3) F-5 #02 - - 1.907 1.912\n profile4(4) F-5 #03 - - 3.500 3.575\n profile5(5) 6-2 - 17 3.500 3.800\n profile6(6) - 15-1 - 3.500 4.000\n profile7(7) F-5 #04 - - 3.747 3.754\n profile8(8) F-5 #05 - - 3.791 3.805\n profile9(9) 6-2 - 17 7.000 7.100\n profile10(10) F-5 #06 15-1 - 7.000 7.300\n profile11(11) 6-2 15-1 1 10.100 10.150\n --------------+--------+------+------------+------+------\n\n Any combination of profiles can be specified by ORing\n individual profiles, for example, a value of 0x2230 selects\n profiles 2, 6, 10, and 11.')
efmCuPme10PPayloadDRateProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(5, 10, 15, 20, 25, 30, 50, 70, 100, 140, 200,))).clone(namedValues=NamedValues(("profile5", 5), ("profile10", 10), ("profile15", 15), ("profile20", 20), ("profile25", 25), ("profile30", 30), ("profile50", 50), ("profile70", 70), ("profile100", 100), ("profile140", 140), ("profile200", 200),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PPayloadDRateProfile.setDescription("The 10PASS-TS PME Downstream Payload Rate Profile, as\n\n\n\n specified in 802.3 Annex 62A. Possible values are:\n profile5(5) - 2.5 Mbps\n profile10(10) - 5 Mbps\n profile15(15) - 7.5 Mbps\n profile20(20) - 10 Mbps\n profile25(25) - 12.5 Mbps\n profile30(30) - 15 Mbps\n profile50(50) - 25 Mbps\n profile70(70) - 35 Mbps\n profile100(100) - 50 Mbps\n profile140(140) - 70 Mbps\n profile200(200) - 100 Mbps\n\n Each value represents a target for the PME's Downstream\n Payload Bitrate as seen at the MII. If the payload rate of\n the selected profile cannot be achieved based on the loop\n environment, bandplan, and PSD mask, the PME initialization\n SHALL fail.")
efmCuPme10PPayloadURateProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(5, 10, 15, 20, 25, 30, 50, 70, 100,))).clone(namedValues=NamedValues(("profile5", 5), ("profile10", 10), ("profile15", 15), ("profile20", 20), ("profile25", 25), ("profile30", 30), ("profile50", 50), ("profile70", 70), ("profile100", 100),))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PPayloadURateProfile.setDescription("The 10PASS-TS PME Upstream Payload Rate Profile, as specified\n in 802.3 Annex 62A. Possible values are:\n profile5(5) - 2.5 Mbps\n profile10(10) - 5 Mbps\n profile15(15) - 7.5 Mbps\n profile20(20) - 10 Mbps\n profile25(25) - 12.5 Mbps\n profile30(30) - 15 Mbps\n profile50(50) - 25 Mbps\n profile70(70) - 35 Mbps\n profile100(100) - 50 Mbps\n\n\n\n Each value represents a target for the PME's Upstream Payload\n Bitrate as seen at the MII. If the payload rate of the\n selected profile cannot be achieved based on the loop\n environment, bandplan, and PSD mask, the PME initialization\n SHALL fail.")
efmCuPme10PProfileRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: efmCuPme10PProfileRowStatus.setDescription("This object controls creation, modification, or deletion of\n the associated entry in efmCuPme10PProfileTable per the\n semantics of RowStatus.\n\n If an active entry is referenced via efmCuAdminProfile or\n efmCuPmeAdminProfile, the entry MUST remain 'active' until\n all references are removed.\n\n An 'active' entry SHALL NOT be modified. In order to modify\n an existing entry, it MUST be taken out of service (by setting\n this object to 'notInService'), modified, and set 'active'\n again.")
efmCuPme10PStatusTable = MibTable((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 2), )
if mibBuilder.loadTexts: efmCuPme10PStatusTable.setDescription('This table provides status information of EFMCu 10PASS-TS\n PMEs (modems).\n\n This table contains live data from the equipment. As such,\n it is NOT persistent.')
efmCuPme10PStatusEntry = MibTableRow((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: efmCuPme10PStatusEntry.setDescription('An entry in the EFMCu 10PASS-TS PME Status table.')
efmCuPme10PFECCorrectedBlocks = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 2, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPme10PFECCorrectedBlocks.setDescription('The number of received and corrected Forward Error Correction\n (FEC) codewords in this 10PASS-TS PME.\n\n This object maps to the aPMEFECCorrectedBlocks attribute in\n Clause 30.\n\n If a Clause 45 MDIO Interface to the PMA/PMD is present,\n then this object maps to the 10P FEC correctable errors\n register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuPme10PFECUncorrectedBlocks = MibTableColumn((1, 3, 6, 1, 2, 1, 167, 1, 2, 6, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: efmCuPme10PFECUncorrectedBlocks.setDescription('The number of received uncorrectable FEC codewords in this\n 10PASS-TS PME.\n\n This object maps to the aPMEFECUncorrectableBlocks attribute\n in Clause 30.\n\n If a Clause 45 MDIO Interface to the PMA/PMD is present,\n then this object maps to the 10P FEC uncorrectable errors\n register.\n\n Discontinuities in the value of this counter can occur at\n re-initialization of the management system, and at other times\n\n\n\n as indicated by the value of ifCounterDiscontinuityTime,\n defined in IF-MIB.')
efmCuGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 2, 1))
efmCuCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 167, 2, 2))
efmCuBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 1)).setObjects(*(("EFM-CU-MIB", "efmCuPAFSupported"), ("EFM-CU-MIB", "efmCuAdminProfile"), ("EFM-CU-MIB", "efmCuTargetDataRate"), ("EFM-CU-MIB", "efmCuTargetSnrMgn"), ("EFM-CU-MIB", "efmCuAdaptiveSpectra"), ("EFM-CU-MIB", "efmCuPortSide"), ("EFM-CU-MIB", "efmCuFltStatus"),))
if mibBuilder.loadTexts: efmCuBasicGroup.setDescription('A collection of objects representing management information\n common for all types of EFMCu ports.')
efmCuPAFGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 2)).setObjects(*(("EFM-CU-MIB", "efmCuPeerPAFSupported"), ("EFM-CU-MIB", "efmCuPAFCapacity"), ("EFM-CU-MIB", "efmCuPeerPAFCapacity"), ("EFM-CU-MIB", "efmCuPAFAdminState"), ("EFM-CU-MIB", "efmCuPAFDiscoveryCode"), ("EFM-CU-MIB", "efmCuPAFRemoteDiscoveryCode"), ("EFM-CU-MIB", "efmCuNumPMEs"),))
if mibBuilder.loadTexts: efmCuPAFGroup.setDescription('A collection of objects supporting OPTIONAL PME\n Aggregation Function (PAF) and PAF discovery in EFMCu ports.')
efmCuPAFErrorsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 3)).setObjects(*(("EFM-CU-MIB", "efmCuPAFInErrors"), ("EFM-CU-MIB", "efmCuPAFInSmallFragments"), ("EFM-CU-MIB", "efmCuPAFInLargeFragments"), ("EFM-CU-MIB", "efmCuPAFInBadFragments"), ("EFM-CU-MIB", "efmCuPAFInLostFragments"), ("EFM-CU-MIB", "efmCuPAFInLostStarts"), ("EFM-CU-MIB", "efmCuPAFInLostEnds"), ("EFM-CU-MIB", "efmCuPAFInOverflows"),))
if mibBuilder.loadTexts: efmCuPAFErrorsGroup.setDescription('A collection of objects supporting OPTIONAL error counters\n of PAF on EFMCu ports.')
efmCuPmeGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 4)).setObjects(*(("EFM-CU-MIB", "efmCuPmeAdminProfile"), ("EFM-CU-MIB", "efmCuPmeOperStatus"), ("EFM-CU-MIB", "efmCuPmeFltStatus"), ("EFM-CU-MIB", "efmCuPmeSubTypesSupported"), ("EFM-CU-MIB", "efmCuPmeAdminSubType"), ("EFM-CU-MIB", "efmCuPmeOperSubType"), ("EFM-CU-MIB", "efmCuPAFRemoteDiscoveryCode"), ("EFM-CU-MIB", "efmCuPmeOperProfile"), ("EFM-CU-MIB", "efmCuPmeSnrMgn"), ("EFM-CU-MIB", "efmCuPmePeerSnrMgn"), ("EFM-CU-MIB", "efmCuPmeLineAtn"), ("EFM-CU-MIB", "efmCuPmePeerLineAtn"), ("EFM-CU-MIB", "efmCuPmeEquivalentLength"), ("EFM-CU-MIB", "efmCuPmeTCCodingErrors"), ("EFM-CU-MIB", "efmCuPmeTCCrcErrors"), ("EFM-CU-MIB", "efmCuPmeThreshLineAtn"), ("EFM-CU-MIB", "efmCuPmeThreshSnrMgn"),))
if mibBuilder.loadTexts: efmCuPmeGroup.setDescription('A collection of objects providing information about\n a 2BASE-TL/10PASS-TS PME.')
efmCuAlarmConfGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 5)).setObjects(*(("EFM-CU-MIB", "efmCuThreshLowRate"), ("EFM-CU-MIB", "efmCuLowRateCrossingEnable"), ("EFM-CU-MIB", "efmCuPmeThreshLineAtn"), ("EFM-CU-MIB", "efmCuPmeLineAtnCrossingEnable"), ("EFM-CU-MIB", "efmCuPmeThreshSnrMgn"), ("EFM-CU-MIB", "efmCuPmeSnrMgnCrossingEnable"), ("EFM-CU-MIB", "efmCuPmeDeviceFaultEnable"), ("EFM-CU-MIB", "efmCuPmeConfigInitFailEnable"), ("EFM-CU-MIB", "efmCuPmeProtocolInitFailEnable"),))
if mibBuilder.loadTexts: efmCuAlarmConfGroup.setDescription('A collection of objects supporting configuration of alarm\n thresholds and notifications in EFMCu ports.')
efmCuNotificationGroup = NotificationGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 6)).setObjects(*(("EFM-CU-MIB", "efmCuLowRateCrossing"), ("EFM-CU-MIB", "efmCuPmeLineAtnCrossing"), ("EFM-CU-MIB", "efmCuPmeSnrMgnCrossing"), ("EFM-CU-MIB", "efmCuPmeDeviceFault"), ("EFM-CU-MIB", "efmCuPmeConfigInitFailure"), ("EFM-CU-MIB", "efmCuPmeProtocolInitFailure"),))
if mibBuilder.loadTexts: efmCuNotificationGroup.setDescription('This group supports notifications of significant conditions\n associated with EFMCu ports.')
efmCuPme2BProfileGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 7)).setObjects(*(("EFM-CU-MIB", "efmCuPme2BProfileDescr"), ("EFM-CU-MIB", "efmCuPme2BRegion"), ("EFM-CU-MIB", "efmCuPme2BsMode"), ("EFM-CU-MIB", "efmCuPme2BMinDataRate"), ("EFM-CU-MIB", "efmCuPme2BMaxDataRate"), ("EFM-CU-MIB", "efmCuPme2BPower"), ("EFM-CU-MIB", "efmCuPme2BConstellation"), ("EFM-CU-MIB", "efmCuPme2BProfileRowStatus"), ("EFM-CU-MIB", "efmCuPme2BsModeDescr"), ("EFM-CU-MIB", "efmCuPme2BsModeRowStatus"), ("EFM-CU-MIB", "efmCuPme2BEquivalentLength"), ("EFM-CU-MIB", "efmCuPme2BMaxDataRatePam16"), ("EFM-CU-MIB", "efmCuPme2BMaxDataRatePam32"), ("EFM-CU-MIB", "efmCuPme2BReachRateRowStatus"),))
if mibBuilder.loadTexts: efmCuPme2BProfileGroup.setDescription('A collection of objects that constitute a configuration\n\n\n\n profile for configuration of 2BASE-TL ports.')
efmCuPme10PProfileGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 8)).setObjects(*(("EFM-CU-MIB", "efmCuPme10PProfileDescr"), ("EFM-CU-MIB", "efmCuPme10PBandplanPSDMskProfile"), ("EFM-CU-MIB", "efmCuPme10PUPBOReferenceProfile"), ("EFM-CU-MIB", "efmCuPme10PBandNotchProfiles"), ("EFM-CU-MIB", "efmCuPme10PPayloadDRateProfile"), ("EFM-CU-MIB", "efmCuPme10PPayloadURateProfile"), ("EFM-CU-MIB", "efmCuPme10PProfileRowStatus"),))
if mibBuilder.loadTexts: efmCuPme10PProfileGroup.setDescription('A collection of objects that constitute a configuration\n profile for configuration of 10PASS-TS ports.')
efmCuPme10PStatusGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 167, 2, 1, 9)).setObjects(*(("EFM-CU-MIB", "efmCuPme10PFECCorrectedBlocks"), ("EFM-CU-MIB", "efmCuPme10PFECUncorrectedBlocks"),))
if mibBuilder.loadTexts: efmCuPme10PStatusGroup.setDescription('A collection of objects providing status information\n specific to 10PASS-TS PMEs.')
efmCuCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 167, 2, 2, 1)).setObjects(*(("EFM-CU-MIB", "efmCuBasicGroup"), ("EFM-CU-MIB", "efmCuPmeGroup"), ("EFM-CU-MIB", "efmCuAlarmConfGroup"), ("EFM-CU-MIB", "efmCuNotificationGroup"), ("EFM-CU-MIB", "efmCuPme2BProfileGroup"), ("EFM-CU-MIB", "efmCuPme10PProfileGroup"), ("EFM-CU-MIB", "efmCuPAFGroup"), ("EFM-CU-MIB", "efmCuPAFErrorsGroup"), ("EFM-CU-MIB", "efmCuPme10PStatusGroup"),))
if mibBuilder.loadTexts: efmCuCompliance.setDescription('The compliance statement for 2BASE-TL/10PASS-TS interfaces.\n Compliance with the following external compliance statements\n is REQUIRED:\n\n MIB Module Compliance Statement\n ---------- --------------------\n IF-MIB ifCompliance3\n EtherLike-MIB dot3Compliance2\n MAU-MIB mauModIfCompl3\n\n Compliance with the following external compliance statements\n is OPTIONAL for implementations supporting PME Aggregation\n Function (PAF) with flexible cross-connect between the PCS\n\n\n\n and PME ports:\n\n MIB Module Compliance Statement\n ---------- --------------------\n IF-INVERTED-STACK-MIB ifInvCompliance\n IF-CAP-STACK-MIB ifCapStackCompliance')
mibBuilder.exportSymbols("EFM-CU-MIB", efmCuPmeEquivalentLength=efmCuPmeEquivalentLength, efmCuPme2BMinDataRate=efmCuPme2BMinDataRate, efmCuLowRateCrossing=efmCuLowRateCrossing, efmCuPme2BMaxDataRatePam16=efmCuPme2BMaxDataRatePam16, efmCuAdminProfile=efmCuAdminProfile, efmCuPme10PProfileRowStatus=efmCuPme10PProfileRowStatus, efmCuPortCapabilityTable=efmCuPortCapabilityTable, efmCuPmeCapabilityTable=efmCuPmeCapabilityTable, efmCuPortSide=efmCuPortSide, efmCuPmeOperSubType=efmCuPmeOperSubType, efmCuPmeSnrMgnCrossingEnable=efmCuPmeSnrMgnCrossingEnable, efmCuPmeSnrMgnCrossing=efmCuPmeSnrMgnCrossing, efmCuPme10PBandplanPSDMskProfile=efmCuPme10PBandplanPSDMskProfile, PYSNMP_MODULE_ID=efmCuMIB, efmCuPme10PFECCorrectedBlocks=efmCuPme10PFECCorrectedBlocks, efmCuPAFInBadFragments=efmCuPAFInBadFragments, efmCuThreshLowRate=efmCuThreshLowRate, efmCuPme10PStatusTable=efmCuPme10PStatusTable, efmCuGroups=efmCuGroups, efmCuPAFErrorsGroup=efmCuPAFErrorsGroup, efmCuPme2BReachRateRowStatus=efmCuPme2BReachRateRowStatus, efmCuPme10PStatusGroup=efmCuPme10PStatusGroup, efmCuPortStatusTable=efmCuPortStatusTable, efmCuPme10PPayloadURateProfile=efmCuPme10PPayloadURateProfile, EfmProfileIndex=EfmProfileIndex, efmCuPmeSnrMgn=efmCuPmeSnrMgn, efmCuPAFDiscoveryCode=efmCuPAFDiscoveryCode, efmCuTargetDataRate=efmCuTargetDataRate, efmCuPme10P=efmCuPme10P, efmCuPmeLineAtnCrossing=efmCuPmeLineAtnCrossing, efmCuPmeConfEntry=efmCuPmeConfEntry, efmCuPme2BsModeTable=efmCuPme2BsModeTable, efmCuPmeStatusEntry=efmCuPmeStatusEntry, efmCuPortNotifications=efmCuPortNotifications, efmCuCompliance=efmCuCompliance, efmCuPme10PProfileIndex=efmCuPme10PProfileIndex, efmCuPAFAdminState=efmCuPAFAdminState, efmCuPme10PPayloadDRateProfile=efmCuPme10PPayloadDRateProfile, efmCuNotificationGroup=efmCuNotificationGroup, efmCuPme2BProfileDescr=efmCuPme2BProfileDescr, efmCuPmeProtocolInitFailure=efmCuPmeProtocolInitFailure, efmCuObjects=efmCuObjects, efmCuPAFSupported=efmCuPAFSupported, efmCuBasicGroup=efmCuBasicGroup, efmCuPme2BsModeDescr=efmCuPme2BsModeDescr, efmCuPmeConfigInitFailEnable=efmCuPmeConfigInitFailEnable, efmCuPme2BPower=efmCuPme2BPower, efmCuPmeDeviceFaultEnable=efmCuPmeDeviceFaultEnable, efmCuPmeGroup=efmCuPmeGroup, efmCuAdaptiveSpectra=efmCuAdaptiveSpectra, efmCuPmeAdminSubType=efmCuPmeAdminSubType, efmCuPeerPAFSupported=efmCuPeerPAFSupported, efmCuCompliances=efmCuCompliances, efmCuPAFInOverflows=efmCuPAFInOverflows, efmCuPAFGroup=efmCuPAFGroup, efmCuPme2BProfileRowStatus=efmCuPme2BProfileRowStatus, efmCuPmeSubTypesSupported=efmCuPmeSubTypesSupported, efmCuMIB=efmCuMIB, efmCuPme2BProfileGroup=efmCuPme2BProfileGroup, efmCuPme2BMaxDataRatePam32=efmCuPme2BMaxDataRatePam32, efmCuPme=efmCuPme, efmCuPme2BProfileIndex=efmCuPme2BProfileIndex, efmCuPAFInSmallFragments=efmCuPAFInSmallFragments, efmCuPmeLineAtn=efmCuPmeLineAtn, EfmProfileIndexOrZero=EfmProfileIndexOrZero, efmCuPortStatusEntry=efmCuPortStatusEntry, efmCuPmeAdminProfile=efmCuPmeAdminProfile, efmCuPeerPAFCapacity=efmCuPeerPAFCapacity, efmCuConformance=efmCuConformance, efmCuPAFCapacity=efmCuPAFCapacity, efmCuPme2BEquivalentLength=efmCuPme2BEquivalentLength, efmCuPme2BProfileTable=efmCuPme2BProfileTable, efmCuTargetSnrMgn=efmCuTargetSnrMgn, efmCuPme2BReachRateEntry=efmCuPme2BReachRateEntry, efmCuPme10PUPBOReferenceProfile=efmCuPme10PUPBOReferenceProfile, efmCuPme2BConstellation=efmCuPme2BConstellation, efmCuPme10PProfileEntry=efmCuPme10PProfileEntry, efmCuPme2BMaxDataRate=efmCuPme2BMaxDataRate, efmCuAlarmConfGroup=efmCuAlarmConfGroup, efmCuPortCapabilityEntry=efmCuPortCapabilityEntry, efmCuLowRateCrossingEnable=efmCuLowRateCrossingEnable, efmCuPme10PBandNotchProfiles=efmCuPme10PBandNotchProfiles, EfmTruthValueOrUnknown=EfmTruthValueOrUnknown, efmCuPme2BsModeRowStatus=efmCuPme2BsModeRowStatus, efmCuPAFInLostStarts=efmCuPAFInLostStarts, efmCuPmeProtocolInitFailEnable=efmCuPmeProtocolInitFailEnable, efmCuPmeCapabilityEntry=efmCuPmeCapabilityEntry, efmCuPme2BReachRateIndex=efmCuPme2BReachRateIndex, efmCuPmeConfigInitFailure=efmCuPmeConfigInitFailure, efmCuPort=efmCuPort, efmCuNumPMEs=efmCuNumPMEs, efmCuPmeNotifications=efmCuPmeNotifications, efmCuPmePeerLineAtn=efmCuPmePeerLineAtn, efmCuPme2B=efmCuPme2B, efmCuPmeDeviceFault=efmCuPmeDeviceFault, efmCuPmeLineAtnCrossingEnable=efmCuPmeLineAtnCrossingEnable, efmCuPmeOperStatus=efmCuPmeOperStatus, efmCuPme10PFECUncorrectedBlocks=efmCuPme10PFECUncorrectedBlocks, efmCuPme2BProfileEntry=efmCuPme2BProfileEntry, efmCuPme10PProfileGroup=efmCuPme10PProfileGroup, efmCuPmeThreshSnrMgn=efmCuPmeThreshSnrMgn, efmCuFltStatus=efmCuFltStatus, efmCuPme2BsMode=efmCuPme2BsMode, efmCuPme2BRegion=efmCuPme2BRegion, efmCuPme10PStatusEntry=efmCuPme10PStatusEntry, efmCuPAFInErrors=efmCuPAFInErrors, efmCuPAFInLargeFragments=efmCuPAFInLargeFragments, efmCuPAFInLostFragments=efmCuPAFInLostFragments, efmCuPAFRemoteDiscoveryCode=efmCuPAFRemoteDiscoveryCode, efmCuPmeConfTable=efmCuPmeConfTable, efmCuPme2BReachRateTable=efmCuPme2BReachRateTable, efmCuPmeThreshLineAtn=efmCuPmeThreshLineAtn, efmCuPmeStatusTable=efmCuPmeStatusTable, efmCuPortConfEntry=efmCuPortConfEntry, efmCuPmeFltStatus=efmCuPmeFltStatus, efmCuPme2BsModeIndex=efmCuPme2BsModeIndex, efmCuPmePeerSnrMgn=efmCuPmePeerSnrMgn, efmCuPmeTCCrcErrors=efmCuPmeTCCrcErrors, efmCuPAFInLostEnds=efmCuPAFInLostEnds, EfmProfileIndexList=EfmProfileIndexList, efmCuPmeOperProfile=efmCuPmeOperProfile, efmCuPme10PProfileDescr=efmCuPme10PProfileDescr, efmCuPortConfTable=efmCuPortConfTable, efmCuPme10PProfileTable=efmCuPme10PProfileTable, efmCuPme2BsModeEntry=efmCuPme2BsModeEntry, efmCuPmeTCCodingErrors=efmCuPmeTCCodingErrors)
|
# (c) 2021 Leon Luithlen
# This code is licensed under MIT license
def strongly_typed(*args, **kwargs):
stargs = args
stkwargs = kwargs
def type_strongly(func):
def wrapper(*args, **kwargs):
for arg, type_ in zip(args, stargs):
assert isinstance(arg,type_), f"{arg} should be of type {type_}"
for kw, arg in kwargs.items():
assert isinstance(arg, stkwargs[kw]), f"{kw} should be of type {stkwargs[kw]} but is of type {type(arg)}: {arg}"
return(func(*args, **kwargs))
return(wrapper)
return(type_strongly)
@strongly_typed(int, str, i=int, s=str)
def check_if_int_and_string(i, s):
if type(i) == int and type(s) == str:
print("hi")
else:
print("Not a number or not a string")
|
# ==== Start of helper classes to be used by TriggerExtractorResultCollection ====
class DocumentPrediction(object):
def __init__(self, docid):
self.docid = docid
self.sentences = dict()
""":type: dict[str, SentencePrediction]"""
def to_json(self):
d = dict()
d['docid'] = self.docid
sentences = []
for sentence in self.sentences.values():
sentences.append(sentence.to_json())
d['sentences'] = sentences
return d
class SentencePrediction(object):
def __init__(self, start, end):
self.id = None
self.text = None
self.start = start # start offset
self.end = end # end offset
self.events = dict()
""":type: dict[str, EventPrediction]"""
self.event_event_relations = dict()
""":type: dict[tuple, SentencePrediction]"""
def to_json(self):
d = dict()
d['start'] = self.start
d['end'] = self.end
events = []
for event in self.events.values():
events.append(event.to_json())
d['events'] = events
event_event_relations = list()
for event_event_relation in self.event_event_relations.values():
event_event_relations.append(event_event_relation.to_json())
d['event_event_relations'] = event_event_relations
return d
class EventPrediction(object):
def __init__(self, trigger):
self.id = None
self.trigger = trigger # each EventPrediction is based on a single TriggerPrediction
""":type: TriggerPrediction"""
self.arguments = dict() # but can have multiple arguments
""":type: dict[str, ArgumentPrediction]"""
def to_json(self):
d = dict()
d['trigger'] = self.trigger.to_json()
args = []
for arg in self.arguments.values():
args.append(arg.to_json())
d['arguments'] = args
return d
class TriggerPrediction(object):
def __init__(self, start, end):
self.id = None
self.text = None
self.start = start
self.end = end
self.labels = dict() # we assume that a single span (start, end) might have multiple predictions
""":type: dict[str, float]"""
def to_json(self):
d = dict()
d['start'] = self.start
d['end'] = self.end
l = dict()
for label in self.labels:
l[label] = '%.4f' % (self.labels[label])
d['labels'] = l
return d
class ArgumentPrediction(object):
def __init__(self, start, end):
self.id = None
self.text = None
self.start = start
self.end = end
self.labels = dict()
""":type: dict[str, float]"""
self.em_id = None # an argument is usually based on an EntityMention, so we allow capturing of the EntityMention id here
def to_json(self):
d = dict()
d['start'] = self.start
d['end'] = self.end
d['em_id'] = self.em_id
l = dict()
for label in self.labels:
l[label] = '%.4f' % (self.labels[label])
d['labels'] = l
return d
class EventEventRelationPrediction(object):
def __init__(self,left_event:EventPrediction,right_event:EventPrediction):
self.left_event = left_event
self.right_event = right_event
self.labels = dict()
""":type: dict[str, float]"""
def to_json(self):
d = dict()
d['left_event'] = self.left_event.to_json()
d['right_event'] = self.right_event.to_json()
for label in self.labels:
d[label] = '%.4f' % (self.labels[label])
d['labels'] = d
return d
# ==== End of helper classes ====
|
"""
Task 1
FizzBuzz has been used as a common challenge during programmer interviews, it requires the
interviewee to write code that prints the numbers between 1 and 100 with the following rules:
•If a number is divisible by 3, print “Fizz”
•If a number is divisible by 5, print “Buzz”
•If a number is divisible by both 3 and 5, print “FizzBuzz”
•Otherwise, print the number
Implement a function that will work through FizzBuzz for the specified number range. Your program
should ask the user for a high and low value before running the function.
Save your program as ex10.py.
"""
#should ask the user for a high and low value before running the function.
#value = input(int(Enter a value betwwen 0(low) and 100(high)))
#function
def FizzBuzz (low,high):
for num in range(low,high):
if num%3==0 and num%5==0:
print("FizzBuzz")
elif num%3==0:
print("Fizz")
elif num%5==0:
print("Buzz")
else:
print(num)
FizzBuzz(1,100)
|
"""
https://leetcode.com/problems/reshape-the-matrix/
566. Reshape the Matrix (Easy)
"""
class Solution:
def matrixReshape(self, mat, r, c):
m = len(mat)
n = len(mat[0])
if m*n != r*c:
return mat
rLoc = 0
cLoc = 0
result = []
row = []
for i in mat:
for j in i:
row.append(j)
cLoc = cLoc + 1
if cLoc == c:
rLoc = rLoc + 1
cLoc = 0
result.append(row[:])
row = []
return result
|
'''
A string with parentheses is well bracketed if all parentheses are matched: every opening bracket has a matching closing bracket and vice versa.
Write a Python function wellbracketed(s) that takes a string s containing parentheses and returns True if s is well bracketed and False otherwise.
Hint: Keep track of the nesting depth of brackets. Initially the depth is 0. The depth increases with each opening bracket and decreases with each closing bracket. What are the constraints on the value of the nesting depth for the string to be wellbracketed?
Here are some examples to show how your function should work.
>>> wellbracketed("22)")
False
>>> wellbracketed("(a+b)(a-b)")
True
>>> wellbracketed("(a(b+c)-d)((e+f)")
False
'''
def wellbracketed(s):
l = list(s)
depth = 0
for c in l:
if c == '(':
depth += 1
elif c == ')':
depth -= 1
if depth == 0:
return True
else:
return False
print(wellbracketed("22)"))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 16:51:16 2019
@author: linyizi
"""
|
# Models are decision tree
# Batandwa Mgutsi
# 12/03/2020
class DecisionCase:
"""A Decision case has a sentence and a set of two other decision cases to execute on yes and on no"""
"""answers by the user in case the DecisonCase requires input"""
sentence = None
requiresAnswer = True
yesCase = None
noCase = None
def __init__(self, sentence, requiresAnswer=True, yesCase=None, noCase=None):
self.sentence = sentence
self.yesCase = yesCase
self.noCase = noCase
self.requiresAnswer = requiresAnswer
def executeDecisionCase(decisionCase):
print(decisionCase.sentence)
if(decisionCase.requiresAnswer):
answer = input()
if(answer == 'yes' and decisionCase.yesCase != None):
executeDecisionCase(decisionCase.yesCase)
elif(answer == 'no' and decisionCase.noCase != None):
executeDecisionCase(decisionCase.noCase)
else:
print("Please enter a 'yes' or a 'no'")
executeDecisionCase(decisionCase)
# These are all the decison that have to be made
isBoy = DecisionCase(
sentence='Are you a boy?',
requiresAnswer=True,
yesCase=DecisionCase(
sentence='You are a boy!',
requiresAnswer=False,
),
noCase=DecisionCase(
sentence='MMM!! Are you a girl?',
requiresAnswer=True,
yesCase=DecisionCase(
sentence='You are a girl!',
requiresAnswer=False,
),
noCase=DecisionCase(
sentence='MMM! i am so confused right now!',
requiresAnswer=False
)
)
)
executeDecisionCase(isBoy)
|
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
length = len(cost)
dp = [0 for x in range(0, length)]
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, length):
# Remember to divided into two cases, if you get into the top of
# stair like case 1, you don't need to add cost into your dp, but
# in other cases, you need to do this, add cost into dp
if i == length - 1:
dp[i] = min(dp[i - 1], dp[i - 2] + cost[i])
else:
dp[i] = min(dp[i - 1] + cost[i], dp[i-2] + cost[i])
return dp[-1]
|
print('\033[1;93m=-=-=-=- \033[1;94mAula de tuplas \033[1;93m=-=-=-=\033[m')
#Tuplas são imutáveis
lanche = ('hamburguer', 'suco', 'pizza', 'pudim')
print(lanche[2])
print(lanche[0:2])
print(lanche[1:])
print(lanche[-1])
print(len(lanche))
print(' ')
lanche = ('hamburguer', 'suco', 'pizza', 'pudim')
for c in lanche:
if c == 'suco':
print(f'Eu vou tomar {c}')
else:
print(f'Eu vou comer {c}')
print(' ')
for i in range(0, len(lanche)):
print(f'Eu vou comer {lanche[i]}')
print(' ')
for pos, eat in enumerate(lanche):
print(f'0{pos+1} -> {eat}')
print(sorted(lanche))
a = (0, 2, 4, 6, 8)
b = (1, 3, 5, 7, 9)
d = a + b
print(sorted(d))
print(' ')
print(d.count(8))
print(sorted(d).index(8))
print(' \n ')
pessoa = ('Davi', '15', 'M', 63.5)
for p in pessoa:
print(f'{p}')
del(lanche)
|
PLURAL_KEYS = (
"view",
"measure",
"dimension",
"dimension_group",
"filter",
"access_filter",
"bind_filters",
"map_layer",
"parameter",
"set",
"column",
"derived_column",
"include",
"explore",
"link",
"when",
"allowed_value",
"named_value_format",
"join",
"datagroup",
"access_grant",
"sql_step",
"sql_where",
"action",
"param",
"form_param",
"option",
"user_attribute_param",
)
EXPR_BLOCK_KEYS = (
"expression_custom_filter",
"html",
"sql_trigger_value",
"sql_table_name",
"sql_distinct_key",
"sql_start",
"sql_always_having",
"sql_always_where",
"sql_trigger",
"sql_foreign_key",
"sql_where",
"sql_end",
"sql_create",
"sql_latitude",
"sql_longitude",
"sql_step",
"sql_on",
"sql",
)
QUOTED_LITERAL_KEYS = (
"label",
"view_label",
"group_label",
"group_item_label",
"suggest_persist_for",
"default_value",
"direction",
"value_format",
"name",
"url",
"icon_url",
"form_url",
"default",
"tags",
"value",
"description",
"sortkeys",
"indexes",
"partition_keys",
"connection",
"include",
"max_cache_age",
"allowed_values",
"timezone",
"persist_for",
"cluster_keys",
"distribution",
"extents_json_url",
"feature_key",
"file",
"property_key",
"property_label_key",
"else",
)
KEYS_WITH_NAME_FIELDS = ("user_attribute_param", "param", "form_param", "option")
|
A = 26
MOD = 1_000_000_007
def shortPalindrome(s):
c1 = [0] * A
c2 = [[0] * A for _ in range(A)]
c3 = [0] * A
res = 0
for i in (ord(c) - 97 for c in s):
res = (res + c3[i]) % MOD
for j in range(A):
c3[j] += c2[j][i]
for j in range(A):
c2[j][i] += c1[j]
c1[i] += 1
return res
print(shortPalindrome(input()))
|
"""Exceptions for downtoearth.
These are helpers provided so that you can raise proper HTTP code errors from your API.
Usage:
from downtoearth.exceptions import NotFoundException
raise NotFoundException('your princess is in another castle')
"""
class BadRequestException(Exception):
def __init__(self, msg):
prefix = '[Bad Request]'
super(BadRequestException, self).__init__(prefix + ' ' + msg)
class ConflictException(Exception):
def __init__(self, msg):
prefix = '[Conflict]'
super(ConflictException, self).__init__(prefix + ' ' + msg)
class InternalServerErrorException(Exception):
def __init__(self, msg):
prefix = '[Internal Server Error]'
super(InternalServerErrorException, self).__init__(prefix + ' ' + msg)
class NotFoundException(Exception):
def __init__(self, msg):
prefix = '[Not Found]'
super(NotFoundException, self).__init__(prefix + ' ' + msg)
class NotImplementedException(Exception):
def __init__(self, msg):
prefix = '[Not Implemented]'
super(NotImplementedException, self).__init__(prefix + ' ' + msg)
|
class Solution:
def isPalindrome(self, x: int) -> bool:
i = 0
str_x = str(x)
n = len(str_x)
while i < n-i-1:
if str_x[i] != str_x[n-i-1]:
return False
i += 1
return True |
"""2017 Advent of Code, Day 2"""
with open("input", "r+") as file:
puzzle_input = file.readlines()
SPREADSHEET = []
CHECKSUM = 0
CHECKSUM_2 = 0
for row in puzzle_input:
SPREADSHEET.append([int(value) for value in row.strip().split()])
for row in SPREADSHEET:
row.sort()
CHECKSUM += row[-1] - row[0]
for index, value in enumerate(row):
for second_index, second_value in enumerate(row):
if index != second_index and not value % second_value:
CHECKSUM_2 += value // second_value
print(CHECKSUM, CHECKSUM_2) |
class Solution:
def getSkyline(self, buildings: [[int]]) -> [[int]]:
if not buildings:
return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = self.getSkyline(buildings[:mid])
right = self.getSkyline(buildings[mid:])
return self.merge(left, right)
def merge(self, left, right):
lh = rh = l = r = 0
res = []
while l < len(left) and r < len(right):
if left[l][0] < right[r][0]:
cp = [left[l][0], max(left[l][1], rh)]
lh = left[l][1]
l += 1
elif left[l][0] > right[r][0]:
cp = [right[r][0], max(right[r][1], lh)]
rh = right[r][1]
r += 1
else:
cp = [left[l][0], max(left[l][1], right[r][1])]
lh, rh = left[l][1], right[r][1]
l += 1
r += 1
if len(res) == 0 or res[-1][1] != cp[1]:
res.append(cp)
res += left[l:] + right[r:]
return res
|
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def valid(sub):
nums = [item for item in sub if item.isdigit()]
return len(set(nums)) == len(nums)
def check_row():
return all(valid(row) for row in board)
def check_col():
return all(valid(col) for col in zip(*board))
def check_sub():
return all(valid([board[r + dr][c + dc]
for dr in range(3) for dc in range(3)])
for r, c in itertools.product((0, 3, 6), repeat=2))
return check_row() and check_col() and check_sub() |
class Node (object):
def __init__(self, leaf, num_spaces=4):
self.name = leaf[0]
self.num_spaces = num_spaces
leaves = leaf[1:]
if len(leaves):
self.leaves = [Node(leaves, num_spaces)]
else:
self.leaves = None
# Returns true when the leaves are added to this branch. False, otherwise.
def add(self, leaves):
if leaves[0] != self.name: return False
leaves = leaves[1:]
if not len(leaves): return False
for leaf in self.leaves:
if leaf.add(leaves): return True
self.leaves.append(Node(leaves, self.num_spaces))
return True
def generate(self, level):
spaces = (level * self.num_spaces) * " "
if not self.leaves:
return spaces + self.name
blocks = [leaf.generate(level+1) for leaf in self.leaves]
return "{}{} {{\n{}\n{}}}".format(spaces, self.name, "\n".join(blocks), spaces)
class GradleConfigBuilder (object):
def __init__(self, tab_space=4, source=None, filepath=None):
self.tab_space = tab_space
self.registry = []
if source:
self.load_source(source)
elif filepath:
self.load_file(filepath)
#
# Load a config from source.
#
# When loading from source, it expects every command to be on its own line.
# Having commands like 'dependencies {\n command; }' are not allowed. But
# 'dependencies {\n command \n}' are allowed.
#
def load_source(self, source):
paths = self.get_paths(source)
for path in paths:
self.add(*path)
def load_file(self, filepath):
fh = open(filepath, "r")
source = fh.read()
fh.close()
self.load_source(source)
def get_paths(self, source):
# Create tuples that will then be added.
nodes = []
paths = []
for line in source.split("\n"):
if "{" in line and "}" in line:
nodes.append(line.strip())
paths.append(nodes[:])
nodes.pop()
elif "{" in line:
pos = line.find("}")
nodes.append(line[:pos].strip())
elif "}" in line:
nodes.pop()
elif len(line.strip()) and line.strip()[0:2] != "//":
nodes.append(line.strip())
paths.append(nodes[:])
nodes.pop()
return paths
def add(self, *path):
new_entry = list(path)
for entry in self.registry:
if new_entry == entry: return
self.registry.append(new_entry)
def insert(self, at_idx, *path):
new_entry = list(path)
if not self.registry:
self.registry.append(new_entry)
return
prev_entry = None
current_idx = 0
idx = 0
for entry in self.registry:
if prev_entry is None:
prev_entry = entry
elif prev_entry[0] != entry[0]:
# At the very end of this group. Now add the entry.
if current_idx == at_idx: break
current_idx += 1
# Insert the new entry if the entry occupying the index
# is not of the same group. Otherwise, wait until the
# last entry in the group has been added.
if current_idx == at_idx and new_entry[0] != entry[0]:
break
prev_entry = entry
idx += 1
self.registry.insert(idx, new_entry)
def after(self, after_entry, *path):
new_entry = list(path)
for idx, entry in enumerate(self.registry):
if entry == after_entry:
next_idx = idx + 1
# Already exists.
if next_idx < len(self.registry) and self.registry[next_idx] == new_entry:
return
self.registry.insert(next_idx, new_entry)
return
def replace(self, subject, replacement):
registry = []
for entry in self.registry[:]:
for idx, item in enumerate(entry[:]):
if subject in item:
item = item.replace(subject, str(replacement))
entry[idx] = item
registry.append(entry)
self.registry = registry
def get_nodes(self):
def add_node(nodes, entry):
for node in nodes:
if node.add(entry):
return True
return False
nodes = []
for entry in self.registry:
if not add_node(nodes, entry):
nodes.append(Node(entry))
return nodes
def generate(self):
blocks = []
for node in self.get_nodes():
blocks.append(node.generate(0))
return "\n\n".join(blocks)
def save(self, filepath):
fh = open(filepath, "w")
fh.write(self.generate())
fh.close()
|
# isr1.py - Timer to activate units in a cycle
# The 7-segment units are controlled one-by one in a cycle, using a timer interrupt for consistent light output.
# Model 1: every timer interrupt, the control switches from one unit to the next.
# User configuration
framebuf = "ABCD" # User configuration: desired content on the 7-segment units
# Static system configuration
TIMER_MS = 5 # Static system configuration: timer fire rate
UNITCOUNT = 4 # Static system configuration: number of 7-segment units
assert TIMER_MS>=1 # Depends on CPU clock speed but should not too low or the CPU load becomes to high.
assert TIMER_MS*UNITCOUNT<=20 # Refresh time should not be too long; refresh frequencies above 50Hz cause visual flicker.
assert UNITCOUNT==len(framebuf) # frame buffer content matches UNITCOUNT
# ISR state (private)
_unit = UNITCOUNT-1 # ISR state: the 7-segment unit currently under control
# Hardware state (private)
_rows = '?' # Hardware state: control of the rows (LED segments of the units)
_column= '?' # Hardware state: control of the column (the "common" pin of the units)
# Helper to visualize the result
_unitlog = ""
_rowslog = ""
_columnlog = ""
def log(sep=None) :
global _unitlog, _rowslog, _columnlog
global _slot, _unit, _rows, _column
if sep :
_unitlog += sep
_rowslog += sep
_columnlog+= sep
_unitlog += chr(_unit+48)
_rowslog += _rows
_columnlog+= _column
def isr() :
global _unit, _rows, _column
sep = None
# Timer expired: control next unit
_column = '-'
_unit += 1
# Wrap around the unit
if _unit>=UNITCOUNT :
_unit = 0
sep = '|'
# New unit under control
_rows = framebuf[_unit]
_column = chr(_unit+48)
log(sep)
for interrupt in range(UNITCOUNT+11) :
isr()
print( f"user : content '{framebuf}'")
print( f"system: frame is {UNITCOUNT} ISR ticks of {TIMER_MS} ms, one per 7-segment unit")
print()
print( f"unit : {_unitlog}")
print( f"rows : {_rowslog}")
print( f"column: {_columnlog}")
print()
print( "Every ISR tick, the rows and column of a (next) unit are powered")
# user : content 'ABCD'
# system: frame is 4 ISR ticks of 5 ms, one per 7-segment unit
#
# unit : |0123|0123|0123|012
# rows : |ABCD|ABCD|ABCD|ABC
# column: |0123|0123|0123|012
#
# Every ISR tick, the rows and column of a (next) unit are powered |
letters = {}
for c in input():
if c in letters:
letters[c] += 1
else:
letters[c] = 1
max_double = max(letters.values())
if max_double == 1:
print(len(letters))
for l in letters:
print(l)
exit(0)
if list(letters.values()).count(max_double) == 1:
print(1)
for l, k in letters.items():
print(l*k, end='')
print()
exit(0)
ans1 = ""
found_first = False
ans2 = ""
found_second = False
for l, k in letters.items():
if k == max_double and not found_first:
ans1 += l*k
found_first = True
continue
if k == max_double and found_first and not found_second:
ans2 += l*k
found_second = True
continue
if k == max_double and found_first and found_second:
ans1 += l
ans2 += l*(k-1)
continue
if k != max_double:
ans1 += l*k
print(2)
print(ans1)
print(ans2)
|
#Generate Christmas Tree Pattern
# Generating Triangle Shape
def triangleShape(n):
for i in range(n):
for j in range(n-i):
print(' ', end=' ')
for k in range(2*i+1):
print('*',end=' ')
print()
# Generating Pole Shape
def poleShape(n):
for i in range(n):
for j in range(n-1):
print(' ', end=' ')
print('* * *')
# Input and Function Call
#row = int(input('Enter number of rows: '))
triangleShape(10)
triangleShape(10)
triangleShape(10)
poleShape(10) |
"""A set of function(s) that are used for estimating frame per second (fps).
These function(s) often receive an inference time, perform some calculation on it.
The function(s) do return a fps value.
"""
def convert_infr_time_to_fps(infr_time: float) -> int:
# Gets the time of inference (infr_time) and returns Frames Per Second (fps)
fps = int(1.0 / infr_time)
return fps
|
class Node():
"""Building Block of Linked List."""
def __init__(self, data):
"""Initialize Node.
Args:
data: The data to be stored.
"""
self.data = data
self.next = None
def __str__(self):
"""String representation of Node."""
return "({}, {})".format(self.data, self.next)
def __repr__(self):
"""Representation of Node."""
return "pyDS.linked_list.Node({}, {})".format(self.data, self.next)
class LinkedList():
"""An implementation of the Linked List data structure."""
def __init__(self):
"""Initialize Linked List."""
self.head = None
def __repr__(self):
"""Representation of Linked List."""
return "pyDS.linked_list.LinkedList({})".format(self.head)
def __iter__(self):
"""Iterate through the Linked List.
Returns:
Generator object.
"""
ptr = self.head
while (ptr):
yield ptr.data
ptr = ptr.next
def __reversed__(self):
"""Reverse the Linked List."""
self.reverse()
def push(self, item):
"""Add item to the front of the Linked List.
Args:
item: The item to be inserted.
"""
new_node = Node(item)
new_node.next = self.head
self.head = new_node
def append(self, item):
"""Add item to the end of the Linked List.
Args:
item: The item to be inserted.
"""
new_node = Node(item)
if self.head is None:
self.head = new_node
return
ptr = self.head
while (ptr.next):
ptr = ptr.next
ptr.next = new_node
def delete(self, item):
"""Delete an item from the Linked List."""
if self.head is None:
raise IndexError('Empty Linked List')
elif self.head.data == item:
self.head = self.head.next
return
temp = self.head
prev = None
while (temp):
if temp.data == item:
break
prev = temp
temp = temp.next
if temp is None:
raise ValueError('Item {} not in Linked List'.format(item))
else:
prev.next = temp.next
def reverse(self):
"""Reverse the items of the Linked List."""
current_ptr = self.head
prev_ptr = None
while current_ptr:
next_ptr = current_ptr.next
current_ptr.next = prev_ptr
prev_ptr = current_ptr
current_ptr = next_ptr
self.head = prev_ptr
|
# check if a number is odd or even
num = int(input("Enter a number: "))
if num%2: # note that it is not checked with ==; result of %2 is 0 or 1 which can be translated as False or True
print("The number is odd")
else:
print("The number is even") |
# zwei 06/16/2014
# inspired by sympy.utilities.iterables.kbins.partition()
def partition(lista, bins):
# EnricoGiampieri's partition generator from
# http://stackoverflow.com/questions/13131491/
# partition-n-items-into-k-bins-in-python-lazily
if len(lista) == 1 or bins == 1:
yield [lista]
elif len(lista) > 1 and bins > 1:
for i in range(1, len(lista)):
for part in partition(lista[i:], bins - 1):
if len([lista[:i]] + part) == bins:
yield [lista[:i]] + part
for i in partition(range(3), 3):
print(i)
|
"""
Writing a Function that accepts 2 parameters.
Draws a playing board based on the rows and columns input
GitHub : @ChaitanyaJoshiX
"""
def DrawingBoard(rows, columns):
for i in range(rows):
if i%2 == 0:
for j in range(columns):
if j%2 == 0:
if j!= columns-1:
print(" ",end="")
else:
print(" ")
else:
if j!= columns-1:
print("|",end="")
else:
print("|")
else:
print("-"*columns)
return True
"""
Testing out the Function
"""
DrawingBoard(23,125)
"""
GitHub : @ChaitanyaJoshiX
"""
|
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I': 1,'V': 5,'X': 10, 'L': 50,'C': 100,'D': 500,'M': 1000}
exception = {'IV': 4,'IX': 9,'XL': 40,'XC': 90,'CD': 400,'CM': 900}
intnum = 0
for exc in exception:
if exc in s:
intnum = intnum + exception[exc]
s = s.replace(exc, '')
arr = list(s)
for i in arr:
intnum = intnum + roman[i]
return intnum
|
class Simbolo:
def __init__(self,tipo,nombre,posicion,ambito,dimensiones=0):
self.tipo=tipo
self.nombre=nombre
self.posicion=posicion
self.ambito=ambito
self.dimensiones=dimensiones |
pytest_plugins = [
'aioclustermanager.tests.fixtures'
]
|
class Result(dict):
"""Result dict. Behaves 'immutable' to the Feature.process method.
Just a simple dict to hold the results from features.
"""
__slots__ = ()
def __setitem__(self, *args):
raise TypeError('`Result` object does not support item assignment.')
def _setitem(self, key, value):
dict.__setitem__(self, key, value)
|
"""
Simple dependencies between tests.
"""
def test_no_skip(ctestdir):
"""One test is skipped, but no other test depends on it,
so all other tests pass.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pytest.skip("explicit skip")
@pytest.mark.dependency()
def test_b():
pass
@pytest.mark.dependency(depends=["test_b"])
def test_c():
pass
@pytest.mark.dependency(depends=["test_c"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose")
result.assert_outcomes(passed=3, skipped=1, failed=0)
result.stdout.fnmatch_lines("""
*::test_a SKIPPED
*::test_b PASSED
*::test_c PASSED
*::test_d PASSED
""")
def test_skip_depend(ctestdir):
"""One test is skipped, other dependent tests are skipped as well.
This also includes indirect dependencies.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pass
@pytest.mark.dependency()
def test_b():
pytest.skip("explicit skip")
@pytest.mark.dependency(depends=["test_b"])
def test_c():
pass
@pytest.mark.dependency(depends=["test_c"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose")
result.assert_outcomes(passed=1, skipped=3, failed=0)
result.stdout.fnmatch_lines("""
*::test_a PASSED
*::test_b SKIPPED
*::test_c SKIPPED
*::test_d SKIPPED
""")
def test_fail_depend(ctestdir):
"""One test fails, other dependent tests are skipped.
This also includes indirect dependencies.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pass
@pytest.mark.dependency()
def test_b():
assert False
@pytest.mark.dependency(depends=["test_b"])
def test_c():
pass
@pytest.mark.dependency(depends=["test_c"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose")
result.assert_outcomes(passed=1, skipped=2, failed=1)
result.stdout.fnmatch_lines("""
*::test_a PASSED
*::test_b FAILED
*::test_c SKIPPED
*::test_d SKIPPED
""")
def test_named_fail_depend(ctestdir):
"""Same as test_fail_depend, but using custom test names.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency(name="a")
def test_a():
pass
@pytest.mark.dependency(name="b")
def test_b():
assert False
@pytest.mark.dependency(name="c", depends=["b"])
def test_c():
pass
@pytest.mark.dependency(name="d", depends=["c"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose")
result.assert_outcomes(passed=1, skipped=2, failed=1)
result.stdout.fnmatch_lines("""
*::test_a PASSED
*::test_b FAILED
*::test_c SKIPPED
*::test_d SKIPPED
""")
def test_explicit_select(ctestdir):
"""Explicitly select only a single test that depends on another one.
Since the other test has not been run at all, the selected test
will be skipped.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pass
@pytest.mark.dependency()
def test_b():
pass
@pytest.mark.dependency()
def test_c():
pass
@pytest.mark.dependency(depends=["test_c"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose", "test_explicit_select.py::test_d")
result.assert_outcomes(passed=0, skipped=1, failed=0)
result.stdout.fnmatch_lines("""
*::test_d SKIPPED
""")
def test_depend_unknown(ctestdir):
"""Depend on an unknown test that is not even defined in the test set.
Note that is not an error to depend on an undefined test, but the
dependent test will be skipped since the non-existent dependency
has not been run successfully.
"""
ctestdir.makepyfile("""
import pytest
@pytest.mark.dependency()
def test_a():
pass
@pytest.mark.dependency()
def test_b():
pass
@pytest.mark.dependency()
def test_c():
pass
@pytest.mark.dependency(depends=["test_x"])
def test_d():
pass
""")
result = ctestdir.runpytest("--verbose")
result.assert_outcomes(passed=3, skipped=1, failed=0)
result.stdout.fnmatch_lines("""
*::test_a PASSED
*::test_b PASSED
*::test_c PASSED
*::test_d SKIPPED
""")
|
# URI Online Judge 1117
nota1, nota2 = -1, -1
continuar = 1
while continuar == 1:
nota1, nota2 = -1, -1
while nota1 < 0 or nota1 > 10:
nota1 = float(input())
if nota1 < 0 or nota1 > 10:
print("nota invalida")
while nota2 < 0 or nota2 > 10:
nota2 = float(input())
if nota2 < 0 or nota2 > 10:
print("nota invalida")
print("media = {0:.2f}".format((nota1+nota2)/2))
continuar = -1
while continuar !=1 and continuar !=2:
print("novo calculo (1-sim 2-nao)")
continuar = int(input())
|
# -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 martin f. krafft <tctools@pobox.madduck.net>
# Released under the MIT Licence
#
_PyBaseException = BaseException
class BaseException(_PyBaseException):
pass
class InvalidDataError(BaseException):
pass
|
result = set()
for *features, label in DATA[1:]:
species = label.pop()
if species.endswith(SUFFIXES):
result.add(species)
|
# Work out the first ten digits of the sum of
# the following one-hundred 50-digit numbers.
num_str = "37107287533902102798797998220837590246510135740250\
46376937677490009712648124896970078050417018260538\
74324986199524741059474233309513058123726617309629\
91942213363574161572522430563301811072406154908250\
23067588207539346171171980310421047513778063246676\
89261670696623633820136378418383684178734361726757\
28112879812849979408065481931592621691275889832738\
44274228917432520321923589422876796487670272189318\
47451445736001306439091167216856844588711603153276\
70386486105843025439939619828917593665686757934951\
62176457141856560629502157223196586755079324193331\
64906352462741904929101432445813822663347944758178\
92575867718337217661963751590579239728245598838407\
58203565325359399008402633568948830189458628227828\
80181199384826282014278194139940567587151170094390\
35398664372827112653829987240784473053190104293586\
86515506006295864861532075273371959191420517255829\
71693888707715466499115593487603532921714970056938\
54370070576826684624621495650076471787294438377604\
53282654108756828443191190634694037855217779295145\
36123272525000296071075082563815656710885258350721\
45876576172410976447339110607218265236877223636045\
17423706905851860660448207621209813287860733969412\
81142660418086830619328460811191061556940512689692\
51934325451728388641918047049293215058642563049483\
62467221648435076201727918039944693004732956340691\
15732444386908125794514089057706229429197107928209\
55037687525678773091862540744969844508330393682126\
18336384825330154686196124348767681297534375946515\
80386287592878490201521685554828717201219257766954\
78182833757993103614740356856449095527097864797581\
16726320100436897842553539920931837441497806860984\
48403098129077791799088218795327364475675590848030\
87086987551392711854517078544161852424320693150332\
59959406895756536782107074926966537676326235447210\
69793950679652694742597709739166693763042633987085\
41052684708299085211399427365734116182760315001271\
65378607361501080857009149939512557028198746004375\
35829035317434717326932123578154982629742552737307\
94953759765105305946966067683156574377167401875275\
88902802571733229619176668713819931811048770190271\
25267680276078003013678680992525463401061632866526\
36270218540497705585629946580636237993140746255962\
24074486908231174977792365466257246923322810917141\
91430288197103288597806669760892938638285025333403\
34413065578016127815921815005561868836468420090470\
23053081172816430487623791969842487255036638784583\
11487696932154902810424020138335124462181441773470\
63783299490636259666498587618221225225512486764533\
67720186971698544312419572409913959008952310058822\
95548255300263520781532296796249481641953868218774\
76085327132285723110424803456124867697064507995236\
37774242535411291684276865538926205024910326572967\
23701913275725675285653248258265463092207058596522\
29798860272258331913126375147341994889534765745501\
18495701454879288984856827726077713721403798879715\
38298203783031473527721580348144513491373226651381\
34829543829199918180278916522431027392251122869539\
40957953066405232632538044100059654939159879593635\
29746152185502371307642255121183693803580388584903\
41698116222072977186158236678424689157993532961922\
62467957194401269043877107275048102390895523597457\
23189706772547915061505504953922979530901129967519\
86188088225875314529584099251203829009407770775672\
11306739708304724483816533873502340845647058077308\
82959174767140363198008187129011875491310547126581\
97623331044818386269515456334926366572897563400500\
42846280183517070527831839425882145521227251250327\
55121603546981200581762165212827652751691296897789\
32238195734329339946437501907836945765883352399886\
75506164965184775180738168837861091527357929701337\
62177842752192623401942399639168044983993173312731\
32924185707147349566916674687634660915035914677504\
99518671430235219628894890102423325116913619626622\
73267460800591547471830798392868535206946944540724\
76841822524674417161514036427982273348055556214818\
97142617910342598647204516893989422179826088076852\
87783646182799346313767754307809363333018982642090\
10848802521674670883215120185883543223812876952786\
71329612474782464538636993009049310363619763878039\
62184073572399794223406235393808339651327408011116\
66627891981488087797941876876144230030984490851411\
60661826293682836764744779239180335110989069790714\
85786944089552990653640447425576083659976645795096\
66024396409905389607120198219976047599490197230297\
64913982680032973156037120041377903785566085089252\
16730939319872750275468906903707539413042652315011\
94809377245048795150954100921645863754710598436791\
78639167021187492431995700641917969777599028300699\
15368713711936614952811305876380278410754449733078\
40789923115535562561142322423255033685442488917353\
44889911501440648020369068063960672322193204149535\
41503128880339536053299340368006977710650566631954\
81234880673210146739058568557934581403627822703280\
82616570773948327592232845941706525094512325230608\
22918802058777319719839450180888072429661980811197\
77158542502016545090413245809786882778948721859617\
72107838435069186155435662884062257473692284509516\
20849603980134001723930671666823555245252804609722\
53503534226472524250874054075591789781264330331690"
def large_sum():
s = 0
for i in range(100):
s += int(num_str[(i * 50):(i * 50 + 50)])
return str(s)[:10]
if __name__ == "__main__":
print(large_sum())
|
class Out():
def __init__(self):
self.log_level = 0
def print(self, msg):
print(msg)
def log(self, level, msg):
if level >= self.log_level:
return
else:
output = ""
if level == 1:
output = "[VERBOSE] "
elif level == 2:
output = "[ DEBUG ] "
print(output + msg)
def set_level(self, level):
self.log_level = level
|
number_of_test_cases = int(input().strip())
for _ in range(number_of_test_cases):
try:
a, b = map(int, input().strip().split(" "))
print(a // b)
except Exception as e:
print("Error Code:", e)
|
def printArray(array):
print(" ")
for itemNum in range(0, len(array)):
print("#" + str(itemNum) + ": " + str(array[itemNum]))
def linearSearch(array, find):
foundInd = -1
found = False
time = 0
while time < len(array) and not found:
if array[time] == find:
print("Found " + str(find) + ", taking " + str(time + 1) + " iterations")
found = True
time += 1
return foundInd
def binarySearch(array, find):
selectSort(array)
high = len(array) - 1
low = 0
time = 0
foundInd = -1
found = False
while high >= low and not found:
mid = (high + low) / 2
if array[mid] > find:
high = mid - 1
elif array[mid] < find:
low = mid + 1
else:
foundInd = mid
found = True
print("Found " + str(find) + ", taking " + str(time + 1) + " iterations")
time += 1
return found
"""
Primary advantage: performs the smallest number of swaps, so it works will when
it would be expensive to move or copy data
"""
def selectSort(array):
for index in range(0, len(array)):
#find the smallest element, starting at item
indexOfSmallest = index
for checkSizeIndex in range(index + 1, len(array)):
if array[checkSizeIndex] < array[indexOfSmallest]:
indexOfSmallest = checkSizeIndex
temp = array[index]
array[index] = array[indexOfSmallest]
array[indexOfSmallest] = temp
def insertSort(array):
for index in range(1, len(array)):
shoveIndex = index
while shoveIndex > 0 and array[shoveIndex] < array[shoveIndex - 1]:
temp = array[shoveIndex]
array[shoveIndex] = array[shoveIndex - 1]
array[shoveIndex - 1] = temp
shoveIndex -= 1
a = [5, 3, 2, 4, 1]
for i in range(1, 6):
binarySearch(a, i) |
# TODO
# Have not even started one bit but easy once get the other part done
# https://bsmg.wiki/mapping/map-format.html#events-2
# Get the Melograph
# Translate the graph to the events
# Write the results to the file
# Onset Can create a idea of where to put the beats
# https://librosa.org/doc/latest/generated/librosa.beat.beat_track.html?msclkid=bd66166baebe11ecabf9d7d7420bed35
# Pitches used for the movement going through
# https://librosa.org/doc/latest/generated/librosa.decompose.nn_filter.html
# https://github.com/ItsOrius/LiteMapper#readme
'''
You may be wondering, how do we manage to incentivize more creative mapping? Rather than just placing events based on time and location, we run a multitude of different checks to decide on where to place our events.
Beats with a high pace (more than 1 block per beat) receive a red center light, beats with a medium pace (at least 2 block per two beats) receive a blue center light, and beats with a slow pace (one block or less per two beats) receive a fading blue center light.
A change in pace results in a ring zoom.
Timestamps with more than one block at a time results in a ring rotation.
Beats with more than one block per two beats receive a ring light every beat.
Any-direction blocks and bombs result in the back lights turning on and the center lights turning off.
The laser opposite of the last (starting on the left) will flash, but the other laser will deactivate.
Both lasers activate on double notes with two beats or more of padding
''' |
class GroupHelper:
def __init__(self,app):
self.app = app
def return_to_group_page(self):
wd = self.app.wd
wd.find_element_by_link_text("group page").click()
def creator(self, group):
wd = self.app.wd
# open_gp
wd.find_element_by_link_text("groups").click()
# init_group_creator
wd.find_element_by_name("new").click()
# fill_group_form
wd.find_element_by_name("group_name").click()
wd.find_element_by_name("group_name").clear()
wd.find_element_by_name("group_name").send_keys(group.name)
wd.find_element_by_name("group_header").click()
wd.find_element_by_name("group_header").clear()
wd.find_element_by_name("group_header").send_keys(group.header)
wd.find_element_by_name("group_footer").click()
wd.find_element_by_name("group_footer").clear()
wd.find_element_by_name("group_footer").send_keys(group.footer)
# sumbit_creation_group
wd.find_element_by_name("submit").click()
self.return_to_group_page()
def delete_first_group(self):
wd = self.app.wd
# link group page
wd.find_element_by_link_text("groups").click()
# select first group
wd.find_element_by_name("selected[]").click()
# Delite
wd.find_element_by_name("delete").click()
self.return_to_group_page() |
'''
Faça um programa que leia as notas referentes às duas avaliações de um aluno. Calcule e imprima a média semestral.
Faça com que o algoritmo só aceite notas válidas (uma nota válida deve pertencer ao intervalo [0,10]). Cada nota deve
ser validada separadamente.
Entrada = A entrada contém vários valores reais, positivos ou negativos. O programa deve ser encerrado quando forem
lidas duas notas válidas.
Saída = Se uma nota inválida for lida, deve ser impressa a mensagem "nota invalida".
Quando duas notas válidas forem lidas, deve ser impressa a mensagem "media = " seguido do valor do cálculo. O valor
deve ser apresentado com duas casas após o ponto decimal.
Exemplo de Entrada Exemplo de Saída
-3.5
3.5 nota invalida
11.0 nota invalida
10.0 media = 6.75
'''
cont = 0
notas =0
while cont != 2:
nota = float(input())
if nota <0 or nota > 10:
print('nota invalida')
else:
notas += nota
cont += 1
if cont == 2:
break
print(f'media = {notas/cont:.2f}')
'''ou
while True:
try:
n1 = float(input())
if n1 < 0 or n1 > 10:
print("nota invalida")
else:
break
except ValueError:
print("nota invalida")
while True:
try:
n2 = float(input())
if n2 < 0 or n2 > 10:
print("nota invalida")
else:
break
except ValueError:
print("nota invalida")
media = (n1+n2)/2
print("media = {:.2f}".format(media)
'''
|
class category(object):
def __init__(self, id=None, account=None, name=None,
description=None, parent=None,
selectable=True, active=True):
self.id = id
self.account = account
self.name = name
self.description = description
self.parent = parent
self.selectable = selectable
self.active = active
def json_data(self):
_tmp = self.__dict__
_tmp.pop('id', None)
return _tmp
|
# Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor.
n1 = int(input('Digite um número: '))
ant = n1 - 1
suc = n1 + 1
print('O seu antecessor é {} e seu sucessor é {}'.format(ant, suc))
|
"""
Fixed and improved version based on "extracting from C++ doxygen documented file Author G.D." and py++ code.
Distributed under the Boost Software License, Version 1.0. (See
accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
"""
class doxygen_doc_extractor:
"""
Extracts Doxygen styled documentation from source or generates it from description.
"""
def __init__(self):
#for caching source
self.file_name = None
self.source = None
#__init__
def __call__(self, declaration):
try:
if self.file_name != declaration.location.file_name:
self.file_name = declaration.location.file_name
self.source = open(declaration.location.file_name).readlines()
find_block_end = False
doc_lines = []
for lcount in xrange(declaration.location.line-2, -1, -1):
line = self.source[lcount]
if not find_block_end:
try:
if line.rstrip()[-2:] == "*/":
find_block_end = True
except:
pass
if find_block_end:
try:
if line.lstrip()[:2] == "/*":
find_block_end = False
except:
pass
final_str = self.clear_str(line)
if not find_block_end and self.is_code(line):
break
if final_str:
doc_lines.insert(0, final_str)
except:
pass
finally:
if doc_lines:
final_doc_lines = [ line.replace("\n","\\n") for line in doc_lines[:-1] ]
final_doc_lines.append(doc_lines[-1].replace("\n",""))
return '"' + ''.join(final_doc_lines) + '"'
else:
return '\"\"'
#__call__()
def clear_str(self, tmp_str):
"""
Replace */! by space and \brief, @fn, \param, etc
"""
tmp_str = tmp_str.replace("/**", "")
tmp_str = tmp_str.replace("*", "")
tmp_str = tmp_str.replace("*/", "")
# tmp_str = reduce(clean, [tmp_str, '/','*','!',"\\brief","@brief","\\fn","@fn","\\ref","@ref", "\"", "\'", "\\c"])
#
# #commands list taken form : http://www.stack.nl/~dimitri/doxygen/commands.html
# replacement_list = [
# # "a",
# "addindex",
# "addtogroup",
# "anchor",
# "arg",
# "attention",
# "author",
# # "b",
# # "brief",
# "bug",
# # "c",
# "callgraph",
# "callergraph",
# "category",
# "class",
# ("code","[Code]"),
# "cond",
# "copybrief",
# "copydetails",
# "copydoc",
# "date",
# "def",
# "defgroup",
# "deprecated",
# "details",
# "dir",
# "dontinclude",
# ("dot","[Dot]"),
# "dotfile",
# "e",
# "else",
# "elseif",
# "em",
# ("endcode","[/Code]"),
# "endcond",
# ("enddot","[/Dot]"),
# "endhtmlonly",
# "endif",
# "endlatexonly",
# "endlink",
# "endmanonly",
# "endmsc",
# "endverbatim",
# "endxmlonly",
# "enum",
# "example",
# "exception",
# "extends",
# "f$",
# "f[",
# "f]",
# "f{",
# "f}",
# "file",
# # "fn",
# "headerfile",
# "hideinitializer",
# "htmlinclude",
# "htmlonly",
# "if",
# "ifnot",
# "image",
# "implements",
# "include",
# "includelineno",
# "ingroup",
# "internal",
# "invariant",
# "interface",
# "latexonly",
# "li",
# "line",
# "link",
# "mainpage",
# "manonly",
# "memberof",
# "msc",
# # "n",
# "name",
# "namespace",
# "nosubgrouping",
# "note",
# "overload",
# # "p",
# "package",
# "page",
# "par",
# "paragraph",
# "param",
# "post",
# "pre",
# # "private (PHP only)",
# # "privatesection (PHP only)",
# "property",
# # "protected (PHP only)",
# # "protectedsection (PHP only)",
# "protocol",
# # "public (PHP only)",
# # "publicsection (PHP only)",
# # "ref",
# "relates",
# "relatesalso",
# "remarks",
# "return",
# "retval",
# "sa",
# "section",
# "see",
# "showinitializer",
# "since",
# "skip",
# "skipline",
# "struct",
# "subpage",
# "subsection",
# "subsubsection",
# "test",
# "throw",
# ("todo","TODO"),
# "tparam",
# "typedef",
# "union",
# "until",
# "var",
# "verbatim",
# "verbinclude",
# "version",
# "warning",
# "weakgroup",
# "xmlonly",
# "xrefitem",
# # "$",
# # "@",
# # "\",
# # "&",
# # "~",
# # "<",
# # ">",
# # "#",
# # "%",
# ]
#
# for command in replacement_list:
# try:
# old,new = command
# except ValueError:
# old = command
# new = command.capitalize()+":"
# tmp_str = clean(tmp_str, "@"+old, new)
# tmp_str = clean(tmp_str, "\\"+old, new)
return tmp_str.lstrip()
#clean_str()
def is_code(self, tmp_str):
"""
Detects if tmp_str is code or not
"""
try:
beg = tmp_str.lstrip()[:2]
return beg != "//" and beg != "/*"
except:
pass
return False
#is_code()
#class doxygen_doc_extractor |
#Project Euler Problem-52
#Author Tushar Gayan
def f(num_1,num_2): #Checks same digit
num_list_1 = [int(i) for i in str(num_1)]
num_list_2 = [int(i) for i in str(num_2)]
num_list_1.sort();num_list_2.sort()
if num_list_1 == num_list_2:
return True
else:
return False
n = 1
while f(n,2*n) != True or f(2*n,3*n) != True or f(3*n,4*n) != True or f(4*n,5*n) != True or f(5*n,6*n) != True:
n+=1
print(n)
|
"""
breadcrumbs.namedobject
~~~~~~~~~~~~~~~~~~~~~~~
Sentinels with good representation.
:copyright: 2021 by breadcrumbs Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class NamedObject(object):
"""A class to construct named sentinels."""
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
def __hash__(self):
return id(self)
def __deepcopy__(self, memo):
return self
|
# problem : https://leetcode.com/problems/coin-change-2/
# time complexity : O(NM)
# algorithm : DP
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
if amount == 0 and len(coins) == 0:
return 1
dp = [[0] * (amount + 1)] * (len(coins) + 1)
for coinInd in range(len(coins)):
coin = coins[coinInd]
prev = dp[coinInd]
now = dp[coinInd + 1]
now[0] = 1
for ind in range(coin, amount + 1):
now[ind] = now[ind-coin] + prev[ind]
return dp[len(coins)][amount]
|
def main():
with open("day1/input.dat") as f:
expenses = [int(n) for n in f.readlines()]
result = None
for a in expenses:
for b in expenses:
if a + b == 2020:
result = a*b
break
return result
if __name__ == "__main__":
print(main()) |
d = {
'name': 'setayesh',
'last_name': 'pasanadideh',
'age': 14,
'b_p': 'tehran',
'p': print,
'wear_glass': False
}
print(d)
print(d['last_name'])
d['p']( 'amirreza') |
COCO_PERSON_SKELETON = [[2, 3], [3,4], [4, 5], [2, 6], [6,7], [7,8], [2,1]]
COCO_KEYPOINTS = [
'nose', # 1
'left_eye', # 2
'right_eye', # 3
'left_ear', # 4
'right_ear', # 5
'left_shoulder', # 6
'right_shoulder', # 7
'left_elbow', # 8
'right_elbow', # 9
'left_wrist', # 10
'right_wrist', # 11
'left_hip', # 12
'right_hip', # 13
'left_knee', # 14
'right_knee', # 15
'left_ankle', # 16
'right_ankle', # 17
]
HFLIP = {
'left_eye': 'right_eye',
'right_eye': 'left_eye',
'left_ear': 'right_ear',
'right_ear': 'left_ear',
'left_shoulder': 'right_shoulder',
'right_shoulder': 'left_shoulder',
'left_elbow': 'right_elbow',
'right_elbow': 'left_elbow',
'left_wrist': 'right_wrist',
'right_wrist': 'left_wrist',
'left_hip': 'right_hip',
'right_hip': 'left_hip',
'left_knee': 'right_knee',
'right_knee': 'left_knee',
'left_ankle': 'right_ankle',
'right_ankle': 'left_ankle',
}
COCO_PERSON_SIGMAS = [
0.026, # nose
0.025, # eyes
0.025, # eyes
0.035, # ears
0.035, # ears
0.079, # shoulders
0.079, # shoulders
0.072, # elbows
0.072, # elbows
0.062, # wrists
0.062, # wrists
0.107, # hips
0.107, # hips
0.087, # knees
0.087, # knees
0.089, # ankles
0.089, # ankles
]
def print_associations():
for j1, j2 in COCO_PERSON_SKELETON:
print(COCO_KEYPOINTS[j1 - 1], '-', COCO_KEYPOINTS[j2 - 1])
if __name__ == '__main__':
print_associations()
draw_skeletons()
|
'''
Escopo Global e Local
não se pode alterar a variavel global dentro de uma função
para uma variavel local ser alterado use a palavra global => NÃO É UMA BOA PRÁTICA NÃO DEVE-SE FAZER
'''
variavel = 'valor'
def func():
print(variavel)
def func2():
# global variavel
variavel = 'Outro valor'
print(variavel)
func()
func2()
print(variavel)
|
class StaticConnection():
def __init__(self, src, dst, bandwidth, delay, loss):
self.src = src
self.dst = dst
self.bandwidth = bandwidth
self.delay = delay
self.loss = loss |
{
'conditions' : [
[ 'skia_os != "ios"', {
'error': '<!(set GYP_DEFINES=\"skia_os=\'ios\'\")'
}],
],
'targets': [
{
'target_name': 'SimpleiOSApp',
'type': 'executable',
'mac_bundle' : 1,
'include_dirs' : [
'../experimental/iOSSampleApp/Shared',
],
'sources': [
'../src/views/ios/SkOSWindow_iOS.mm',
'../src/views/mac/SkEventNotifier.h',
'../src/views/mac/SkEventNotifier.mm',
'../experimental/iOSSampleApp/iPad/AppDelegate_iPad.h',
'../experimental/iOSSampleApp/iPad/AppDelegate_iPad.mm',
'../experimental/iOSSampleApp/iPhone/AppDelegate_iPhone.h',
'../experimental/iOSSampleApp/iPhone/AppDelegate_iPhone.mm',
'../experimental/iOSSampleApp/Shared/SkUIView.h',
'../experimental/iOSSampleApp/Shared/SkUIView.mm',
'../experimental/iOSSampleApp/Shared/skia_ios.mm',
'../experimental/SimpleiOSApp/SimpleApp.h',
'../experimental/SimpleiOSApp/SimpleApp.mm',
'../experimental/SimpleiOSApp/SimpleiOSApp-Info.plist',
],
'dependencies': [
'skia_base_libs.gyp:skia_base_libs',
'effects.gyp:effects',
'images.gyp:images',
'views.gyp:views',
'xml.gyp:xml',
],
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework',
'$(SDKROOT)/System/Library/Frameworks/CoreText.framework',
'$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
'$(SDKROOT)/System/Library/Frameworks/ImageIO.framework',
'$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework',
'$(SDKROOT)/System/Library/Frameworks/UIKit.framework',
],
'libraries!': [
#remove mac dependencies
'$(SDKROOT)/System/Library/Frameworks/Cocoa.framework',
'$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
'$(SDKROOT)/System/Library/Frameworks/QuartzCore.framework',
'$(SDKROOT)/System/Library/Frameworks/OpenGL.framework',
'$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
],
},
'xcode_settings' : {
'INFOPLIST_FILE' : '../experimental/SimpleiOSApp/SimpleiOSApp-Info.plist',
},
'xcode_config_file': '../experimental/iOSSampleApp/SkiOSSampleApp-Base.xcconfig',
'mac_bundle_resources' : [
'../experimental/SimpleiOSApp/iPad/MainWindow_iPad.xib',
'../experimental/SimpleiOSApp/iPhone/MainWindow_iPhone.xib',
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
|
vogais = {
'a': 0,
'e': 0,
'i': 0,
'o': 0,
'u': 0
}
texto = str(input('insira um texto: ')).strip().lower()
for letra in texto:
if letra in 'a':
vogais['a'] += 1
elif letra in 'e':
vogais['e'] += 1
elif letra in 'i':
vogais['i'] += 1
elif letra in 'o':
vogais['o'] += 1
elif letra in 'u':
vogais['u'] += 1
print(vogais)
|
# Copyright 2014 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
load("@io_bazel_rules_go//go/private:rules/binary.bzl", "go_binary")
load("@io_bazel_rules_go//go/private:rules/library.bzl", "go_library")
load("@io_bazel_rules_go//go/private:rules/test.bzl", "go_test")
load("@io_bazel_rules_go//go/private:rules/cgo.bzl", "setup_cgo_library")
def go_library_macro(name, srcs=None, cgo=False, cdeps=[], copts=[], clinkopts=[], **kwargs):
"""See go/core.rst#go_library for full documentation."""
cgo_info = None
if cgo:
cgo_info = setup_cgo_library(
name = name,
srcs = srcs,
cdeps = cdeps,
copts = copts,
clinkopts = clinkopts,
)
go_library(
name = name,
srcs = srcs,
cgo_info = cgo_info,
**kwargs
)
def go_binary_macro(name, srcs=None, cgo=False, cdeps=[], copts=[], clinkopts=[], **kwargs):
"""See go/core.rst#go_binary for full documentation."""
cgo_info = None
if cgo:
cgo_info = setup_cgo_library(
name = name,
srcs = srcs,
cdeps = cdeps,
copts = copts,
clinkopts = clinkopts,
)
return go_binary(
name = name,
srcs = srcs,
cgo_info = cgo_info,
**kwargs
)
def go_test_macro(name, srcs=None, cgo=False, cdeps=[], copts=[], clinkopts=[], **kwargs):
"""See go/core.rst#go_test for full documentation."""
cgo_info = None
if cgo:
cgo_info = setup_cgo_library(
name = name,
srcs = srcs,
cdeps = cdeps,
copts = copts,
clinkopts = clinkopts,
)
return go_test(
name = name,
srcs = srcs,
cgo_info = cgo_info,
**kwargs
)
|
alien_0 = {'color': 'green', 'points': 5} #create a dictionary
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
print(alien_0)
alien_0['x_position'] = 0 # add to the dictionary
alien_0['y_position'] = 25 # add to the dictionary
print(alien_0)
# starting with an empty dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# modifying values in a dictionary
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0 = {'color': 'yellow'}
print("The alien is now " + alien_0['color'] + ".")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
# removing key value pairs
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
# list of dictionaries
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
# make the list of 30 aliens
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# show the first 5 aliens
for alien in aliens [:5]:
print(alien)
print("...")
# show how many aliens have been created
print("Total number of aliens: " + str(len(aliens)))
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] == 'yellow'
alien['speed'] == 'medium'
alien['points'] == 10
for alien in aliens[0:5]:
print(alien)
print("...")
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] == 'yellow'
alien['speed'] == 'medium'
alien['points'] == 10
elif alien['color'] == 'yellow':
alien['color'] == 'red'
alien['speed'] == 'fast'
alien['points'] == 15
for alien in aliens[0:5]:
print(alien)
print("...") |
class SETTINGS:
__slots__ = ("TOKEN","DB_NAME")
def __init__(self):
self.TOKEN = '415193750:AAFNBxqmF5ow24TwzuJlzYKpYSPmt_K5p_A'
self.DB_NAME = 'vk2tl.db'
|
###############################################################################
#
# $Id$
#
###############################################################################
__all__ = ["client","constants","file_list","enq_message","messages","md_client","mw_client","pe_client"]
|
class Node(object):
def __init__(self, id):
self.id = id
self.vec = []
self.neighbours = []
def add_neighbour(self, node_id):
self.neighbours.append(node_id)
class Graph(object):
def __init__(self):
# id -> node
self.nodes = {}
self.edges = []
def add_node(self, node):
if type(node) != Node:
raise AttributeError(
"the arrgument 'node' in method add_node is not type Node !")
self.nodes[node.id] = node
def get_node(self, id):
return self.nodes[id]
def add_edge(self, edge):
self.edges.append(edge)
|
n = int(input())
matrix = [[int(n) for n in input().split(", ")] for _ in range(n)]
flat_matrix = [number for row in matrix for number in row]
print(flat_matrix)
|
INTENT = "intent"
INTENTS = "intents"
ENTITIES = "entities"
UTTERANCES = "utterances"
USE_SYNONYMS = "use_synonyms"
SYNONYMS = "synonyms"
DATA = "data"
VALUE = "value"
TEXT = "text"
ENTITY = "entity"
SLOT_NAME = "slot_name"
TRUE_POSITIVE = "true_positive"
FALSE_POSITIVE = "false_positive"
FALSE_NEGATIVE = "false_negative"
INTENT_UTTERANCES = "intent_utterances"
PARSING_ERRORS = "parsing_errors"
METRICS = "metrics"
AVERAGE_METRICS = "average_metrics"
CONFUSION_MATRIX = "confusion_matrix"
NONE_INTENT_NAME = "null"
EXACT_PARSINGS = "exact_parsings"
|
def to_hex(hh: bytes, for_c=False):
hex_values = ("{:02x}".format(c) for c in hh)
if for_c:
return "{" + ", ".join("0x{}".format(x) for x in hex_values) + "}"
else:
return " ".join(hex_values)
|
IP =input("enter your ip address ")
count_seg = 0
len_seg = 0
i = ''
for i in range(0,len(IP)):
if(IP[i] =='.'):
print("segment {} contain {} characters".format(count_seg+1,len_seg))
count_seg += 1
len_seg = 0
else:
len_seg +=1
if i != "." :
print("segment {} contain {} characters".format(count_seg+1,len_seg))
|
"""Custom errors goes here"""
class Error(Exception):
"""Base error class"""
pass
class InvalidUserInput(Error):
"""Exception raised for invalid user input"""
pass
|
numero=int(input("Digite numero: "))
if(numero%2==0):
print("el numero es par")
else:
print("el numero es impar")
|
# could be set as random or defined by node num
def getdelay(source,destination,size):
return 1
def getdownloadspeed(id):
return 1000 |
def has_print_function(tokens):
p = 0
while p < len(tokens):
if tokens[p][0] != 'FROM':
p += 1
continue
if tokens[p + 1][0:2] != ('NAME', '__future__'):
p += 1
continue
if tokens[p + 2][0] != 'IMPORT':
p += 1
continue
current = p + 3
# ignore LEFT_PARENTHESIS token
if tokens[current][0] == 'LEFT_PARENTHESIS':
current += 1
while (current < len(tokens) and tokens[current][0] == 'NAME'):
if tokens[current][1] == 'print_function':
return True
# ignore AS and NAME tokens if present
# anyway, ignore COMMA token
if current + 1 < len(tokens) and tokens[current + 1][0] == 'AS':
current += 4
else:
current += 2
p += 1
return False
def replace_print_by_name(tokens):
def is_print(token):
return token[0] == 'PRINT'
return [('NAME', 'print') if is_print(x) else x for x in tokens]
|
#*--------------------------------------------------
#* decorator.py
#* excerpt from https://refactoring.guru/design-patterns/decorator/python/example
#* ejemplo obtenido desde el canal de youtube BettaTech: https://www.youtube.com/watch?v=Ab9HxiPLryg
#*--------------------------------------------------
# COMPONENTE
class Enemy():
def take_damage(self) -> float:
pass
def movement_speed(self) -> float:
pass
# Componente concreto enemigo base
class BaseEnemy(Enemy):
def take_damage(self) -> float:
return 10
def movement_speed(self) -> float:
return 10
# Componente enemigo invencible (enemigo que no recibe daño)
class InvencibleEnemy(Enemy):
def take_damage(self) -> float:
return 0
def movement_speed(self):
return 0
# Clase decorator
class EnemyDecorator(Enemy):
_enemy: Enemy = None
def __init__(self, enemy: Enemy) -> None:
self._enemy = enemy
@property
def enemy(self) -> Enemy:
return self._enemy
def take_damage(self) -> float:
return self._enemy.take_damage()
def movement_speed(self) -> float:
return self._enemy.movement_speed()
# Concrete decorators
class HelmetDecorator(EnemyDecorator):
def take_damage(self) -> float:
return self.enemy.take_damage() * 0.5
# Concrete decorators
class BootsDecorator(EnemyDecorator):
def take_damage(self) -> float:
return self._enemy.take_damage() * 0.2
def movement_speed(self) -> float:
return self._enemy.movement_speed() * 2
if __name__ == "__main__":
# Crear un enemigo base
base_enemy = BaseEnemy()
print(f"Damage dealt to base enemy: ", base_enemy.take_damage())
print(f"Movement speed of the base enemy: ", enemy_with_helmet.movement_speed())
print()
# Le agrega un casco al enemigo
enemy_with_helmet = HelmetDecorator(base_enemy)
print(f"Damage dealt to the enemy with helmet: ", enemy_with_helmet.take_damage())
print(f"Movement speed of the enemy with helmet and boots: ", enemy_with_helmet.movement_speed())
print()
# Le agrega botas al enemigo
enemy_with_boots_helmet = BootsDecorator(enemy_with_helmet)
print(f"Damage dealt to the enemy with boots and helmet: ", enemy_with_boots_helmet.take_damage())
print(f"Movement speed of the enemy with helmet and boots: ", enemy_with_boots_helmet.movement_speed())
|
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 450
SCREEN_CENTER = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
BUTTON_COLOR = (0, 0, 0)
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 50
BALL_WIDTH = 10
BALL_HEIGHT = 10
AUDIO_ICON_WIDTH = 20
AUDIO_ICON_HEIGHT = 20
AUDIO_ICON_X = SCREEN_WIDTH - AUDIO_ICON_WIDTH
AUDIO_ICON_Y = SCREEN_HEIGHT - AUDIO_ICON_HEIGHT
|
# Source : https://leetcode.com/problems/longest-continuous-increasing-subsequence/
# Author : foxfromworld
# Date : 07/12/2021
# First attempt
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
start, ret = 0, 0
for i, num in enumerate(nums):
if i > 0 and nums[i-1] >= num:
start = i
ret = max(ret, i - start + 1)
return ret
|
def print_translation(args):
"""
Parses calls to print to convert to the C++ equivalent
Parameters
----------
args : list of str
List of arguments to add to the print statement
Returns
-------
str
The converted print statement
"""
return_str = "std::cout << "
for arg in args[:-1]:
return_str += arg + " + "
return return_str + args[-1] + " << std::endl"
def sqrt_translation(args):
"""
Parses calls to sqrt to convert to the C++ equivalent
Parameters
----------
args : list of str
List of arguments to add to the print statement
Returns
-------
str
The converted sqrt statement
"""
return "sqrt(" + args[0] + ")"
|
"""
protocolDefinitions.py
The following module consists of a list of commands or definitions to be used in the communication between devices and the control system
Michael Xynidis
Fluvio L Lobo Fenoglietto
09/26/2016
"""
# Definition Name Value Class
# ---------- ---- ----- -----
SOH = chr(0x01) # Start of Heading 0x01 STD
ENQ = chr(0x05) # Enquiry 0x05 STD
EOT = chr(0x04) # End of Transmission 0x04 STD
ACK = chr(0x06) # Positive Acknowledgement 0x06 STD
NAK = chr(0x15) # Negative Acknowledgement 0x15 STD
CAN = chr(0x18) # Cancel Current Command 0x18 STD
# Device Control Commands
# We have extended the four (4) standard "device control" commands by means of a two-byte communication protocol
DC1 = chr(0x11) # Device Control 1: Diagnostic Functions 0x11 STD
DC1_DEVICEID = chr(0x00) # Device Identification
DC1_SDCHECK = chr(0x01) # SD Card Check 0x00 ORG
# 0xFF ORG
DC2 = chr(0x12) # Device Control 2: Operational Functions 0x12 STD
DC2_SENDWAV = chr(0x00) # Send .WAV File 0x00 ORG
DC2_DELVOLATILE = chr(0x01) # Delete Volatile Files 0x01 ORG
# 0xFF ORG
DC3 = chr(0x13) # Device Control 3: Device-Specific Functions 0x13 STD
DC3_STARTREC = chr(0x00) # Start Recording 0x00 ORG
DC3_STOPREC = chr(0x01) # Stop Recording 0x01 ORG
DC3_STARTPLAY = chr(0x02) # Start Playback 0x02 ORG
DC3_STOPPLAY = chr(0x03) # Stop Playback 0x03 ORG
DC3_STARTSTREAM = chr(0x04) # Start Microphone Stream 0x04 ORG
DC3_STARTTRACKING = chr(0x05) # Start Tracking Microphone Stream for Peaks 0x05 ORG
DC3_STOPTRACKING = chr(0x06) # Stop Tracking Microphone Stream for Peaks 0x06 ORG
# 0xFF ORG
DC4 = chr(0x14) # Device Control 4: Simulation Functions 0x14 STD
DC4_NORMALHB = chr(0x00) # Playback of Normal Heart Beat 0x00 ORG
DC4_ESHMURMUR = chr(0x01) # Playback of Early Systolic Heart Beat 0x01 ORG
# 0xFF ORG
# Legend
# STD - Standard terminology / Standard reference for command
# ORG - Original or custom-made command and reference
|
"""
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1
"""
class TreeNode:
"""
Tree node class representation
"""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def checkValid(root: TreeNode, last_visited: int) -> bool:
"""
Time: O(n)
Space: O(n)
"""
if root is None:
return True
if root.left and not checkValid(root.left, last_visited):
return False
if last_visited is not None and root.val <= last_visited:
return False
last_visited = root.val
if root.right and not checkValid(root.right, last_visited):
return False
return True
def isValidBST(root: TreeNode) -> bool:
"""
Time: O(n)
Space: O(n)
"""
return checkValid(root, None)
def isValidBSTIter(root: TreeNode) -> bool:
"""
Time: O(n)
Space: O(n)
"""
if root is None:
return True
stack = [(root, float('-inf'), float('inf'))]
while stack:
node, lower_bound, upper_bound = stack.pop()
if node.val <= lower_bound or node.val >= upper_bound:
return False
if node.left:
stack.append((node.left, lower_bound, node.val))
if node.right:
stack.append((node.right, node.val, upper_bound))
return True
if __name__ == '__main__':
# Test 1
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
print(isValidBST(root))
print(isValidBSTIter(root))
# Test 2
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.right.left = TreeNode(3)
root.right.right = TreeNode(6)
print(isValidBST(root))
print(isValidBSTIter(root))
|
"""
Copyright (R) @huawei.com, all rights reserved
-*- coding:utf-8 -*-
CREATED: 2020-6-04 20:12:13
MODIFIED: 2020-6-06 14:04:45
"""
SUCCESS = 0
FAILED = 1
ACL_DEVICE = 0
ACL_HOST = 1
MEMORY_NORMAL = 0
MEMORY_HOST = 1
MEMORY_DEVICE = 2
MEMORY_DVPP = 3
# error code
ACL_ERROR_NONE = 0
ACL_ERROR_INVALID_PARAM = 100000
ACL_ERROR_UNINITIALIZE = 100001
ACL_ERROR_REPEAT_INITIALIZE = 100002
ACL_ERROR_INVALID_FILE = 100003
ACL_ERROR_WRITE_FILE = 100004
ACL_ERROR_INVALID_FILE_SIZE = 100005
ACL_ERROR_PARSE_FILE = 100006
ACL_ERROR_FILE_MISSING_ATTR = 100007
ACL_ERROR_FILE_ATTR_INVALID = 100008
ACL_ERROR_INVALID_DUMP_CONFIG = 100009
ACL_ERROR_INVALID_PROFILING_CONFIG = 100010
ACL_ERROR_INVALID_MODEL_ID = 100011
ACL_ERROR_DESERIALIZE_MODEL = 100012
ACL_ERROR_PARSE_MODEL = 100013
ACL_ERROR_READ_MODEL_FAILURE = 100014
ACL_ERROR_MODEL_SIZE_INVALID = 100015
ACL_ERROR_MODEL_MISSING_ATTR = 100016
ACL_ERROR_MODEL_INPUT_NOT_MATCH = 100017
ACL_ERROR_MODEL_OUTPUT_NOT_MATCH = 100018
ACL_ERROR_MODEL_NOT_DYNAMIC = 100019
ACL_ERROR_OP_TYPE_NOT_MATCH = 100020
ACL_ERROR_OP_INPUT_NOT_MATCH = 100021
ACL_ERROR_OP_OUTPUT_NOT_MATCH = 100022
ACL_ERROR_OP_ATTR_NOT_MATCH = 100023
ACL_ERROR_OP_NOT_FOUND = 100024
ACL_ERROR_OP_LOAD_FAILED = 100025
ACL_ERROR_UNSUPPORTED_DATA_TYPE = 100026
ACL_ERROR_FORMAT_NOT_MATCH = 100027
ACL_ERROR_BIN_SELECTOR_NOT_REGISTERED = 100028
ACL_ERROR_KERNEL_NOT_FOUND = 100029
ACL_ERROR_BIN_SELECTOR_ALREADY_REGISTERED = 100030
ACL_ERROR_KERNEL_ALREADY_REGISTERED = 100031
ACL_ERROR_INVALID_QUEUE_ID = 100032
ACL_ERROR_REPEAT_SUBSCRIBE = 100033
ACL_ERROR_STREAM_NOT_SUBSCRIBE = 100034
ACL_ERROR_THREAD_NOT_SUBSCRIBE = 100035
ACL_ERROR_WAIT_CALLBACK_TIMEOUT = 100036
ACL_ERROR_REPEAT_FINALIZE = 100037
ACL_ERROR_BAD_ALLOC = 200000
ACL_ERROR_API_NOT_SUPPORT = 200001
ACL_ERROR_INVALID_DEVICE = 200002
ACL_ERROR_MEMORY_ADDRESS_UNALIGNED = 200003
ACL_ERROR_RESOURCE_NOT_MATCH = 200004
ACL_ERROR_INVALID_RESOURCE_HANDLE = 200005
ACL_ERROR_STORAGE_OVER_LIMIT = 300000
ACL_ERROR_INTERNAL_ERROR = 500000
ACL_ERROR_FAILURE = 500001
ACL_ERROR_GE_FAILURE = 500002
ACL_ERROR_RT_FAILURE = 500003
ACL_ERROR_DRV_FAILURE = 500004
# rule for mem
ACL_MEM_MALLOC_HUGE_FIRST = 0
ACL_MEM_MALLOC_HUGE_ONLY = 1
ACL_MEM_MALLOC_NORMAL_ONLY = 2
# rule for memory copy
ACL_MEMCPY_HOST_TO_HOST = 0
ACL_MEMCPY_HOST_TO_DEVICE = 1
ACL_MEMCPY_DEVICE_TO_HOST = 2
ACL_MEMCPY_DEVICE_TO_DEVICE = 3
# input
LAST_ONE = -1
LAST_TWO = -2
type_dict = {
"bool": 0,
"int8": 1,
"int16": 2,
"int32": 4,
"int64": 8,
"uint8": 1,
"uint16": 2,
"uint32": 4,
"uint64": 8,
"float16": 2,
"float32": 4,
"float64": 8,
"float_": 8
}
NPY_BOOL = 0
NPY_BYTE = 1
NPY_UBYTE = 2
NPY_SHORT = 3
NPY_USHORT = 4
NPY_INT = 5
NPY_UINT = 6
NPY_LONG = 7
NPY_ULONG = 8
NPY_LONGLONG = 9
NPY_ULONGLONG = 10
ACL_DT_UNDEFINED = -1
ACL_FLOAT = 0
ACL_FLOAT16 = 1
ACL_INT8 = 2
ACL_INT32 = 3
ACL_UINT8 = 4
ACL_INT16 = 6
ACL_UINT16 = 7
ACL_UINT32 = 8
ACL_INT64 = 9
ACL_UINT64 = 10
ACL_DOUBLE = 11
ACL_BOOL = 12
# data format
ACL_FORMAT_UNDEFINED = -1
ACL_FORMAT_NCHW = 0
ACL_FORMAT_NHWC = 1
ACL_FORMAT_ND = 2
ACL_FORMAT_NC1HWC0 = 3
ACL_FORMAT_FRACTAL_Z = 4
ACL_DT_UNDEFINED = -1
ACL_FLOAT = 0
ACL_FLOAT16 = 1
ACL_INT8 = 2
ACL_INT32 = 3
ACL_UINT8 = 4
ACL_INT16 = 6
ACL_UINT16 = 7
ACL_UINT32 = 8
ACL_INT64 = 9
ACL_UINT64 = 10
ACL_DOUBLE = 11
ACL_BOOL = 12
acl_dtype = {
"dt_undefined": -1,
"float": 0,
"float16": 1,
"int8": 2,
"int32": 3,
"uint8": 4,
"int16": 6,
"uint16": 7,
"uint32": 8,
"int64": 9,
"double": 11,
"bool": 12
}
ACL_CALLBACK_NO_BLOCK = 0
ACL_CALLBACK_BLOCK = 1
PIXEL_FORMAT_YUV_400 = 0 # 0, YUV400 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_420 = 1 # 1, YUV420SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_420 = 2 # 2, YUV420SP NV21 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_422 = 3 # 3, YUV422SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_422 = 4 # 4, YUV422SP NV21 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_444 = 5 # 5, YUV444SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_444 = 6 # 6, YUV444SP NV21 8bit
PIXEL_FORMAT_YUYV_PACKED_422 = 7 # 7, YUV422P YUYV 8bit
PIXEL_FORMAT_UYVY_PACKED_422 = 8 # 8, YUV422P UYVY 8bit
PIXEL_FORMAT_YVYU_PACKED_422 = 9 # 9, YUV422P YVYU 8bit
PIXEL_FORMAT_VYUY_PACKED_422 = 10 # 10, YUV422P VYUY 8bit
PIXEL_FORMAT_YUV_PACKED_444 = 11 # 11, YUV444P 8bit
PIXEL_FORMAT_RGB_888 = 12 # 12, RGB888
PIXEL_FORMAT_BGR_888 = 13 # 13, BGR888
PIXEL_FORMAT_ARGB_8888 = 14 # 14, ARGB8888
PIXEL_FORMAT_ABGR_8888 = 15 # 15, ABGR8888
PIXEL_FORMAT_RGBA_8888 = 16 # 16, RGBA8888
PIXEL_FORMAT_BGRA_8888 = 17 # 17, BGRA8888
PIXEL_FORMAT_YUV_SEMI_PLANNER_420_10BIT = 18 # 18, YUV420SP 10bit
PIXEL_FORMAT_YVU_SEMI_PLANNER_420_10BIT = 19 # 19, YVU420sp 10bit
PIXEL_FORMAT_YVU_PLANAR_420 = 20 # 20, YUV420P 8bit
# images format
IMG_EXT = ['.jpg', '.JPG', '.png', '.PNG', '.bmp', '.BMP', '.jpeg', '.JPEG']
|
# -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: 2005-12-01
# Author: Ivan Vilata i Balaguer - ivan@selidor.net
#
# $Id$
#
########################################################################
"""Utility scripts for PyTables.
This package contains some modules which provide a ``main()`` function
(with no arguments), so that they can be used as scripts.
"""
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"\n",
"from finnhub.exceptions import FinnhubAPIException\n",
"from finnhub.exceptions import FinnhubRequestException\n",
"\n",
"class Client:\n",
" API_URL = \"https://finnhub.io/api/v1\"\n",
"\n",
" def __init__(self, api_key, requests_params=None):\n",
" self.api_key = api_key\n",
" self.session = self._init__session()\n",
" self._requests_params = requests_params\n",
"\n",
" def _init__session(self):\n",
" session = requests.session()\n",
" session.headers.update({'Accept': 'application/json',\n",
" 'User-Agent': 'finnhub/python'})\n",
" return session\n",
"\n",
" def _request(self, method, uri, **kwargs):\n",
" \n",
" kwargs['timeout'] = 10\n",
"\n",
" data = kwargs.get('data', None)\n",
"\n",
" if data and isinstance(data, dict):\n",
" kwargs['data'] = data\n",
" else:\n",
" kwargs['data'] = {}\n",
"\n",
" kwargs['data']['token'] = self.api_key\n",
" kwargs['params'] = kwargs['data']\n",
"\n",
" del(kwargs['data'])\n",
"\n",
" response = getattr(self.session, method)(uri, **kwargs)\n",
"\n",
" return self._handle_response(response)\n",
"\n",
" def _create_api_uri(self, path):\n",
" return \"{}/{}\".format(self.API_URL, path)\n",
"\n",
" def _request_api(self, method, path, **kwargs):\n",
" uri = self._create_api_uri(path)\n",
" return self._request(method, uri, **kwargs)\n",
"\n",
" def _handle_response(self, response):\n",
" if not str(response.status_code).startswith('2'):\n",
" raise FinnhubAPIException(response)\n",
" try:\n",
" return response.json()\n",
" except ValueError:\n",
" raise FinnhubRequestException(\"Invalid Response: {}\".format(response.text))\n",
"\n",
" def exchange(self):\n",
" return self._get(\"stock/exchange\")\n",
"\n",
" def stock_symbol(self, **params):\n",
" return self._get(\"stock/symbol\", data=params)\n",
"\n",
" def quote(self, **params):\n",
" return self._get(\"quote\", data=params)\n",
"\n",
" def stock_candle(self, **params):\n",
" return self._get(\"stock/candle\", data=params)\n",
"\n",
" def stock_tick(self, **params):\n",
" return self._get(\"stock/tick\", data=params)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "PythonData",
"language": "python",
"name": "pythondata"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
class ObjectList(object):
""""""
def __init__(self):
self._items = []
def __getitem__(self, index):
if index >= 0 and index < len(self._items):
return self._items[index]
else:
raise IndexError()
def __len__(self):
return len(self._items)
def _get_count(self):
return len(self._items)
count = property(_get_count)
|
# Comment1
class Module2(object):
command_name = 'module2'
targets = [r'products/module2_target.txt']
dependencies = [('module1_target.txt', True)]
configs = ['module2a.conf', 'module2b.conf']
|
'''
Created on 2016年2月16日
@author: Darren
'''
'''
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Examples:
Given [1, 2, 3, 4, 5],
return true.
Given [5, 4, 3, 2, 1],
return false.
'''
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
num1,num2=nums[0],max(nums)
for i in range(1,len(nums)):
if nums[i]>num2:
return True
if nums[i]>num1 and nums[i]<num2:
num2=nums[i]
if nums[i]<num1:
num1=nums[i]
return False |
class ValidDate(object):
@classmethod
def special_char(self,char):
"""Check to see if char is in a list of special date chars
"""
if(char == '-'):
return True
else:
return False
@classmethod
def check_and_store(self,char):
"""Check to see if each char is a number or a special char in my list.
"""
if(char.isnumeric()):
return True
else:
if(self.special_char(char)):
return True
else:
return False
### Look at each char and if its not a number
### or one of my special chars then delete it
### and keep going...
@classmethod
def remove_unwanted_chars(self,date):
""" Check each char and store the good ones and drop the bad ones
"""
localstore = []
for elem in date:
bval = self.check_and_store(elem)
if bval:
localstore.append(elem)
result = ''.join(localstore)
return result
if __name__ == "__main__":
testcases = ['123','2020-04-01>>','2020-05-07>>','456']
vd = ValidDate()
for ex in testcases:
print(ex)
result = vd.remove_unwanted_chars(ex)
print(result)
|
# pylint: disable=line-too-long
"""
Implement a compiler for the interpreter developed in Exercise 12, Problem 1.
The program should be compiled in a language based on operand stack.
The following operations are supported:
* ``CONST c``: push the value ``c`` on the stack,
* ``LOAD v``: load the value of the variable ``v`` and push it on the stack,
* ``STORE v``: pop a value from the stack and store it to the variable ``v``,
* ``OP {operation}``: pop two values ("left" and "right"), apply the operation and
push the result on the stack, and
* ``FUNC f``: pop a value from the stack, apply the function ``f`` on it and push the
result on the stack.
Please see `page 5`_ of the exercise for an example.
.. _page 5: https://ethz.ch/content/dam/ethz/special-interest/infk/inst-cs/lst-dam/documents/Education/Classes/Fall2019/0027_Intro/Homework/u12.pdf?page=5
"""
|
n = int(input())
arr = list(map(int, input().rstrip().split()))
arr.reverse()
for num in arr:
print(num , end=" ")
|
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def get_name(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, source, destination):
"""Assumes source and destination are of class Node"""
self.source = source
self.destination = destination
def get_source(self):
return self.source
def get_destination(self):
return self.destination
def __str__(self):
return "{} -> {}".format(self.source.get_name(), self.destination.get_name())
class Diagraph(object):
"""Edges is a dictionary mapping each node to a list of its children"""
def __init__(self):
self.edges = {}
def add_node(self, node):
if node in self.edges:
raise ValueError('Duplicate node')
else:
self.edges[node] = []
def add_edge(self, edge):
source = edge.get_source()
destination = edge.get_destination()
if not (source in self.edges and destination in self.edges):
raise ValueError('Node not in graph')
self.edges[source].append(destination)
def children_of(self, node):
return self.edges[node]
def has_node(self, node):
return node in self.edges
def get_node(self, name):
for node in self.edges:
if node.get_name() == name:
return node
raise NameError(name)
def __str__(self):
result = ''
for source in self.edges:
for destination in self.edges[source]:
result += "{} -> {}\n".format(source.get_name(), destination.get_name())
return result[:-1] # omit final newline
class Graph(Diagraph):
def add_edge(self, edge):
super().add_edge(edge)
rev = Edge(edge.get_destination(), edge.get_source())
super().add_edge(rev)
def build_city_graph(graph_type):
g = graph_type()
for name in ('Boston', 'Providence', 'New York', 'Chicago', 'Denver', 'Phoenix', 'Los Angeles'):
g.add_node(Node(name))
g.add_edge(Edge(g.get_node('Boston'), g.get_node('Providence')))
g.add_edge(Edge(g.get_node('Boston'), g.get_node('New York')))
g.add_edge(Edge(g.get_node('Providence'), g.get_node('Boston')))
g.add_edge(Edge(g.get_node('Providence'), g.get_node('New York')))
g.add_edge(Edge(g.get_node('New York'), g.get_node('Chicago')))
g.add_edge(Edge(g.get_node('Chicago'), g.get_node('Denver')))
g.add_edge(Edge(g.get_node('Denver'), g.get_node('Phoenix')))
g.add_edge(Edge(g.get_node('Denver'), g.get_node('New York')))
g.add_edge(Edge(g.get_node('Chicago'), g.get_node('Phoenix')))
g.add_edge(Edge(g.get_node('Los Angeles'), g.get_node('Boston')))
return g
print(build_city_graph(Diagraph), '\n\n', build_city_graph(Graph), '\n\n')
def print_path(path):
"""Assumes path is a list of nodes"""
result = ''
for i in range(len(path)):
result += str(path[i])
if i is not len(path) - 1:
result += ' -> '
return result
def DFS(graph, start, end, path, shortest, to_print=False):
"""Depth First Search.
Assumes graph is a Diagraph; start and end are nodes;
path and shortest are lists of nodes.
Returns shortest path from start to end in graph"""
path += [start]
if to_print:
print("Current DFS path:", print_path(path))
if start == end:
return path
for node in graph.children_of(start):
if node not in path: # avoid cycles
if shortest is None or len(path) < len(shortest):
new_path = DFS(graph, node, end, path, shortest, to_print)
if new_path is not None:
shortest = new_path
elif to_print:
print("Already visited", node)
return shortest
def shortest_path(graph, start, end, to_print=False):
"""Assumes graph is a Diagraph; start and end are nodes
Returns a shortest path from start to end in graph"""
return DFS(graph, start, end, [], None, to_print)
def test_shortest_path(source, destination):
g = build_city_graph(Diagraph)
sp = shortest_path(g, g.get_node(source), g.get_node(destination), to_print=True)
if sp is not None:
print("Shortest path from {} to {} is {}.".format(source, destination, print_path(sp)))
else:
print("There is no path from {} to {}".format(source, destination))
test_shortest_path('Chicago', 'Boston')
test_shortest_path('Boston', 'Phoenix')
def BFS(graph, start, end, to_print=False):
"""Breadth-first Search.
Assumes graph is a Diagraph; start and end are nodes.
Returns a shortest path from start to end in graph"""
initial_path = [start]
path_queue = [initial_path]
while len(path_queue) is not 0:
# Get and remove oldest element in path_queue
temporary_path = path_queue.pop(0)
if to_print:
print("Current BFS path:", print_path(temporary_path))
last_node = temporary_path[-1]
if last_node == end:
return temporary_path
for next_node in graph.children_of(last_node):
if next_node not in temporary_path:
new_path = temporary_path + [next_node]
path_queue.append(new_path)
return None
def shortest_path(graph, start, end, to_print=False):
"""Assumes graph is a Diagraph; start and end are nodes
Returns a shortest path from start to end in graph"""
return BFS(graph, start, end, to_print)
test_shortest_path('Boston', 'Phoenix')
class WeightedEdge(Edge):
def __init__(self, source, destination, weight):
super().__init__(source, destination)
self.weight = weight
def get_weight(self):
return self.weight
def __str__(self):
return "{}->{} ({})".format(super().get_source(), super().get_destination(), self.get_weight())
|
"""
You want to find people who have as much exposure to different cultures as yourself.
Complete the uncommon_cities helper that takes the cities you have visited (my_cities) and the cities the other person has visited (other_cities) and returns the number of cities that both sequences do NOT have in common.
So given [A B C] and [B C D] it should return 2 because only A and D are different.
You can loop through both sequences but maybe there is a more concise way to do it?
"""
def uncommon_cities(my_cities, other_cities):
"""Compare my_cities and other_cities and return the number of different
cities between the two"""
return len(list(set(my_cities) ^ set(other_cities)))
|
M = ContF = cont = 0
while True:
idade = int(input('Idade:'))
sexo = 't'
while sexo not in 'mf':
sexo = str(input('Sexo:[M/F] ')).lower().strip()[0]
if idade > 18:
cont+=1
if sexo in 'f' and idade < 20:
ContF+= 1
if sexo in 'm':
M += 1
escolha = 't'
while escolha not in 'sn':
escolha = str(input('Quer continuar?[S/N]:'))
if escolha == 'n':
break
print(f'''Tem {ContF} mulheres com menos de 20 anos
Ao todo são {M} homens cadastrados
Tem {cont} pessoas com mais de 18 anos''')
|
## Advent of Code 2018: Day 14
## https://adventofcode.com/2018/day/14
## Jesse Williams
## Answers: [Part 1]: 8176111038, [Part 2]: 20225578
INPUT = 890691
def createNewRecipes(recipes, elves):
newRcpSum = recipes[elves[0]] + recipes[elves[1]] # add current recipes together
newRcpDigits = list(map(int, list(str(newRcpSum)))) # separate digits into a list
return newRcpDigits
def chooseNewCurrentRecipes(recipes, elves):
newElves = [0, 0]
for i, elf in enumerate(elves):
newElves[i] = (elves[i] + (1 + recipes[elves[i]])) % len(recipes)
return newElves
if __name__ == "__main__":
## Part 1
recipes = [3, 7]
elves = [0, 1] # stores the index of the current recipe for each elf
numRecipes = INPUT
numRecipesMade = 0
numExtraRecipes = 10
while numRecipesMade < numRecipes + numExtraRecipes:
newRecipes = createNewRecipes(recipes, elves) # create new recipes and add them to the end of the list
recipes += newRecipes
elves = chooseNewCurrentRecipes(recipes, elves) # update the current recipe for each elf
numRecipesMade += len(newRecipes)
extraRecipes = recipes[numRecipes:numRecipes+numExtraRecipes]
print('The next {} recipes after an initial {} are: {}'.format(numExtraRecipes, numRecipes, ''.join(map(str, extraRecipes))))
## Part 2
# Since adding two single digit numbers together can result in either a 1- or 2-digit number, we check both possibilities
recipes = [3, 7]
elves = [0, 1] # stores the index of the current recipe for each elf
done = False
targetSequenceInt = INPUT
targetSequence = list(map(int, list(str(targetSequenceInt))))
while not done:
recipes += createNewRecipes(recipes, elves) # create new recipes and add them to the end of the list
elves = chooseNewCurrentRecipes(recipes, elves) # update the current recipe for each elf
if (recipes[-len(targetSequence):] == targetSequence):
recipesToLeft = len(recipes[:-len(targetSequence)])
done = True
elif (recipes[-len(targetSequence)-1:-1] == targetSequence):
recipesToLeft = len(recipes[:-len(targetSequence)-1])
done = True
print("There are {} recipes to the left of the first instance of the sequence '{}'.".format(recipesToLeft, targetSequenceInt))
|
#!/usr/local/bin/python3.6
def is_ztest(m):
if int(m.author.id) == int(zigID):
return True
else:
return False
|
def read_matrix(c, r):
matrix = []
for _ in range(c):
row = input().split(' ')
matrix.append(row)
return matrix
c, r = [int(n) for n in input().split(' ')]
matrix = read_matrix(c, r)
matches = 0
for col in range(c - 1):
for row in range(r - 1):
if matrix[col][row] == matrix[col][row + 1] == matrix[col + 1][row] == matrix[col + 1][row + 1]:
matches += 1
print(matches) |
# Option for variable 'simulation_type':
# 1: cylindrical roller bearing
# 2:
# 3: cylindrical roller thrust bearing
# 4: ball on disk (currently not fully supported)
# 5: pin on disk
# 6: 4 ball
# 7: ball on three plates
# 8: ring on ring
# global simulation setup
simulation_type = 5 # one of the above types
simulation_name = 'PinOnDisk'
auto_print = True # True or False
auto_plot = True
auto_report = False # reporting currently not supported, don't change
# global test setup / bearing information
tribo_system_name = 'foo'
number_pins = 1
sliding_diameter = 50 # in mm, sliding diameter on disc
# Pin (CB1)
e_cb1 = 210000 # young's modulus in MPa
ny_cb1 = 0.3 # poisson number in MPa
diameter_cb1 = 12.7
length_cb1 = 12.7 # in mm
type_profile_cb1 = 'Circle' # 'None', 'Circle', 'File'
path_profile_cb1 = '' # path to profile.txt file required if TypeProfile == 'File'
profile_radius_cb1 = 6.35 # input required if TypeProfile == 'Circle'
# Disk (CB2)
e_cb2 = 210000 # young's modulus in MPa
ny_cb2 = 0.3 # poisson number in MPa
diameter_cb2 = 50
# Loads
global_force = 50 # in N
rot_velocity1 = 50 # in rpm
# Mesh
res_x = 41 # data points along roller length
res_y = 41 # data points along roller width
|
BUSINESS_METRICS_VIEW_CONFIG = {
'Write HBase' : [['write operation', 'Write/HBase'],
['log length', 'Write/Log'],
['memory/thread', 'Write/MemoryThread'],
],
'Read HBase' : [['read operation', 'Read/HBase'],
['result size', 'Read/ResultSize'],
['memory/thread', 'Read/MemoryThread'],
],
}
ONLINE_METRICS_MENU_CONFIG = {
'Online Write' : [['Qps', 'Write/Qps'],
['HBase Latency', 'Write/HBase Latency'],
['Total Latency', 'Write/Total Latency'],
['WriteFail', 'Write/WriteFail'],
['HTablePool', 'Write/HTablePool'],
['Replication', 'Write/Replication'],
['Exception', 'Write/Exception'],
],
'Online Read' : [['Qps', 'Read/Qps'],
['HBase Latency', 'Read/HBase Latency'],
['Total Latency', 'Read/Total Latency'],
['ReadFail', 'Read/ReadFail'],
['HTablePool', 'Read/HTablePool'],
['Exception', 'Read/Exception'],
],
}
ONLINE_METRICS_COUNTER_CONFIG = {
}
ONLINE_METRICS_TITLE_CONFIG = {
}
ONLINE_METRICS_ENDPOINT_CONFIG = {
}
|
n=int(input())
for i in range(1,n):
if i+sum(map(int,list(str(i))))==n:
print(i)
exit()
print(0) |
"""
Doctests
You have the option to write tests into your docstring in python.
"""
def add(a, b):
"""
>>> add(2, 3)
5
>>> add(100, 200)
300
"""
return a + b
# command line command to run the doctests:
# python -m doctest -v filename.py |
edge_array = [];
par =[0,0,0,0,0,0]
for par[0] in range(0,3):
for par[1] in range(0,3):
for par[2] in range(0,3):
for par[3] in range(0,3):
for par[4] in range(0,3):
for par[5] in range(0,3):
edge_array.append(str(par[0])+" "+str(par[1])+" "+str(par[2])+" "+str(par[3])+" "+str(par[4])+" "+str(par[5])+" 0")
i = 0
par2 =[0,0,0,0,0,0]
for par[0] in range(0,3):
for par[1] in range(0,3):
for par[2] in range(0,3):
for par[3] in range(0,3):
for par[4] in range(0,3):
for par[5] in range(0,3):
index = par[0]+par[1]*3+par[2]*9+par[3]*27+par[4]*81+par[5]*243
if (index > i and index < 728):
try:
edge_array[index] = str(par[5])+" "+str(par[4])+" "+str(par[3])+" "+str(par[2])+" "+str(par[1])+" "+str(par[0])+" -1"
except ValueError:
pass
j = 0
for par_each in par:
if (par_each == 1):
par2[j] = 2
elif (par_each == 2):
par2[j] = 1
else:
par2[j] = 0
j += 1
index2 = par2[0]*243+par2[1]*81+par2[2]*27+par2[3]*9+par2[4]*3+par2[5]
if (index2 > i and index2 < 728):
try:
edge_array[index2] = str(par2[0])+" "+str(par2[1])+" "+str(par2[2])+" "+str(par2[3])+" "+str(par2[4])+" "+str(par2[5])+" -1"
except ValueError:
pass
i += 1
i=0
for edge_each in edge_array:
print(edge_array[i])
i += 1 |
""" Steinhaus-Johnson-Trotter algorithm """
def SJT_gen(n: int):
"""Generate the swaps for the Steinhaus-Johnson-Trotter algorithm.
Args:
n (int): [description]
Returns:
[type]: [description]
Yields:
[type]: [description]
"""
if n == 2:
yield 0
yield 0 # tricky part: return to the origin
return
gen = SJT_gen(n - 1)
for x in gen:
for i in range(n - 2, -1, -1): # downward
yield i
yield x + 1
for i in range(n - 1): # upward
yield i
yield next(gen) # tricky part
def SJT(n: int):
"""Generate the swaps for the Steinhaus-Johnson-Trotter algorithm.
Args:
n (int): [description]
Returns:
[type]: [description]
Yields:
[type]: [description]
"""
perm = list(range(n))
for x in SJT_gen(n):
yield perm
perm[x], perm[x + 1] = perm[x + 1], perm[x]
def main():
fruits = list("🍉🍌🍇🍏")
print(" 0 1 2 3")
for lst in SJT(4):
mylst = list(fruits[i] for i in lst)
print("".join(mylst))
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
class Node(object):
def __init__(self, type_, value, children=None):
self.type = type_ # Options: 'operator', 'identifier', 'value'
self.value = value
self.children = children or []
def dump(self, recursive=False):
"""Return a formatted dump of the tree in current node.
:param recursive: whether show children recursively
"""
if recursive:
dumped_children = ', '.join(child.dump(recursive)
for child in self.children)
else:
dumped_children = '...'
return '{}(value={!r}, children={})'.format(
self.type.capitalize(), self.value,
'[{}]'.format(dumped_children if self.children else '')
)
__repr__ = __str__ = dump
@staticmethod
def merge_all_children(nodes):
"""Merge all the children of `nodes` together.
"""
merged = []
for node in nodes:
merged.extend(node.children)
return merged
def resemble(self, node):
"""Whether current node has the same *type* and *value* with `node`.
:param node: the node to compare with
"""
return self.type == node.type and self.value == node.value
def shift_up_grandchildren(self):
"""Remove the children of current node, and merge all the original
grandchildren together as the new children.
"""
self.children = self.merge_all_children(self.children)
return self
def copy(self):
"""Deep copy the tree in current code."""
children = [child.copy() for child in self.children]
return Node(self.type, self.value, children)
def walk(self, parent=None, index=None):
"""Recursively yield all descendant nodes in the tree starting at
current node (including current node).
:param parent: the parent node of current node
:param index: the index of current node in parent's children
"""
yield (parent, index, self)
for i, child in enumerate(self.children):
for grandchild in child.walk(self, i):
yield grandchild
|
levels = {
1: {
'ship': (80, 60),
'enemies': ((24, 24), (50, 24), (100, 24), (120, 24))
},
2: {
'ship': (80, 110),
'enemies': ((10, 10), (80, 10), (150, 10),
(10, 30), (80, 30), (150, 30))
},
3: {
'ship': (10, 60),
'enemies': ((90, 10), (90, 50), (90, 90),
(110, 10), (110, 50), (110, 90),
(130, 10), (130, 50), (130, 90),
)
},
4: {
'ship': (80, 110),
'enemies': ((10, 10), (40, 10), (80, 10), (110, 10), (150, 10),
(10, 30), (40, 30), (80, 30), (110, 30), (150, 30), )
},
5: {
'ship': (10, 60),
'enemies': ((80, 10), (103, 10), (123, 16), (137, 32),
(144, 61), (139, 80), (121, 104), (105, 110),
(79, 36), (101, 48), (99, 74), (79, 84),
)
},
6: {
'ship': (10, 10),
'enemies': ((40, 20), (60, 20), (80, 20), (100, 20), (120, 20), (140, 20),
(60, 40), (80, 40), (100, 40), (120, 40), (140, 40),
(80, 60), (100, 60), (120, 60), (140, 60),
(100, 80), (120, 80), (140, 80),
(100, 100), (120, 100), (140, 100),
)
},
7: {
'ship': (80, 110),
'enemies': ((10, 10), (30, 10), (50, 10), (70, 10), (90, 10),
(110, 10), (130, 10), (150, 10),
(10, 30), (30, 30), (50, 30), (70, 30), (90, 30),
(110, 30), (130, 30), (150, 30),
(60, 50), (80, 50), (100, 50)
)
},
}
|
class HttpRequest:
def __init__(self, path, method, headers, path_params, query_params, body):
self.path = path
self.method = method
self.headers = headers
self.path_params = path_params
self.query_params = query_params
self.body = body
|
"""
3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min
which returns the minimum eiement? Push, pop and min should ail operate in 0 ( 1 ) time.
"""
"""
Solution --> keep track of what is min at each stage of opertaion
"""
class Stack:
def __init__(self):
self.items = []
self.mins = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
if not self.mins:
self.mins.append(data)
return
if self.mins[-1] > data:
self.mins.append(data)
else:
self.mins.append(self.mins[-1])
def pop(self):
self.mins.pop(-1)
return self.items.pop(-1)
def min(self):
return self.mins[-1]
stack = Stack()
stack.push(2)
stack.push(5)
stack.push(1)
print(stack.min())
stack.pop()
print(stack.min())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.